diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index 506d0f66af47..f479f62bd580 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -176,7 +176,7 @@ com.azure:azure-monitor-query-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-openrewrite;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-perf-test-parent;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-quantum-jobs;1.0.0-beta.1;1.0.0-beta.2 -com.azure:azure-search-documents;11.8.0;11.9.0-beta.2 +com.azure:azure-search-documents;11.8.0;12.0.0-beta.1 com.azure:azure-search-perf;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-security-attestation;1.1.37;1.2.0-beta.1 com.azure:azure-security-confidentialledger;1.0.33;1.1.0-beta.2 diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index d6a84b45680b..180db3544bf9 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -316,11 +316,9 @@ Let's explore them with a search for a "luxury" hotel. 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); +for (SearchResult searchResult : SEARCH_CLIENT.search(new SearchOptions().setSearchText("luxury"))) { + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", doc.get("HotelId"), doc.get("HotelName")); } ``` @@ -330,9 +328,7 @@ Define a `Hotel` class. ```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; public String getId() { @@ -358,11 +354,9 @@ public static class Hotel { Use it in place of `SearchDocument` when querying. ```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); +for (SearchResult searchResult : SEARCH_CLIENT.search(new SearchOptions().setSearchText("luxury"))) { + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", doc.get("Id"), doc.get("Name")); } ``` @@ -375,11 +369,11 @@ 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() +SearchOptions options = new SearchOptions().setSearchText("luxury") .setFilter("rating ge 4") .setOrderBy("rating desc") .setTop(5); -SearchPagedIterable searchResultsIterable = SEARCH_CLIENT.search("luxury", options, Context.NONE); +SearchPagedIterable searchResultsIterable = SEARCH_CLIENT.search(options); // ... ``` @@ -394,7 +388,7 @@ There are multiple ways of preparing search fields for a search index. For basic to configure the field of model class. ```java readme-sample-createIndexUseFieldBuilder -List searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null); +List searchFields = SearchIndexClient.buildSearchFields(Hotel.class); SEARCH_INDEX_CLIENT.createIndex(new SearchIndex("index", searchFields)); ``` @@ -402,50 +396,48 @@ 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) +searchFieldList.add(new SearchField("HotelId", SearchFieldDataType.STRING) .setKey(true) .setFilterable(true) .setSortable(true)); - -searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING) +searchFieldList.add(new SearchField("HotelName", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true)); -searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING) +searchFieldList.add(new SearchField("Description", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE)); -searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) +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) +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) + new SearchField("StateProvince", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) .setSortable(true), - new SearchField("country", SearchFieldDataType.STRING) + new SearchField("Country", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) .setSortable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) + new SearchField("PostalCode", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) - .setSortable(true) - )); + .setSortable(true))); // Prepare suggester. -SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName")); +SearchSuggester suggester = new SearchSuggester("sg", "hotelName"); // Prepare SearchIndex with index name and search fields. -SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester); +SearchIndex index = new SearchIndex("hotels", searchFieldList).setSuggesters(suggester); // Create an index SEARCH_INDEX_CLIENT.createIndex(index); ``` @@ -457,8 +449,8 @@ your index if you already know the key. You could get the key from a query, for 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()); +Map hotel = SEARCH_CLIENT.getDocument("1").getAdditionalProperties(); +System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.get("Id"), hotel.get("Name")); ``` ### Adding documents to your index @@ -468,9 +460,16 @@ There are [a few special rules for merging](https://learn.microsoft.com/rest/api 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"))); +Map hotel = new LinkedHashMap<>(); +hotel.put("Id", "783"); +hotel.put("Name", "Upload Inn"); + +Map hotel2 = new LinkedHashMap<>(); +hotel2.put("Id", "12"); +hotel2.put("Name", "Renovated Ranch"); +IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(hotel), + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(hotel2)); SEARCH_CLIENT.indexDocuments(batch); ``` @@ -484,10 +483,10 @@ The examples so far have been using synchronous APIs, but we provide full suppor to use [SearchAsyncClient](#create-a-searchclient). ```java readme-sample-searchWithAsyncClient -SEARCH_ASYNC_CLIENT.search("luxury") +SEARCH_ASYNC_CLIENT.search(new SearchOptions().setSearchText("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()); + Map hotel = result.getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.get("Id"), hotel.get("Name")); }); ``` @@ -528,7 +527,7 @@ Any Search API operation that fails will throw an [`HttpResponseException`][Http ```java readme-sample-handleErrorsWithSyncClient try { - Iterable results = SEARCH_CLIENT.search("hotel"); + Iterable results = SEARCH_CLIENT.search(new SearchOptions().setSearchText("hotel")); } catch (HttpResponseException ex) { // The exception contains the HTTP status code and the detailed message // returned from the search service diff --git a/sdk/search/azure-search-documents/assets.json b/sdk/search/azure-search-documents/assets.json index 87fd4e5ebeec..75cc50246a1f 100644 --- a/sdk/search/azure-search-documents/assets.json +++ b/sdk/search/azure-search-documents/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "java", "TagPrefix": "java/search/azure-search-documents", - "Tag": "java/search/azure-search-documents_3eb1fda9ef" + "Tag": "java/search/azure-search-documents_fd0a3d83ca" } diff --git a/sdk/search/azure-search-documents/checkstyle-suppressions.xml b/sdk/search/azure-search-documents/checkstyle-suppressions.xml index 0980dfeec582..1903db19265a 100644 --- a/sdk/search/azure-search-documents/checkstyle-suppressions.xml +++ b/sdk/search/azure-search-documents/checkstyle-suppressions.xml @@ -3,12 +3,11 @@ - - - - - - + + + + + diff --git a/sdk/search/azure-search-documents/customizations/pom.xml b/sdk/search/azure-search-documents/customizations/pom.xml new file mode 100644 index 000000000000..23dcd3377ae8 --- /dev/null +++ b/sdk/search/azure-search-documents/customizations/pom.xml @@ -0,0 +1,21 @@ + + + 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/customizations/src/main/java/SearchCustomizations.java b/sdk/search/azure-search-documents/customizations/src/main/java/SearchCustomizations.java new file mode 100644 index 000000000000..9c283997d202 --- /dev/null +++ b/sdk/search/azure-search-documents/customizations/src/main/java/SearchCustomizations.java @@ -0,0 +1,88 @@ +// 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.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.FieldDeclaration; +import com.github.javaparser.ast.body.MethodDeclaration; +import com.github.javaparser.ast.body.VariableDeclarator; +import com.github.javaparser.ast.nodeTypes.NodeWithMembers; +import org.slf4j.Logger; + +import java.util.Arrays; + +/** + * Contains customizations for Azure AI Search code generation. + */ +public class SearchCustomizations extends Customization { + @Override + public void customize(LibraryCustomization libraryCustomization, Logger logger) { + PackageCustomization documents = libraryCustomization.getPackage("com.azure.search.documents"); + PackageCustomization indexes = libraryCustomization.getPackage("com.azure.search.documents.indexes"); + PackageCustomization knowledge = libraryCustomization.getPackage("com.azure.search.documents.knowledgebases"); + + hideGeneratedSearchApis(documents); + + addSearchAudienceScopeHandling(documents.getClass("SearchClientBuilder"), logger); + addSearchAudienceScopeHandling(indexes.getClass("SearchIndexClientBuilder"), logger); + addSearchAudienceScopeHandling(indexes.getClass("SearchIndexerClientBuilder"), logger); + addSearchAudienceScopeHandling(knowledge.getClass("KnowledgeBaseRetrievalClientBuilder"), logger); + } + + // Weird quirk in the Java generator where SearchOptions is inferred from the parameters of searchPost in TypeSpec, + // where that class doesn't actually exist in TypeSpec so it requires making the searchPost API public which we + // don't want. This customization hides the searchPost APIs that were exposed. + private static void hideGeneratedSearchApis(PackageCustomization documents) { + for (String className : Arrays.asList("SearchClient", "SearchAsyncClient")) { + documents.getClass(className).customizeAst(ast -> ast.getClassByName(className).ifPresent(clazz -> { + clazz.getMethodsByName("searchWithResponse") + .stream() + .filter(method -> method.isAnnotationPresent("Generated")) + .forEach(MethodDeclaration::setModifiers); + + clazz.getMethodsByName("autocompleteWithResponse") + .stream() + .filter(method -> method.isAnnotationPresent("Generated")) + .forEach(MethodDeclaration::setModifiers); + + clazz.getMethodsByName("suggestWithResponse") + .stream() + .filter(method -> method.isAnnotationPresent("Generated")) + .forEach(MethodDeclaration::setModifiers); + })); + } + } + + // Adds SearchAudience handling to generated builders. This is a temporary fix until + // https://github.com/microsoft/typespec/issues/9458 is addressed. + private static void addSearchAudienceScopeHandling(ClassCustomization customization, Logger logger) { + customization.customizeAst(ast -> ast.getClassByName(customization.getClassName()).ifPresent(clazz -> { + // Make sure 'DEFAULT_SCOPES' exists before adding instance level 'scopes' + if (clazz.getMembers().stream().noneMatch(declaration -> declaration.isFieldDeclaration() + && "DEFAULT_SCOPES".equals(declaration.asFieldDeclaration().getVariable(0).getNameAsString()))) { + logger.info( + "Client builder didn't contain field 'DEFAULT_SCOPES', skipping adding support for SearchAudience"); + return; + } + + // Add mutable instance 'String[] scopes' with an initialized value of 'DEFAULT_SCOPES'. Also, add the + // Generated annotation so this will get cleaned up automatically in the future when the TypeSpec issue is + // resolved. + clazz.addMember(new FieldDeclaration().setModifiers(Modifier.Keyword.PRIVATE) + .addMarkerAnnotation("Generated") + .addVariable(new VariableDeclarator().setName("scopes").setType("String[]") + .setInitializer("DEFAULT_SCOPES"))); + + // Get the 'createHttpPipeline' method and change the 'BearerTokenAuthenticationPolicy' to use 'scopes' + // instead of 'DEFAULT_SCOPES' when creating the object. + clazz.getMethodsByName("createHttpPipeline").forEach(method -> method.getBody().ifPresent(body -> + method.setBody(StaticJavaParser.parseBlock(body.toString().replace("DEFAULT_SCOPES", "scopes"))))); + })); + } +} diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index 7399e0580391..608c5b0baad7 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -16,7 +16,7 @@ com.azure azure-search-documents - 11.9.0-beta.2 + 12.0.0-beta.1 jar @@ -28,26 +28,28 @@ 0.35 - --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-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.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.testingmodels.environment.models=com.fasterxml.jackson.databind + --add-opens com.azure.search.documents/com.azure.search.documents.testingmodels.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-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 + --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 true @@ -71,11 +73,6 @@ azure-core-http-netty 1.16.3 - - com.azure - azure-core-serializer-json-jackson - 1.6.3 - - *
- * 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; + @Generated + private final SearchClientImpl serviceClient; /** - * 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. + * Initializes an instance of SearchAsyncClient class. * - * @return the indexName value. + * @param serviceClient the service client implementation. */ - public String getIndexName() { - return this.indexName; + @Generated + SearchAsyncClient(SearchClientImpl serviceClient) { + this.serviceClient = serviceClient; } /** - * Gets the {@link HttpPipeline} powering this client. + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. * * @return the pipeline. */ HttpPipeline getHttpPipeline() { - return this.httpPipeline; + return serviceClient.getHttpPipeline(); } /** - * Gets the endpoint for the Azure AI Search service. + * Gets the endpoint used to communicate with the Azure AI Search service. * - * @return the endpoint value. + * @return The endpoint. */ public String getEndpoint() { - return this.endpoint; + return serviceClient.getEndpoint(); } /** - * 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());
-     *         }
-     *     });
-     * 
- * + * Gets the name of the Azure AI Search index. * - * @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 + * @return The index name. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono uploadDocuments(Iterable documents) { - return uploadDocumentsWithResponse(documents, null).map(Response::getValue); + public String getIndexName() { + return serviceClient.getIndexName(); } /** - * Uploads a collection of documents to the target index. + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. * - *

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 + * @return The service version. */ - @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); + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); } /** - * 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}). + * Queries the number of documents in the index. + *

Response Body Schema

* - *

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());
-     *         }
-     *     });
+     * {@code
+     * long
+     * }
      * 
- * * - * @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 + * @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 64-bit integer along with {@link Response} on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono mergeDocuments(Iterable documents) { - return mergeDocumentsWithResponse(documents, null).map(Response::getValue); + public Mono> getDocumentCountWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getDocumentCountWithResponseAsync(requestOptions); } /** - * 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.

+ * 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", "innerHits", "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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

* - * *
-     * 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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
      * 
- * * - * @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 + * @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> 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); + Mono> searchGetWithResponse(RequestOptions requestOptions) { + return this.serviceClient.searchGetWithResponseAsync(requestOptions); } /** - * 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}). + * 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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

* - *

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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: Object (Required)
+     *     }
+     * }
+     * }
      * 
- * * - * @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 + * @param key The key of the document to retrieve. + * @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 mergeOrUploadDocuments(Iterable documents) { - return mergeOrUploadDocumentsWithResponse(documents, null).map(Response::getValue); + public Mono> getDocumentWithResponse(String key, RequestOptions requestOptions) { + return this.serviceClient.getDocumentWithResponseAsync(key, requestOptions); } /** - * 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}). + * 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 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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
      * 
- * * - * @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 + * @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 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> 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); + Mono> suggestGetWithResponse(String searchText, String suggesterName, + RequestOptions requestOptions) { + return this.serviceClient.suggestGetWithResponseAsync(searchText, suggesterName, requestOptions); } /** - * Deletes a collection of documents from the target index. + * Sends a batch of document write actions to the index. + *

Request Body Schema

* - *

Code Sample

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

Delete dynamic SearchDocument.

+ *

Response Body Schema

* - * *
-     * 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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @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 + * @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 deleteDocuments(Iterable documents) { - return deleteDocumentsWithResponse(documents, null).map(Response::getValue); + Mono> indexWithResponse(BinaryData batch, RequestOptions requestOptions) { + return this.serviceClient.indexWithResponseAsync(batch, requestOptions); } /** - * Deletes a collection of documents from the target index. - * - *

Code Sample

- * - *

Delete dynamic SearchDocument.

+ * 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

* - * *
-     * 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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @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 + * @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 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> 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); + Mono> autocompleteGetWithResponse(String searchText, String suggesterName, + RequestOptions requestOptions) { + return this.serviceClient.autocompleteGetWithResponseAsync(searchText, suggesterName, requestOptions); } /** - * 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 + * Queries the number of documents in the index. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 64-bit integer on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono indexDocuments(IndexDocumentsBatch batch) { - return indexDocumentsWithResponse(batch, null).map(Response::getValue); + public Mono getDocumentCount() { + // Generated convenience method for getDocumentCountWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDocumentCountWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(Long.class)); } /** - * 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 + * Searches for documents in the index. + * + * @param querySourceAuthorization Token identifying the user for which the query is being executed. This token is + * used to enforce security restrictions on documents. + * @param enableElevatedRead A value that enables elevated read that bypass document level permission checks for the + * query operation. + * @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> indexDocumentsWithResponse(IndexDocumentsBatch batch, - IndexDocumentsOptions options) { - return withContext(context -> indexDocumentsWithResponse(batch, options, context)); + Mono searchGet(String querySourceAuthorization, Boolean enableElevatedRead, + 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 (querySourceAuthorization != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-query-source-authorization"), + querySourceAuthorization); + } + if (enableElevatedRead != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-enable-elevated-read"), + String.valueOf(enableElevatedRead)); + } + 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(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchDocumentsResult.class)); } - 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); + /** + * Searches for documents in the index. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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) + Mono searchGet() { + // Generated convenience method for searchGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return searchGetWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchDocumentsResult.class)); } /** - * Retrieves a document from the Azure AI Search index. + * Searches for documents in 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());
-     *         }
-     *     });
-     * 
- * + * The {@link ContinuablePagedFlux} 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 ContinuablePagedFlux} 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. * - * @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 + * @param options Options for search API. + * @return A {@link ContinuablePagedFlux} that iterates over search results and provides access to the + * {@link SearchPagedResponse} for each page containing HTTP response and count, facet, and coverage information. + * @see Search documents */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDocument(String key, Class modelClass) { - return getDocumentWithResponse(key, modelClass, (List) null, (String) null).map(Response::getValue); + public SearchPagedFlux search(SearchOptions options) { + return search(options, null); } /** - * Retrieves a document from the Azure AI Search index. + * Searches for documents in 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());
-     *         }
-     *     });
-     * 
- * + * The {@link ContinuablePagedFlux} 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 ContinuablePagedFlux} 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. * - * @param key The key of the document to retrieve. - * @param modelClass The model class converts to. - * @param querySourceAuthorization Token identifying the user for which the query is being executed. - * This token is used to enforce security restrictions on documents. - * @param Convert document to the generic type. - * @return the document object - * @see Lookup document + * @param options Options for search API. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A {@link ContinuablePagedFlux} that iterates over search results and provides access to the + * {@link SearchPagedResponse} for each page containing HTTP response and count, facet, and coverage information. + * @see Search documents */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getDocument(String key, Class modelClass, String querySourceAuthorization) { - return getDocumentWithResponse(key, modelClass, (List) null, querySourceAuthorization) - .map(Response::getValue); + public SearchPagedFlux search(SearchOptions options, RequestOptions requestOptions) { + return new SearchPagedFlux(() -> (continuationToken, pageSize) -> { + Mono> mono; + if (continuationToken == null) { + BinaryData binaryData + = (options == null) ? null : BinaryData.fromObject(SearchUtils.fromSearchOptions(options)); + mono = searchWithResponse(binaryData, SearchUtils.addSearchHeaders(requestOptions, options)); + } else { + if (continuationToken.getApiVersion() != serviceClient.getServiceVersion()) { + return Flux.error(new IllegalStateException( + "Continuation token uses invalid apiVersion that doesn't match client serviceVersion. " + + "apiVersion: " + continuationToken.getApiVersion() + ", serviceVersion: " + + serviceClient.getServiceVersion())); + } + mono = searchWithResponse(BinaryData.fromObject(continuationToken.getNextPageParameters()), + requestOptions); + } + return mono.map(response -> new SearchPagedResponse(response, serviceClient.getServiceVersion())).flux(); + }); } /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. + * Retrieves a document from the index. * - *

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 + * @param querySourceAuthorization Token identifying the user for which the query is being executed. This token is + * used to enforce security restrictions on documents. + * @param enableElevatedRead A value that enables elevated read that bypass document level permission checks for the + * query operation. + * @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> getDocumentWithResponse(String key, Class modelClass, List selectedFields) { - return withContext( - context -> getDocumentWithResponseInternal(key, modelClass, selectedFields, null, null, context)); + public Mono getDocument(String key, String querySourceAuthorization, Boolean enableElevatedRead, + List selectedFields) { + // Generated convenience method for getDocumentWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (querySourceAuthorization != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-query-source-authorization"), + querySourceAuthorization); + } + if (enableElevatedRead != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-enable-elevated-read"), + String.valueOf(enableElevatedRead)); + } + if (selectedFields != null) { + requestOptions.addQueryParam("$select", + selectedFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getDocumentWithResponse(key, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(LookupDocument.class)); } /** - * Retrieves a document from the Azure AI Search index. - *

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

Code Sample

+ * Retrieves a document from the index. * - *

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. - * @param querySourceAuthorization Token identifying the user for which the query is being executed. - * This token is used to enforce security restrictions on documents. - * @return a response containing the document object - * @see Lookup 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> getDocumentWithResponse(String key, Class modelClass, List selectedFields, - String querySourceAuthorization) { - return withContext(context -> getDocumentWithResponseInternal(key, modelClass, selectedFields, - querySourceAuthorization, null, context)); + public Mono getDocument(String key) { + // Generated convenience method for getDocumentWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDocumentWithResponse(key, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(LookupDocument.class)); } /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. - * - * @param options Additional options for retrieving the document. - * @param Convert document to the generic type. - * @return response containing a document object - * @throws NullPointerException If {@code options} is null. - * @see Lookup document + * 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 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> getDocumentWithResponse(GetDocumentOptions options) { - return withContext(context -> getDocumentWithResponse(options, context)); - } - - Mono> getDocumentWithResponse(GetDocumentOptions options, Context context) { - Objects.requireNonNull(options, "'options' cannot be null."); - return getDocumentWithResponseInternal(options.getKey(), options.getModelClass(), options.getSelectedFields(), - null, options.isElevatedReadEnabled(), context); - } - - Mono> getDocumentWithResponse(String key, Class modelClass, List selectedFields, - String querySourceAuthorization, Context context) { - return getDocumentWithResponseInternal(key, modelClass, selectedFields, querySourceAuthorization, null, - context); - } - - Mono> getDocumentWithResponseInternal(String key, Class modelClass, List selectedFields, - String querySourceAuthorization, Boolean enableElevatedRead, Context context) { - try { - return restClient.getDocuments() - .getWithResponseAsync(key, selectedFields, querySourceAuthorization, enableElevatedRead, 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); + Mono suggestGet(String searchText, String suggesterName, 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, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SuggestDocumentsResult.class)); } /** - * 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. + * 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. + * @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 getDocumentCount() { - return this.getDocumentCountWithResponse().map(Response::getValue); + Mono suggestGet(String searchText, String suggesterName) { + // Generated convenience method for suggestGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return suggestGetWithResponse(searchText, suggesterName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SuggestDocumentsResult.class)); } /** - * 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. + * Sends a batch of document write actions to 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> 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); - } + Mono index(IndexDocumentsBatch batch) { + // Generated convenience method for indexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return indexWithResponse(BinaryData.fromObject(batch), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(IndexDocumentsResult.class)); } /** - * 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 -> {
-     *         // Reached the $skip limit, stop requesting more documents.
-     *         return numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT;
-     *     })
-     *     .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 + * Sends a batch of document write actions to 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. + * @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. + * @return response containing the status of operations for all documents in the indexing request on successful + * completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedFlux search(String searchText) { - return this.search(searchText, null, null); + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono indexDocuments(IndexDocumentsBatch batch) { + return indexDocumentsWithResponse(batch, null, null).flatMap(FluxUtil::toMono); } /** - * 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. + * Sends a batch of document write actions to the index. * - *

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 -> {
-     *         // Reached the $skip limit, stop requesting more documents.
-     *         return numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT;
-     *     })
-     *     .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. - * @param querySourceAuthorization Token identifying the user for which the query is being executed. - * This token is used to enforce security restrictions on documents. - * @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 + * @param batch The batch of index actions. + * @param options Options that allow specifying document indexing behavior. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @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. + * @throws IndexBatchException If {@code options} is null or has {@link IndexDocumentsOptions#throwOnAnyError()} set + * to true and 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. + * @return response containing the status of operations for all documents in the indexing request on successful + * completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedFlux search(String searchText, String querySourceAuthorization) { - return this.search(searchText, null, querySourceAuthorization, null); + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> indexDocumentsWithResponse(IndexDocumentsBatch batch, + IndexDocumentsOptions options, RequestOptions requestOptions) { + return indexWithResponse(BinaryData.fromObject(batch), requestOptions).flatMap(response -> { + IndexDocumentsResult results = response.getValue().toObject(IndexDocumentsResult.class); + return (response.getStatusCode() == 207 && (options == null || options.throwOnAnyError())) + ? Mono.error(new IndexBatchException(results)) + : Mono.just(new SimpleResponse<>(response, results)); + }); } /** - * 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 -> {
-     *         // Reached the $skip limit, stop requesting more documents.
-     *         return numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT;
-     *     })
-     *     .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());
-     *         }
-     *     }));
-     * 
- * + * Autocompletes incomplete query terms based on input text and matching terms in the index. * - * @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 + * @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 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}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedFlux search(String searchText, SearchOptions searchOptions) { - return search(searchText, searchOptions, null); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono autocompleteGet(String searchText, String suggesterName, 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, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AutocompleteResult.class)); } /** - * 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 -> {
-     *         // Reached the $skip limit, stop requesting more documents.
-     *         return numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT;
-     *     })
-     *     .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());
-     *         }
-     *     }));
-     * 
- * + * Autocompletes incomplete query terms based on input text and matching terms in the index. * - * @param searchText A full-text search query expression. - * @param searchOptions Parameters to further refine the search query - * @param querySourceAuthorization Token identifying the user for which the query is being executed. - * @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 + * @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. + * @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}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedFlux search(String searchText, SearchOptions searchOptions, String querySourceAuthorization) { - 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(); - Boolean enableElevatedRead = (searchOptions != null) ? searchOptions.isElevatedReadEnabled() : null; - Function> func = continuationToken -> withContext(context -> search(request, - continuationToken, firstPageResponse, querySourceAuthorization, enableElevatedRead, context)); - return new SearchPagedFlux(() -> func.apply(null), func); - } - - SearchPagedFlux search(String searchText, SearchOptions searchOptions, String querySourceAuthorization, - Context context) { - SearchRequest request = createSearchRequest(searchText, searchOptions); - // The firstPageResponse shared among all functional calls below. - // Do not initial new instance directly in func call. - Boolean enableElevatedRead = (searchOptions != null) ? searchOptions.isElevatedReadEnabled() : null; - final SearchFirstPageResponseWrapper firstPageResponseWrapper = new SearchFirstPageResponseWrapper(); - Function> func = continuationToken -> search(request, continuationToken, - firstPageResponseWrapper, querySourceAuthorization, enableElevatedRead, context); - return new SearchPagedFlux(() -> func.apply(null), func); - } - - private Mono search(SearchRequest request, String continuationToken, - SearchFirstPageResponseWrapper firstPageResponseWrapper, String querySourceAuthorization, - Boolean enableElevatedRead, Context context) { - SearchRequest requestToUse = (continuationToken == null) - ? request - : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); - - return restClient.getDocuments() - .searchPostWithResponseAsync(requestToUse, querySourceAuthorization, enableElevatedRead, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(response -> { - SearchPagedResponse page = mapToSearchPagedResponse(response, serializer, serviceVersion); - 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()); - } - - static SearchPagedResponse mapToSearchPagedResponse(Response response, - JsonSerializer serializer, SearchServiceVersion serviceVersion) { - SearchDocumentsResult result = response.getValue(); - return 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()); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono autocompleteGet(String searchText, String suggesterName) { + // Generated convenience method for autocompleteGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return autocompleteGetWithResponse(searchText, suggesterName, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AutocompleteResult.class)); } /** - * Suggests documents in the index that match the given partial query. - * - *

Code Sample

+ * Searches for documents in the index. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

* - *

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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight (Optional): [
+     *         String (Optional)
+     *     ]
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby (Optional): [
+     *         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/innerHits/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields (Optional): [
+     *         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 (Optional): [
+     *         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 (Optional): [
+     *         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: Float (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *             perDocumentVectorLimit: Integer (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *     hybridSearch (Optional): {
+     *         maxTextRecallSize: Integer (Optional)
+     *         countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *     }
+     * }
+     * }
      * 
- * * - * @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); - } - - /** - * Suggests documents in the index that match the given partial query. - * - *

Code Sample

+ *

Response Body Schema

* - *

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());
-     *         }
-     *     });
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
      * 
- * * - * @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 + * @param searchPostRequest The searchPostRequest parameter. + * @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.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) + Mono> searchWithResponse(BinaryData searchPostRequest, RequestOptions requestOptions) { + return this.serviceClient.searchWithResponseAsync(searchPostRequest, requestOptions); } /** - * Autocompletes incomplete query terms based on input text and matching terms in the index. + * Suggests documents in the index that match the given partial query text. + *

Request Body Schema

* - *

Code Sample

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

Autocomplete text from documents in service.

+ *

Response Body Schema

* - * *
-     * SEARCH_ASYNC_CLIENT.autocomplete("searchText", "sg")
-     *     .subscribe(result -> System.out.printf("The complete term is %s", result.getText()));
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
      * 
- * * - * @param searchText search text - * @param suggesterName suggester name - * @return auto complete result. + * @param suggestPostRequest The suggestPostRequest parameter. + * @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.COLLECTION) - public AutocompletePagedFlux autocomplete(String searchText, String suggesterName) { - return autocomplete(searchText, suggesterName, null); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> suggestWithResponse(BinaryData suggestPostRequest, RequestOptions requestOptions) { + return this.serviceClient.suggestWithResponseAsync(suggestPostRequest, requestOptions); } /** * Autocompletes incomplete query terms based on input text and matching terms in the index. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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 (Optional): [
+     *         String (Optional)
+     *     ]
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
* - *

Autocomplete text from documents in service with option.

+ *

Response Body Schema

* - * *
-     * 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())
-     *     );
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @param searchText search text - * @param suggesterName suggester name - * @param autocompleteOptions autocomplete options - * @return auto complete result. + * @param autocompletePostRequest The autocompletePostRequest parameter. + * @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}. */ - 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()))); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> autocompleteWithResponse(BinaryData autocompletePostRequest, + RequestOptions requestOptions) { + return this.serviceClient.autocompleteWithResponseAsync(autocompletePostRequest, requestOptions); } /** - * Create search request from search text and parameters - * - * @param searchText search text - * @param options search options - * @return SearchRequest + * Suggests documents in the index that match the given partial query text. + * + * @param options Options for suggest API. + * @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}. */ - 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.getDebugMode()); - - 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(); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono suggest(SuggestOptions options) { + // Generated convenience method for suggestWithResponse + RequestOptions requestOptions = new RequestOptions(); + SuggestPostRequest suggestPostRequestObj + = new SuggestPostRequest(options.getSearchText(), options.getSuggesterName()).setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setOrderBy(options.getOrderBy()) + .setSearchFields(options.getSearchFields()) + .setSelect(options.getSelect()) + .setTop(options.getTop()); + BinaryData suggestPostRequest = BinaryData.fromObject(suggestPostRequestObj); + return suggestWithResponse(suggestPostRequest, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SuggestDocumentsResult.class)); } - static String createQueryRewrites(QueryRewrites queryRewrites) { - if (queryRewrites == null) { - return null; - } - return queryRewrites.toString(); + /** + * Suggests documents in the index that match the given partial query text. + * + * @param options Options for suggest API. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @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 along with {@link Response} on successful + * completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> suggestWithResponse(SuggestOptions options, + RequestOptions requestOptions) { + SuggestPostRequest suggestPostRequestObj + = new SuggestPostRequest(options.getSearchText(), options.getSuggesterName()).setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setOrderBy(options.getOrderBy()) + .setSearchFields(options.getSearchFields()) + .setSelect(options.getSelect()) + .setTop(options.getTop()); + BinaryData suggestPostRequest = BinaryData.fromObject(suggestPostRequestObj); + return suggestWithResponse(suggestPostRequest, requestOptions).map( + response -> new SimpleResponse<>(response, response.getValue().toObject(SuggestDocumentsResult.class))); } /** - * Create suggest request from search text, suggester name, and parameters + * Autocompletes incomplete query terms based on input text and matching terms in the index. * - * @param searchText search text - * @param suggesterName search text - * @param options suggest options - * @return SuggestRequest + * @param options Options for autocomplete API. + * @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}. */ - 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()); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono autocomplete(AutocompleteOptions options) { + // Generated convenience method for autocompleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + AutocompletePostRequest autocompletePostRequestObj + = new AutocompletePostRequest(options.getSearchText(), options.getSuggesterName()) + .setAutocompleteMode(options.getAutocompleteMode()) + .setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setSearchFields(options.getSearchFields()) + .setTop(options.getTop()); + BinaryData autocompletePostRequest = BinaryData.fromObject(autocompletePostRequestObj); + return autocompleteWithResponse(autocompletePostRequest, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AutocompleteResult.class)); } /** - * Create Autocomplete request from search text, suggester name, and parameters + * Autocompletes incomplete query terms based on input text and matching terms in the index. * - * @param searchText search text - * @param suggesterName search text - * @param options autocomplete options - * @return AutocompleteRequest + * @param options Options for autocomplete API. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @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 along with {@link Response} on successful completion of {@link Mono}. */ - 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); + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> autocompleteWithResponse(AutocompleteOptions options, + RequestOptions requestOptions) { + AutocompletePostRequest autocompletePostRequestObj + = new AutocompletePostRequest(options.getSearchText(), options.getSuggesterName()) + .setAutocompleteMode(options.getAutocompleteMode()) + .setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setSearchFields(options.getSearchFields()) + .setTop(options.getTop()); + BinaryData autocompletePostRequest = BinaryData.fromObject(autocompletePostRequestObj); + return autocompleteWithResponse(autocompletePostRequest, requestOptions) + .map(response -> new SimpleResponse<>(response, response.getValue().toObject(AutocompleteResult.class))); } - } 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/SearchAudience.java similarity index 97% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchAudience.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAudience.java index 0396f01968a8..a0e8d55b6a23 100644 --- 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/SearchAudience.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.models; +package com.azure.search.documents; import com.azure.core.util.ExpandableStringEnum; 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 3a1a84bbd787..c5d9187af581 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,1305 +1,1907 @@ // 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 java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; -import java.util.stream.Collectors; - +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.HttpPipeline; +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.BinaryData; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -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.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.core.util.paging.ContinuablePagedIterable; +import com.azure.search.documents.implementation.SearchClientImpl; +import com.azure.search.documents.implementation.SearchUtils; +import com.azure.search.documents.implementation.models.AutocompletePostRequest; +import com.azure.search.documents.implementation.models.SuggestPostRequest; +import com.azure.search.documents.models.AutocompleteMode; import com.azure.search.documents.models.AutocompleteOptions; import com.azure.search.documents.models.AutocompleteResult; -import com.azure.search.documents.models.GetDocumentOptions; -import com.azure.search.documents.models.IndexActionType; import com.azure.search.documents.models.IndexBatchException; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.IndexDocumentsOptions; 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.SearchOptions; -import com.azure.search.documents.models.SearchResult; +import com.azure.search.documents.models.SearchPagedIterable; +import com.azure.search.documents.models.SearchPagedResponse; +import com.azure.search.documents.models.SemanticErrorMode; +import com.azure.search.documents.models.SuggestDocumentsResult; 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.Objects; +import java.util.stream.Collectors; /** - * 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; + private static final ClientLogger LOGGER = new ClientLogger(SearchClient.class); - /** - * The underlying AutoRest client used to interact with the Azure AI Search service - */ - private final SearchIndexClientImpl restClient; + @Generated + private final SearchClientImpl serviceClient; /** - * The pipeline that powers this client. + * Initializes an instance of SearchClient class. + * + * @param serviceClient the service client implementation. */ - private final HttpPipeline httpPipeline; - - final JsonSerializer serializer; + @Generated + SearchClient(SearchClientImpl serviceClient) { + this.serviceClient = serviceClient; + } /** - * Package private constructor to be used by {@link SearchClientBuilder} + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. + * + * @return the pipeline. */ - 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; + HttpPipeline getHttpPipeline() { + return serviceClient.getHttpPipeline(); } /** - * Gets the name of the Azure AI Search index. + * Gets the endpoint used to communicate with the Azure AI Search service. * - * @return the indexName value. + * @return The endpoint. */ - public String getIndexName() { - return this.indexName; + public String getEndpoint() { + return serviceClient.getEndpoint(); } /** - * Gets the {@link HttpPipeline} powering this client. + * Gets the name of the Azure AI Search index. * - * @return the pipeline. + * @return The index name. */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; + public String getIndexName() { + return serviceClient.getIndexName(); } /** - * Gets the endpoint for the Azure AI Search service. + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. * - * @return the endpoint value. + * @return The service version. */ - public String getEndpoint() { - return this.endpoint; + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); } /** - * Uploads a collection of documents to the target index. - * - *

Code Sample

- * - *

Upload dynamic SearchDocument.

+ * Queries the number of documents in the index. + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * long
+     * }
      * 
- * * - * @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 + * @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 64-bit integer along with {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult uploadDocuments(Iterable documents) { - return uploadDocumentsWithResponse(documents, null, Context.NONE).getValue(); + public Response getDocumentCountWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getDocumentCountWithResponse(requestOptions); } /** - * Uploads a collection of documents to the target index. - * - *

Code Sample

- * - *

Upload dynamic SearchDocument.

+ * 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", "innerHits", "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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
      * 
- * * - * @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 + * @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 uploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.UPLOAD), options, context); + Response searchGetWithResponse(RequestOptions requestOptions) { + return this.serviceClient.searchGetWithResponse(requestOptions); } /** - * 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.

+ * 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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: Object (Required)
+     *     }
+     * }
+     * }
      * 
- * * - * @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 + * @param key The key of the document to retrieve. + * @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 IndexDocumentsResult mergeDocuments(Iterable documents) { - return mergeDocumentsWithResponse(documents, null, Context.NONE).getValue(); + public Response getDocumentWithResponse(String key, RequestOptions requestOptions) { + return this.serviceClient.getDocumentWithResponse(key, requestOptions); } /** - * 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

+ * 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

* - *

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());
-     * }
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
      * 
- * * - * @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 + * @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 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 mergeDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE), options, context); + Response suggestGetWithResponse(String searchText, String suggesterName, + RequestOptions requestOptions) { + return this.serviceClient.suggestGetWithResponse(searchText, suggesterName, requestOptions); } /** - * 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}). + * Sends a batch of document write actions to the index. + *

Request Body Schema

* - *

Code Sample

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

Merge or upload dynamic SearchDocument.

+ *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @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 + * @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 IndexDocumentsResult mergeOrUploadDocuments(Iterable documents) { - return mergeOrUploadDocumentsWithResponse(documents, null, Context.NONE).getValue(); + Response indexWithResponse(BinaryData batch, RequestOptions requestOptions) { + return this.serviceClient.indexWithResponse(batch, requestOptions); } /** - * 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.

+ * 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

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @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 + * @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 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 mergeOrUploadDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.MERGE_OR_UPLOAD), options, - context); + Response autocompleteGetWithResponse(String searchText, String suggesterName, + RequestOptions requestOptions) { + return this.serviceClient.autocompleteGetWithResponse(searchText, suggesterName, requestOptions); } /** - * 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 + * Queries the number of documents in the index. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 64-bit integer. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult deleteDocuments(Iterable documents) { - return deleteDocumentsWithResponse(documents, null, Context.NONE).getValue(); + public long getDocumentCount() { + // Generated convenience method for getDocumentCountWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDocumentCountWithResponse(requestOptions).getValue().toObject(Long.class); } /** - * 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 + * Searches for documents in the index. + * + * @param querySourceAuthorization Token identifying the user for which the query is being executed. This token is + * used to enforce security restrictions on documents. + * @param enableElevatedRead A value that enables elevated read that bypass document level permission checks for the + * query operation. + * @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 Response deleteDocumentsWithResponse(Iterable documents, - IndexDocumentsOptions options, Context context) { - return indexDocumentsWithResponse(buildIndexBatch(documents, IndexActionType.DELETE), options, context); + SearchDocumentsResult searchGet(String querySourceAuthorization, Boolean enableElevatedRead, 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 (querySourceAuthorization != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-query-source-authorization"), + querySourceAuthorization); + } + if (enableElevatedRead != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-enable-elevated-read"), + String.valueOf(enableElevatedRead)); + } + 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(requestOptions).getValue().toObject(SearchDocumentsResult.class); } /** - * 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 + * Searches for documents in the index. + * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 IndexDocumentsResult indexDocuments(IndexDocumentsBatch batch) { - return indexDocumentsWithResponse(batch, null, Context.NONE).getValue(); + SearchDocumentsResult searchGet() { + // Generated convenience method for searchGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return searchGetWithResponse(requestOptions).getValue().toObject(SearchDocumentsResult.class); } /** - * 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());
-     * }
-     * 
- * + * Searches for documents in the Azure AI Search index. + *

+ * The {@link ContinuablePagedIterable} 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 ContinuablePagedIterable} 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. * - * @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 + * @param options Options for search API. + * @return A {@link ContinuablePagedIterable} that iterates over search results and provides access to the + * {@link SearchPagedResponse} for each page containing HTTP response and count, facet, and coverage information. + * @see Search 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); + public SearchPagedIterable search(SearchOptions options) { + return search(options, null); } /** - * Retrieves a document from the Azure AI Search index. + * Searches for documents in the Azure AI Search index. *

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

Code Sample

- * - *

Get dynamic SearchDocument.

+ * The {@link ContinuablePagedIterable} 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 ContinuablePagedIterable} 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. * - * - *
-     * 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 options Options for search API. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A {@link ContinuablePagedIterable} that iterates over search results and provides access to the + * {@link SearchPagedResponse} for each page containing HTTP response and count, facet, and coverage information. + * @see Search documents + */ + public SearchPagedIterable search(SearchOptions options, RequestOptions requestOptions) { + return new SearchPagedIterable(() -> (continuationToken, pageSize) -> { + Response response; + if (continuationToken == null) { + BinaryData binaryData + = (options == null) ? null : BinaryData.fromObject(SearchUtils.fromSearchOptions(options)); + response = searchWithResponse(binaryData, SearchUtils.addSearchHeaders(requestOptions, options)); + } else { + if (continuationToken.getApiVersion() != serviceClient.getServiceVersion()) { + throw LOGGER.atError() + .addKeyValue("apiVersion", continuationToken.getApiVersion()) + .addKeyValue("serviceVersion", serviceClient.getServiceVersion()) + .log(new IllegalStateException( + "Continuation token uses invalid apiVersion that doesn't match client serviceVersion.")); + } + response = searchWithResponse(BinaryData.fromObject(continuationToken.getNextPageParameters()), + requestOptions); + } + return new SearchPagedResponse(response, serviceClient.getServiceVersion()); + }); + } + + /** + * Retrieves a document from the index. * * @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 + * @param querySourceAuthorization Token identifying the user for which the query is being executed. This token is + * used to enforce security restrictions on documents. + * @param enableElevatedRead A value that enables elevated read that bypass document level permission checks for the + * query operation. + * @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 T getDocument(String key, Class modelClass) { - return getDocumentWithResponse(key, modelClass, (List) null, Context.NONE).getValue(); + public LookupDocument getDocument(String key, String querySourceAuthorization, Boolean enableElevatedRead, + List selectedFields) { + // Generated convenience method for getDocumentWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (querySourceAuthorization != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-query-source-authorization"), + querySourceAuthorization); + } + if (enableElevatedRead != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-enable-elevated-read"), + String.valueOf(enableElevatedRead)); + } + if (selectedFields != null) { + requestOptions.addQueryParam("$select", + selectedFields.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getDocumentWithResponse(key, requestOptions).getValue().toObject(LookupDocument.class); } /** - * Retrieves a document from the Azure AI Search index. - *

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

Code Sample

- * - *

Get dynamic SearchDocument.

+ * Retrieves a document from the index. * - * - *
-     * 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 + * @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 Response getDocumentWithResponse(String key, Class modelClass, List selectedFields, - Context context) { - return getDocumentWithResponseInternal(key, modelClass, selectedFields, null, null, context); + public LookupDocument getDocument(String key) { + // Generated convenience method for getDocumentWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDocumentWithResponse(key, requestOptions).getValue().toObject(LookupDocument.class); } /** - * Retrieves a document from the Azure AI Search index. - *

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

Code Sample

+ * Suggests documents in the index that match the given partial query text. * - *

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 querySourceAuthorization Token identifying the user for which the query is being executed. - * This token is used to enforce security restrictions on documents. - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing a document object - * @see Lookup document + * @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 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 Response getDocumentWithResponse(String key, Class modelClass, List selectedFields, - String querySourceAuthorization, Context context) { - return getDocumentWithResponseInternal(key, modelClass, selectedFields, querySourceAuthorization, null, - context); + SuggestDocumentsResult suggestGet(String searchText, String suggesterName, 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, requestOptions).getValue() + .toObject(SuggestDocumentsResult.class); } /** - * Retrieves a document from the Azure AI Search index. - *

- * View naming rules for guidelines on - * constructing valid document keys. + * Suggests documents in the index that match the given partial query text. * - * @param options Additional options for retrieving the document. - * @param context additional context that is passed through the Http pipeline during the service call - * @param Convert document to the generic type. - * @return response containing a document object - * @throws NullPointerException If {@code options} is null. - * @see Lookup document + * @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. + * @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 Response getDocumentWithResponse(GetDocumentOptions options, Context context) { - Objects.requireNonNull(options, "'options' cannot be null."); - return getDocumentWithResponseInternal(options.getKey(), options.getModelClass(), options.getSelectedFields(), - null, options.isElevatedReadEnabled(), context); + SuggestDocumentsResult suggestGet(String searchText, String suggesterName) { + // Generated convenience method for suggestGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return suggestGetWithResponse(searchText, suggesterName, requestOptions).getValue() + .toObject(SuggestDocumentsResult.class); } - private Response getDocumentWithResponseInternal(String key, Class modelClass, - List selectedFields, String querySourceAuthorization, Boolean enableElevatedRead, Context context) { - - try { - Response> response = restClient.getDocuments() - .getWithResponse(key, selectedFields, querySourceAuthorization, enableElevatedRead, null, context); + /** + * Sends a batch of document write actions to 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) + IndexDocumentsResult index(IndexDocumentsBatch batch) { + // Generated convenience method for indexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return indexWithResponse(BinaryData.fromObject(batch), requestOptions).getValue() + .toObject(IndexDocumentsResult.class); + } - 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); - } + /** + * Sends a batch of document write actions to 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. + * @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. + * @return response containing the status of operations for all documents in the indexing request. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public IndexDocumentsResult indexDocuments(IndexDocumentsBatch batch) { + return indexDocumentsWithResponse(batch, null, null).getValue(); } /** - * Queries the number of documents in the search index. - * - *

Code Sample

+ * Sends a batch of document write actions to the index. * - *

Get document count.

- * - * - *
-     * long count = SEARCH_CLIENT.getDocumentCount();
-     * System.out.printf("There are %d documents in service.", count);
-     * 
- * - * - * @return the number of documents. + * @param batch The batch of index actions. + * @param options Options that allow specifying document indexing behavior. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @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. + * @throws IndexBatchException If {@code options} is null or has {@link IndexDocumentsOptions#throwOnAnyError()} set + * to true and 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. + * @return response containing the status of operations for all documents in the indexing request. */ @ServiceMethod(returns = ReturnType.SINGLE) - public long getDocumentCount() { - return getDocumentCountWithResponse(Context.NONE).getValue(); + public Response indexDocumentsWithResponse(IndexDocumentsBatch batch, + IndexDocumentsOptions options, RequestOptions requestOptions) { + Response response = indexWithResponse(BinaryData.fromObject(batch), requestOptions); + IndexDocumentsResult results = response.getValue().toObject(IndexDocumentsResult.class); + if (response.getStatusCode() == 207 && (options == null || options.throwOnAnyError())) { + throw LOGGER.atError().log(new IndexBatchException(results)); + } else { + return new SimpleResponse<>(response, results); + } } /** - * 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());
-     * 
- * + * Autocompletes incomplete query terms based on input text and matching terms in the index. * - * @param context additional context that is passed through the Http pipeline during the service call - * @return response containing the number of documents. + * @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 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 Response getDocumentCountWithResponse(Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDocuments().countWithResponse(null, context), LOGGER); + AutocompleteResult autocompleteGet(String searchText, String suggesterName, 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, requestOptions).getValue() + .toObject(AutocompleteResult.class); } /** - * 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;
-     *     }
-     * }
-     * 
- * + * Autocompletes incomplete query terms based on input text and matching terms in the index. * - * @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 + * @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. + * @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. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public SearchPagedIterable search(String searchText) { - return search(searchText, null, Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + AutocompleteResult autocompleteGet(String searchText, String suggesterName) { + // Generated convenience method for autocompleteGetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return autocompleteGetWithResponse(searchText, suggesterName, requestOptions).getValue() + .toObject(AutocompleteResult.class); } /** - * 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. + * Searches for documents in the index. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

* - *

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());
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight (Optional): [
+     *         String (Optional)
+     *     ]
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby (Optional): [
+     *         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/innerHits/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields (Optional): [
+     *         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 (Optional): [
+     *         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 (Optional): [
+     *         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: Float (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *             perDocumentVectorLimit: Integer (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *     hybridSearch (Optional): {
+     *         maxTextRecallSize: Integer (Optional)
+     *         countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *     }
+     * }
+     * }
+     * 
* - * 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()); - * } - * }); + *

Response Body Schema

* - * if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) { - * // Reached the $skip limit, stop requesting more documents. - * break; - * } - * } + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
      * 
- * * - * @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 + * @param searchPostRequest The searchPostRequest parameter. + * @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.COLLECTION) - public SearchPagedIterable search(String searchText, SearchOptions searchOptions, Context context) { - return search(searchText, searchOptions, null, context); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response searchWithResponse(BinaryData searchPostRequest, RequestOptions requestOptions) { + return this.serviceClient.searchWithResponse(searchPostRequest, requestOptions); } /** - * 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

+ * Suggests documents in the index that match the given partial query text. + *

Request Body Schema

* - *

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());
+     * {@code
+     * {
+     *     filter: String (Optional)
+     *     fuzzy: Boolean (Optional)
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby (Optional): [
+     *         String (Optional)
+     *     ]
+     *     search: String (Required)
+     *     searchFields (Optional): [
+     *         String (Optional)
+     *     ]
+     *     select (Optional): [
+     *         String (Optional)
+     *     ]
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
* - * 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()); - * } - * }); + *

Response Body Schema

* - * if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) { - * // Reached the $skip limit, stop requesting more documents. - * break; - * } - * } + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
      * 
- * * - * @param searchText A full-text search query expression. - * @param searchOptions Parameters to further refine the search query - * @param querySourceAuthorization Token identifying the user for which the query is being executed. - * This token is used to enforce security restrictions on documents. - * @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 + * @param suggestPostRequest The suggestPostRequest parameter. + * @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.COLLECTION) - public SearchPagedIterable search(String searchText, SearchOptions searchOptions, String querySourceAuthorization, - 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, querySourceAuthorization, context); - return new SearchPagedIterable(() -> func.apply(null), func); - } - - private SearchPagedResponse search(SearchRequest request, String continuationToken, - SearchFirstPageResponseWrapper firstPageResponseWrapper, String querySourceAuthorization, Context context) { - SearchRequest requestToUse = (continuationToken == null) - ? request - : SearchContinuationToken.deserializeToken(serviceVersion.getVersion(), continuationToken); - - return Utility.executeRestCallWithExceptionHandling(() -> { - Response response = restClient.getDocuments() - .searchPostWithResponse(requestToUse, querySourceAuthorization, null, 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); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response suggestWithResponse(BinaryData suggestPostRequest, RequestOptions requestOptions) { + return this.serviceClient.suggestWithResponse(suggestPostRequest, requestOptions); } /** - * Suggests documents in the index that match the given partial query. + * Autocompletes incomplete query terms based on input text and matching terms in the index. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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 (Optional): [
+     *         String (Optional)
+     *     ]
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
* - *

Suggest text from documents in service.

+ *

Response Body Schema

* - * *
-     * 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());
-     *     }
-     * }
+     * {@code
+     * {
+     *     @search.coverage: Double (Optional)
+     *     value (Required): [
+     *          (Required){
+     *             text: String (Required)
+     *             queryPlusText: String (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @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 + * @param autocompletePostRequest The autocompletePostRequest parameter. + * @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.COLLECTION) - public SuggestPagedIterable suggest(String searchText, String suggesterName) { - return suggest(searchText, suggesterName, null, Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response autocompleteWithResponse(BinaryData autocompletePostRequest, RequestOptions requestOptions) { + return this.serviceClient.autocompleteWithResponse(autocompletePostRequest, requestOptions); } /** - * 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 + * Suggests documents in the index that match the given partial query text. + * + * @param options Options for suggest API. + * @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. */ - @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)); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SuggestDocumentsResult suggest(SuggestOptions options) { + // Generated convenience method for suggestWithResponse + RequestOptions requestOptions = new RequestOptions(); + SuggestPostRequest suggestPostRequestObj + = new SuggestPostRequest(options.getSearchText(), options.getSuggesterName()).setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setOrderBy(options.getOrderBy()) + .setSearchFields(options.getSearchFields()) + .setSelect(options.getSelect()) + .setTop(options.getTop()); + BinaryData suggestPostRequest = BinaryData.fromObject(suggestPostRequestObj); + return suggestWithResponse(suggestPostRequest, requestOptions).getValue() + .toObject(SuggestDocumentsResult.class); } - 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); + /** + * Suggests documents in the index that match the given partial query text. + * + * @param options Options for suggest API. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @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 along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response suggestWithResponse(SuggestOptions options, RequestOptions requestOptions) { + SuggestPostRequest suggestPostRequestObj + = new SuggestPostRequest(options.getSearchText(), options.getSuggesterName()).setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setOrderBy(options.getOrderBy()) + .setSearchFields(options.getSearchFields()) + .setSelect(options.getSelect()) + .setTop(options.getTop()); + BinaryData suggestPostRequest = BinaryData.fromObject(suggestPostRequestObj); + Response response = suggestWithResponse(suggestPostRequest, requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SuggestDocumentsResult.class)); } /** * 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. + * @param options Options for autocomplete API. + * @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. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public AutocompletePagedIterable autocomplete(String searchText, String suggesterName) { - return autocomplete(searchText, suggesterName, null, Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public AutocompleteResult autocomplete(AutocompleteOptions options) { + // Generated convenience method for autocompleteWithResponse + RequestOptions requestOptions = new RequestOptions(); + AutocompletePostRequest autocompletePostRequestObj + = new AutocompletePostRequest(options.getSearchText(), options.getSuggesterName()) + .setAutocompleteMode(options.getAutocompleteMode()) + .setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setSearchFields(options.getSearchFields()) + .setTop(options.getTop()); + BinaryData autocompletePostRequest = BinaryData.fromObject(autocompletePostRequestObj); + return autocompleteWithResponse(autocompletePostRequest, requestOptions).getValue() + .toObject(AutocompleteResult.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. + * @param options Options for autocomplete API. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @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 along with {@link Response}. */ - @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); + @ServiceMethod(returns = ReturnType.SINGLE) + public Response autocompleteWithResponse(AutocompleteOptions options, + RequestOptions requestOptions) { + AutocompletePostRequest autocompletePostRequestObj + = new AutocompletePostRequest(options.getSearchText(), options.getSuggesterName()) + .setAutocompleteMode(options.getAutocompleteMode()) + .setFilter(options.getFilter()) + .setUseFuzzyMatching(options.isUseFuzzyMatching()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setSearchFields(options.getSearchFields()) + .setTop(options.getTop()); + BinaryData autocompletePostRequest = BinaryData.fromObject(autocompletePostRequestObj); + Response response = autocompleteWithResponse(autocompletePostRequest, requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(AutocompleteResult.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..1aa31ec09aac 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,602 +1,428 @@ // 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.JacksonAdapter; 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.implementation.SearchClientImpl; 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 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 { +public final class SearchClientBuilder implements HttpTrait, + ConfigurationTrait, TokenCredentialTrait, + KeyCredentialTrait, EndpointTrait { + 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); + @Generated + private static final String SDK_NAME = "name"; - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); + @Generated + private static final String SDK_VERSION = "version"; - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; + @Generated + private static final String[] DEFAULT_SCOPES = new String[] { "https://search.azure.com/.default" }; - 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; + @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 client used to send the request. */ - 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 HttpClient httpClient; /** - * 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 httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + 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 pipeline to send requests through. */ - public SearchIndexingBufferedSenderBuilder bufferedSender(TypeReference documentType) { - return new SearchIndexingBufferedSenderBuilder<>(); - } - - private void validateIndexNameAndEndpoint() { - Objects.requireNonNull(indexName, "'indexName' cannot be null."); - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - } - - private HttpPipeline getHttpPipeline() { - if (httpPipeline != null) { - return httpPipeline; - } - - return Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - } + @Generated + private HttpPipeline pipeline; /** - * 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)); + 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.endpoint = endpoint; + this.pipeline = pipeline; return this; } + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; + /** - * 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 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 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 clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; return this; } + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + /** - * 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. + * {@inheritDoc}. */ - public SearchClientBuilder audience(SearchAudience audience) { - this.audience = audience; + @Generated + @Override + public SearchClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; return this; } /** - * 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. + * {@inheritDoc}. */ - public SearchClientBuilder indexName(String indexName) { - if (CoreUtils.isNullOrEmpty(indexName)) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); - } - this.indexName = indexName; + @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 {@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 configuration(Configuration configuration) { + this.configuration = configuration; return this; } + /* + * The TokenCredential used for authentication. + */ + @Generated + private TokenCredential tokenCredential; + /** - * Gets the default Azure Search headers and query parameters allow list. - * - * @return The default {@link HttpLogOptions} allow list. + * {@inheritDoc}. */ - public static HttpLogOptions getDefaultLogOptions() { - return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); + @Generated + @Override + public SearchClientBuilder credential(TokenCredential tokenCredential) { + this.tokenCredential = tokenCredential; + return this; } + /* + * The KeyCredential used for authentication. + */ + @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."); + public SearchClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } - if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) { - perCallPolicies.add(policy); - } else { - perRetryPolicies.add(policy); - } + /* + * The name of the index. + */ + @Generated + private String indexName; + /** + * Sets The name of the index. + * + * @param indexName the indexName value. + * @return the SearchClientBuilder. + */ + @Generated + public SearchClientBuilder indexName(String indexName) { + this.indexName = indexName; 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. + * Sets Service version. * - * @param jsonSerializer The serializer to serialize user defined models. - * @return The updated SearchClientBuilder object. + * @param serviceVersion the serviceVersion value. + * @return the SearchClientBuilder. */ - public SearchClientBuilder serializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = jsonSerializer; + @Generated + public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; return this; } + /* + * The retry policy that will attempt to retry failed requests, if applicable. + */ + @Generated + private RetryPolicy retryPolicy; + /** - * 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.

+ * Sets The retry policy that will attempt to retry failed requests, if applicable. * - * @param client The {@link HttpClient} to use for requests. - * @return The updated SearchClientBuilder object. + * @param retryPolicy the retryPolicy value. + * @return the SearchClientBuilder. */ - @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."); - } - - this.httpClient = client; + @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.

+ * Sets the Audience to use for authentication with Microsoft Entra ID. *

- * 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}. + * If {@code audience} is null the public cloud audience will be assumed. * - * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. + * @param audience The Audience to use for authentication with Microsoft Entra ID. * @return The updated SearchClientBuilder object. */ - @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."); + public SearchClientBuilder audience(SearchAudience audience) { + if (audience == null) { + this.scopes = DEFAULT_SCOPES; + } else { + this.scopes = new String[] { audience.getValue() + "/.default" }; } - - 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. + * Builds an instance of SearchClientImpl with the provided parameters. * - * @param configuration The configuration store that will be used. - * @return The updated SearchClientBuilder object. + * @return an instance of SearchClientImpl. */ - @Override - public SearchClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; + @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, this.indexName, localServiceVersion); + return client; + } + + @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."); + Objects.requireNonNull(indexName, "'indexName' 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, 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 {@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)}. + * Builds an instance of SearchAsyncClient class. * - * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. - * @return The updated SearchClientBuilder object. + * @return an instance of SearchAsyncClient. */ - public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; + @Generated + public SearchAsyncClient buildAsyncClient() { + return new SearchAsyncClient(buildInnerClient()); } /** - * 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)}. + * Builds an instance of SearchClient class. * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated SearchClientBuilder object. + * @return an instance of SearchClient. */ - @Override - public SearchClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; + @Generated + public SearchClient buildClient() { + return new SearchClient(buildInnerClient()); } + private static final ClientLogger LOGGER = new ClientLogger(SearchClientBuilder.class); + /** - * 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. + * Create a new instance of {@link SearchIndexingBufferedSenderBuilder} used to configure {@link + * SearchIndexingBufferedSender SearchIndexingBufferedSenders} and {@link SearchIndexingBufferedAsyncSender + * SearchIndexingBufferedAsyncSenders}. * - * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchClientBuilder object. + * @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}. */ - public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - return this; + public SearchIndexingBufferedSenderBuilder bufferedSender(TypeReference documentType) { + return new SearchIndexingBufferedSenderBuilder<>(); } /** @@ -612,22 +438,33 @@ public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { @ServiceClientBuilder( serviceClients = { SearchIndexingBufferedSender.class, SearchIndexingBufferedAsyncSender.class }) public final class SearchIndexingBufferedSenderBuilder { + private final ClientLogger logger = new ClientLogger(SearchIndexingBufferedSenderBuilder.class); - private Function documentKeyRetriever; + private Function, String> 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 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 JsonSerializer jsonSerializer; + + private Consumer onActionAddedConsumer; + + private Consumer onActionSucceededConsumer; + + private Consumer onActionErrorConsumer; + + private Consumer onActionSentConsumer; private SearchIndexingBufferedSenderBuilder() { } @@ -643,19 +480,13 @@ private SearchIndexingBufferedSenderBuilder() { * 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; - + SearchClient client = buildClient(); 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); + return new SearchIndexingBufferedSender<>(client, serializer, documentKeyRetriever, autoFlush, + autoFlushInterval, initialBatchActionCount, maxRetriesPerAction, throttlingDelay, maxThrottlingDelay, + onActionAddedConsumer, onActionSucceededConsumer, onActionErrorConsumer, onActionSentConsumer); } /** @@ -669,19 +500,13 @@ public SearchIndexingBufferedSender buildSender() { * 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; - + SearchAsyncClient asyncClient = buildAsyncClient(); 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); + return new SearchIndexingBufferedAsyncSender<>(asyncClient, serializer, documentKeyRetriever, autoFlush, + autoFlushInterval, initialBatchActionCount, maxRetriesPerAction, throttlingDelay, maxThrottlingDelay, + onActionAddedConsumer, onActionSucceededConsumer, onActionErrorConsumer, onActionSentConsumer); } /** @@ -711,7 +536,6 @@ public SearchIndexingBufferedSenderBuilder autoFlush(boolean autoFlush) { */ public SearchIndexingBufferedSenderBuilder autoFlushInterval(Duration autoFlushInterval) { Objects.requireNonNull(autoFlushInterval, "'autoFlushInterval' cannot be null."); - this.autoFlushInterval = autoFlushInterval; return this; } @@ -730,41 +554,40 @@ public SearchIndexingBufferedSenderBuilder initialBatchActionCount(int initia if (initialBatchActionCount < 1) { throw logger.logExceptionAsError(new IllegalArgumentException("'batchSize' cannot be less than one.")); } - this.initialBatchActionCount = initialBatchActionCount; return this; } // 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; - // } - + // /** + // * 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; - // } - + // /** + // * 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. *

@@ -781,7 +604,6 @@ public SearchIndexingBufferedSenderBuilder maxRetriesPerAction(int maxRetries if (maxRetriesPerAction < 1) { throw logger.logExceptionAsError(new IllegalArgumentException("'maxRetries' cannot be less than one.")); } - this.maxRetriesPerAction = maxRetriesPerAction; return this; } @@ -799,12 +621,10 @@ public SearchIndexingBufferedSenderBuilder maxRetriesPerAction(int maxRetries */ 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; } @@ -825,12 +645,10 @@ public SearchIndexingBufferedSenderBuilder throttlingDelay(Duration throttlin */ 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; } @@ -843,7 +661,7 @@ public SearchIndexingBufferedSenderBuilder maxThrottlingDelay(Duration maxThr * @return The updated SearchIndexingBufferedSenderBuilder object. */ public SearchIndexingBufferedSenderBuilder - onActionAdded(Consumer> onActionAddedConsumer) { + onActionAdded(Consumer onActionAddedConsumer) { this.onActionAddedConsumer = onActionAddedConsumer; return this; } @@ -856,7 +674,7 @@ public SearchIndexingBufferedSenderBuilder maxThrottlingDelay(Duration maxThr * @return The updated SearchIndexingBufferedSenderBuilder object. */ public SearchIndexingBufferedSenderBuilder - onActionSucceeded(Consumer> onActionSucceededConsumer) { + onActionSucceeded(Consumer onActionSucceededConsumer) { this.onActionSucceededConsumer = onActionSucceededConsumer; return this; } @@ -869,7 +687,7 @@ public SearchIndexingBufferedSenderBuilder maxThrottlingDelay(Duration maxThr * @return The updated SearchIndexingBufferedSenderBuilder object. */ public SearchIndexingBufferedSenderBuilder - onActionError(Consumer> onActionErrorConsumer) { + onActionError(Consumer onActionErrorConsumer) { this.onActionErrorConsumer = onActionErrorConsumer; return this; } @@ -881,8 +699,7 @@ public SearchIndexingBufferedSenderBuilder maxThrottlingDelay(Duration maxThr * request. * @return The updated SearchIndexingBufferedSenderBuilder object. */ - public SearchIndexingBufferedSenderBuilder - onActionSent(Consumer> onActionSentConsumer) { + public SearchIndexingBufferedSenderBuilder onActionSent(Consumer onActionSentConsumer) { this.onActionSentConsumer = onActionSentConsumer; return this; } @@ -894,10 +711,26 @@ public SearchIndexingBufferedSenderBuilder maxThrottlingDelay(Duration maxThr * @return The updated SearchIndexingBufferedSenderBuilder object. * @throws NullPointerException If {@code documentKeyRetriever} is null. */ - public SearchIndexingBufferedSenderBuilder documentKeyRetriever(Function documentKeyRetriever) { + public SearchIndexingBufferedSenderBuilder + documentKeyRetriever(Function, String> documentKeyRetriever) { this.documentKeyRetriever = Objects.requireNonNull(documentKeyRetriever, "'documentKeyRetriever' cannot be null"); 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 SearchIndexingBufferedSenderBuilder object. + */ + public SearchIndexingBufferedSenderBuilder serializer(JsonSerializer jsonSerializer) { + this.jsonSerializer = jsonSerializer; + return this; + } } + + @Generated + private String[] scopes = DEFAULT_SCOPES; } 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 index 42bd2f4236f1..847a672a30b9 100644 --- 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 @@ -4,10 +4,10 @@ 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.http.rest.RequestOptions; import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; +import com.azure.json.JsonProviders; +import com.azure.json.JsonReader; import com.azure.search.documents.implementation.batching.SearchIndexingAsyncPublisher; import com.azure.search.documents.models.IndexAction; import com.azure.search.documents.models.IndexActionType; @@ -20,6 +20,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collection; +import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicReference; @@ -27,8 +28,6 @@ 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. @@ -37,12 +36,12 @@ */ @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; + final SearchIndexingAsyncPublisher publisher; + private final JsonSerializer serializer; private Timer autoFlushTimer; private final AtomicReference flushTask = new AtomicReference<>(); @@ -50,20 +49,19 @@ public final class SearchIndexingBufferedAsyncSender { private volatile boolean isClosed = false; private final ReentrantLock closeLock = new ReentrantLock(); - SearchIndexingBufferedAsyncSender(SearchIndexClientImpl restClient, JsonSerializer serializer, - Function documentKeyRetriever, boolean autoFlush, Duration autoFlushInterval, + SearchIndexingBufferedAsyncSender(SearchAsyncClient searchAsyncClient, JsonSerializer serializer, + Function, String> 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); + Consumer onActionAdded, Consumer onActionSucceeded, + Consumer onActionError, Consumer onActionSent) { + this.publisher = new SearchIndexingAsyncPublisher(searchAsyncClient, documentKeyRetriever, autoFlush, + initialBatchActionCount, maxRetriesPerAction, throttlingDelay, maxThrottlingDelay, onActionAdded, + onActionSucceeded, onActionError, onActionSent); this.autoFlush = autoFlush; this.flushWindowMillis = Math.max(0, autoFlushInterval.toMillis()); this.autoFlushTimer = (this.autoFlush && this.flushWindowMillis > 0) ? new Timer() : null; + this.serializer = serializer; } @@ -72,7 +70,7 @@ public final class SearchIndexingBufferedAsyncSender { * * @return The {@link IndexAction IndexActions} in the batch that are ready to be indexed. */ - public Collection> getActions() { + public Collection getActions() { return publisher.getActions(); } @@ -97,7 +95,21 @@ int getBatchActionCount() { * @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)); + return addUploadActions(documents, null); + } + + /** + * 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 requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response indicating that the documents have been added to the batch. + */ + public Mono addUploadActions(Collection documents, RequestOptions requestOptions) { + return createAndAddActions(documents, IndexActionType.UPLOAD, requestOptions); } /** @@ -110,7 +122,21 @@ public Mono addUploadActions(Collection documents) { * @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)); + return addDeleteActions(documents, null); + } + + /** + * 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 requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response indicating that the documents have been added to the batch. + */ + public Mono addDeleteActions(Collection documents, RequestOptions requestOptions) { + return createAndAddActions(documents, IndexActionType.DELETE, requestOptions); } /** @@ -123,7 +149,21 @@ public Mono addDeleteActions(Collection documents) { * @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)); + return addMergeActions(documents, null); + } + + /** + * 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 requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response indicating that the documents have been added to the batch. + */ + public Mono addMergeActions(Collection documents, RequestOptions requestOptions) { + return createAndAddActions(documents, IndexActionType.MERGE, requestOptions); } /** @@ -136,7 +176,21 @@ public Mono addMergeActions(Collection documents) { * @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)); + return addMergeOrUploadActions(documents, null); + } + + /** + * 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 requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response indicating that the documents have been added to the batch. + */ + public Mono addMergeOrUploadActions(Collection documents, RequestOptions requestOptions) { + return createAndAddActions(documents, IndexActionType.MERGE_OR_UPLOAD, requestOptions); } /** @@ -148,18 +202,32 @@ public Mono addMergeOrUploadActions(Collection documents) { * @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)); + public Mono addActions(Collection actions) { + return addActions(actions, null); } - Mono createAndAddActions(Collection documents, IndexActionType actionType, Context context) { - return addActions(createDocumentActions(documents, actionType), 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. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response indicating that the documents have been added to the batch. + */ + public Mono addActions(Collection actions, RequestOptions requestOptions) { + return addActions(Mono.just(actions), requestOptions); } - Mono addActions(Collection> actions, Context context) { - ensureOpen(); + Mono createAndAddActions(Collection documents, IndexActionType actionType, RequestOptions requestOptions) { + return addActions(createDocumentActions(documents, actionType), requestOptions); + } - return publisher.addActions(actions, context, this::rescheduleFlushTask); + Mono addActions(Mono> actionsMono, RequestOptions requestOptions) { + return ensureOpen().then(actionsMono) + .flatMap( + actions -> publisher.addActions(actions, requestOptions, () -> rescheduleFlushTask(requestOptions))); } /** @@ -168,35 +236,41 @@ Mono addActions(Collection> actions, Context context) { * @return A reactive response that indicates if the flush operation has completed. */ public Mono flush() { - return withContext(this::flush); + return flush(null); } - Mono flush(Context context) { - ensureOpen(); - - rescheduleFlushTask(); - return publisher.flush(false, false, context); + /** + * Sends the current batch of documents to be indexed. + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response that indicates if the flush operation has completed. + */ + public Mono flush(RequestOptions requestOptions) { + return ensureOpen().then(rescheduleFlushTask(requestOptions)) + .then(publisher.flush(false, false, requestOptions)); } - private void rescheduleFlushTask() { - if (!autoFlush) { - return; - } - - TimerTask newTask = new TimerTask() { - @Override - public void run() { - Mono.defer(() -> publisher.flush(false, false, Context.NONE)).subscribe(); + private Mono rescheduleFlushTask(RequestOptions requestOptions) { + return Mono.fromRunnable(() -> { + if (!autoFlush) { + return; } - }; - // 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(); - } + TimerTask newTask = new TimerTask() { + @Override + public void run() { + Mono.defer(() -> publisher.flush(false, false, requestOptions)).subscribe(); + } + }; - this.autoFlushTimer.schedule(newTask, flushWindowMillis); + // 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); + }); } /** @@ -208,10 +282,19 @@ public void run() { * @return A reactive response indicating that the buffered sender has been closed. */ public Mono close() { - return withContext(this::close); + return close(null); } - Mono close(Context context) { + /** + * 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. + * + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. + * @return A reactive response indicating that the buffered sender has been closed. + */ + public Mono close(RequestOptions requestOptions) { if (!isClosed) { closeLock.lock(); try { @@ -228,7 +311,7 @@ Mono close(Context context) { autoFlushTimer = null; } - return publisher.flush(true, true, context); + return publisher.flush(true, true, requestOptions); } return Mono.empty(); @@ -240,20 +323,22 @@ Mono close(Context context) { return Mono.empty(); } - private void ensureOpen() { - if (isClosed) { - throw LOGGER.logExceptionAsError(new IllegalStateException("Buffered sender has been closed.")); - } + private Mono ensureOpen() { + return isClosed ? Mono.error(new IllegalStateException("Buffered sender has been closed.")) : Mono.empty(); } - private static Collection> createDocumentActions(Collection documents, - IndexActionType actionType) { - Collection> actions = new ArrayList<>(documents.size()); + private Mono> createDocumentActions(Collection documents, IndexActionType actionType) { + return Mono.fromCallable(() -> { + Collection actions = new ArrayList<>(documents.size()); - for (T document : documents) { - actions.add(new IndexAction().setActionType(actionType).setDocument(document)); - } + for (T document : documents) { + try (JsonReader jsonReader = JsonProviders.createReader(serializer.serializeToBytes(document))) { + actions.add(new IndexAction().setActionType(actionType) + .setAdditionalProperties(jsonReader.readMap(JsonReader::readUntyped))); + } + } - return actions; + 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 index 52185156e3d7..668425cfe813 100644 --- 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 @@ -4,10 +4,11 @@ package com.azure.search.documents; import com.azure.core.annotation.ServiceClient; -import com.azure.core.util.Context; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.implementation.SearchIndexClientImpl; +import com.azure.json.JsonProviders; +import com.azure.json.JsonReader; import com.azure.search.documents.implementation.batching.SearchIndexingPublisher; import com.azure.search.documents.models.IndexAction; import com.azure.search.documents.models.IndexActionType; @@ -16,9 +17,12 @@ import com.azure.search.documents.options.OnActionSentOptions; import com.azure.search.documents.options.OnActionSucceededOptions; +import java.io.IOException; +import java.io.UncheckedIOException; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; +import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; @@ -26,6 +30,7 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Supplier; /** * This class provides a buffered sender that contains operations for conveniently indexing documents to an Azure Search @@ -41,6 +46,7 @@ public final class SearchIndexingBufferedSender { private final long flushWindowMillis; final SearchIndexingPublisher publisher; + private final JsonSerializer serializer; private Timer autoFlushTimer; @@ -52,20 +58,19 @@ public final class SearchIndexingBufferedSender { private final AtomicBoolean closed = new AtomicBoolean(); private final ReentrantLock closeLock = new ReentrantLock(); - SearchIndexingBufferedSender(SearchIndexClientImpl restClient, JsonSerializer serializer, - Function documentKeyRetriever, boolean autoFlush, Duration autoFlushInterval, + SearchIndexingBufferedSender(SearchClient searchClient, JsonSerializer serializer, + Function, String> 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); + Consumer onActionAdded, Consumer onActionSucceeded, + Consumer onActionError, Consumer onActionSent) { + this.publisher = new SearchIndexingPublisher<>(searchClient, documentKeyRetriever, autoFlush, + initialBatchActionCount, maxRetriesPerAction, throttlingDelay, maxThrottlingDelay, onActionAdded, + onActionSucceeded, onActionError, onActionSent); this.autoFlush = autoFlush; this.flushWindowMillis = Math.max(0, autoFlushInterval.toMillis()); this.autoFlushTimer = (this.autoFlush && this.flushWindowMillis > 0) ? new Timer() : null; + this.serializer = serializer; } /** @@ -73,7 +78,7 @@ public final class SearchIndexingBufferedSender { * * @return The list of {@link IndexAction IndexActions} in the batch that are ready to be indexed. */ - public Collection> getActions() { + public Collection getActions() { return publisher.getActions(); } @@ -97,7 +102,7 @@ int getBatchActionCount() { * @param documents Documents to be uploaded. */ public void addUploadActions(Collection documents) { - addUploadActions(documents, null, Context.NONE); + addUploadActions(documents, null, null); } /** @@ -108,10 +113,10 @@ public void addUploadActions(Collection documents) { * * @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. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void addUploadActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.UPLOAD, timeout, context); + public void addUploadActions(Collection documents, Duration timeout, RequestOptions requestOptions) { + createAndAddActions(documents, IndexActionType.UPLOAD, timeout, requestOptions); } /** @@ -123,7 +128,7 @@ public void addUploadActions(Collection documents, Duration timeout, Context * @param documents Documents to be deleted. */ public void addDeleteActions(Collection documents) { - addDeleteActions(documents, null, Context.NONE); + addDeleteActions(documents, null, null); } /** @@ -134,10 +139,10 @@ public void addDeleteActions(Collection documents) { * * @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. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void addDeleteActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.DELETE, timeout, context); + public void addDeleteActions(Collection documents, Duration timeout, RequestOptions requestOptions) { + createAndAddActions(documents, IndexActionType.DELETE, timeout, requestOptions); } /** @@ -149,7 +154,7 @@ public void addDeleteActions(Collection documents, Duration timeout, Context * @param documents Documents to be merged. */ public void addMergeActions(Collection documents) { - addMergeActions(documents, null, Context.NONE); + addMergeActions(documents, null, null); } /** @@ -160,10 +165,10 @@ public void addMergeActions(Collection documents) { * * @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. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void addMergeActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.MERGE, timeout, context); + public void addMergeActions(Collection documents, Duration timeout, RequestOptions requestOptions) { + createAndAddActions(documents, IndexActionType.MERGE, timeout, requestOptions); } /** @@ -175,7 +180,7 @@ public void addMergeActions(Collection documents, Duration timeout, Context c * @param documents Documents to be merged or uploaded. */ public void addMergeOrUploadActions(Collection documents) { - addMergeOrUploadActions(documents, null, Context.NONE); + addMergeOrUploadActions(documents, null, null); } /** @@ -186,10 +191,10 @@ public void addMergeOrUploadActions(Collection documents) { * * @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. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void addMergeOrUploadActions(Collection documents, Duration timeout, Context context) { - createAndAddActions(documents, IndexActionType.MERGE_OR_UPLOAD, timeout, context); + public void addMergeOrUploadActions(Collection documents, Duration timeout, RequestOptions requestOptions) { + createAndAddActions(documents, IndexActionType.MERGE_OR_UPLOAD, timeout, requestOptions); } /** @@ -200,8 +205,8 @@ public void addMergeOrUploadActions(Collection documents, Duration timeout, C * * @param actions Index actions. */ - public void addActions(Collection> actions) { - addActions(actions, null, Context.NONE); + public void addActions(Collection actions) { + addActions(actions, null, null); } /** @@ -212,44 +217,46 @@ public void addActions(Collection> actions) { * * @param actions Index actions. * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void addActions(Collection> actions, Duration timeout, Context context) { - addActionsInternal(actions, timeout, context); + public void addActions(Collection actions, Duration timeout, RequestOptions requestOptions) { + addActionsInternal(() -> actions, timeout, requestOptions); } - void createAndAddActions(Collection documents, IndexActionType actionType, Duration timeout, Context context) { - addActionsInternal(createDocumentActions(documents, actionType), timeout, context); + void createAndAddActions(Collection documents, IndexActionType actionType, Duration timeout, + RequestOptions requestOptions) { + addActionsInternal(createDocumentActions(documents, actionType), timeout, requestOptions); } - void addActionsInternal(Collection> actions, Duration timeout, Context context) { + void addActionsInternal(Supplier> actions, Duration timeout, + RequestOptions requestOptions) { ensureOpen(); - publisher.addActions(actions, timeout, context, this::rescheduleFlushTask); + publisher.addActions(actions.get(), timeout, requestOptions, this::rescheduleFlushTask); } /** * Sends the current batch of documents to be indexed. */ public void flush() { - flush(null, Context.NONE); + flush(null, null); } /** * 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. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void flush(Duration timeout, Context context) { - flushInternal(timeout, context); + public void flush(Duration timeout, RequestOptions requestOptions) { + flushInternal(timeout, requestOptions); } - void flushInternal(Duration timeout, Context context) { + void flushInternal(Duration timeout, RequestOptions requestOptions) { ensureOpen(); rescheduleFlushTask(); - publisher.flush(false, false, timeout, context); + publisher.flush(false, false, timeout, requestOptions); } private void rescheduleFlushTask() { @@ -260,7 +267,7 @@ private void rescheduleFlushTask() { TimerTask newTask = new TimerTask() { @Override public void run() { - publisher.flush(false, false, null, Context.NONE); + publisher.flush(false, false, null, null); } }; @@ -280,7 +287,7 @@ public void run() { * IllegalStateException} to be thrown. */ public void close() { - close(null, Context.NONE); + close(null, null); } /** @@ -290,13 +297,13 @@ public void close() { * IllegalStateException} to be thrown. * * @param timeout Duration before the operation times out. - * @param context Additional context that is passed through the HTTP pipeline. + * @param requestOptions The options to configure the HTTP request before HTTP client sends it. */ - public void close(Duration timeout, Context context) { - closeInternal(timeout, context); + public void close(Duration timeout, RequestOptions requestOptions) { + closeInternal(timeout, requestOptions); } - void closeInternal(Duration timeout, Context context) { + void closeInternal(Duration timeout, RequestOptions requestOptions) { if (!closed.get()) { closeLock.lock(); try { @@ -312,7 +319,7 @@ void closeInternal(Duration timeout, Context context) { autoFlushTimer = null; } - publisher.flush(true, true, timeout, context); + publisher.flush(true, true, timeout, requestOptions); } } finally { closeLock.unlock(); @@ -326,14 +333,21 @@ private void ensureOpen() { } } - private static Collection> createDocumentActions(Collection documents, + private Supplier> createDocumentActions(Collection documents, IndexActionType actionType) { - Collection> actions = new ArrayList<>(documents.size()); - - for (T document : documents) { - actions.add(new IndexAction().setActionType(actionType).setDocument(document)); - } + return () -> { + Collection actions = new ArrayList<>(documents.size()); + + for (T document : documents) { + try (JsonReader jsonReader = JsonProviders.createReader(serializer.serializeToBytes(document))) { + actions.add(new IndexAction().setActionType(actionType) + .setAdditionalProperties(jsonReader.readMap(JsonReader::readUntyped))); + } catch (IOException ex) { + throw LOGGER.atError().log(new UncheckedIOException(ex)); + } + } - return actions; + 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 92ef25a86b1d..5b5f3c1d5a6c 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,36 +1,17 @@ // 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. - */ - V2024_07_01("2024-07-01"), - - /** - * {@code 2025-09-01} service version. - */ - V2025_09_01("2025-09-01"), - - /** - * {@code 2025-11-01-preview} service version. + * Enum value 2025-11-01-preview. */ V2025_11_01_PREVIEW("2025-11-01-preview"); @@ -50,8 +31,8 @@ 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 V2025_11_01_PREVIEW; 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 deleted file mode 100644 index 6302ba602bf4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/DocumentsImpl.java +++ /dev/null @@ -1,944 +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.annotation.BodyParam; -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.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.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 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. - */ - private final DocumentsService service; - - /** - * The service client containing this operation class. - */ - private final SearchIndexClientImpl client; - - /** - * Initializes an instance of DocumentsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - DocumentsImpl(SearchIndexClientImpl 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. - */ - @Host("{endpoint}/indexes('{indexName}')") - @ServiceInterface(name = "SearchIndexClientDocuments") - public interface DocumentsService { - - @Get("/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); - - @Get("/docs/$count") - @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); - - @Post("/docs/search.post.search") - @ExpectedResponses({ 200, 206 }) - @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("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, - @HeaderParam("x-ms-enable-elevated-read") Boolean xMsEnableElevatedRead, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchRequest searchRequest, - Context context); - - @Post("/docs/search.post.search") - @ExpectedResponses({ 200, 206 }) - @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("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, - @HeaderParam("x-ms-enable-elevated-read") Boolean xMsEnableElevatedRead, - @HeaderParam("Accept") String accept, @BodyParam("application/json") SearchRequest searchRequest, - Context context); - - @Get("/docs('{key}')") - @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("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, - @HeaderParam("x-ms-enable-elevated-read") Boolean xMsEnableElevatedRead, - @HeaderParam("Accept") String accept, Context context); - - @Get("/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("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, - @HeaderParam("x-ms-enable-elevated-read") Boolean xMsEnableElevatedRead, - @HeaderParam("Accept") String accept, Context context); - - @Post("/docs/search.post.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); - - @Post("/docs/search.post.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); - - @Post("/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); - - @Post("/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); - - @Post("/docs/search.post.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); - - @Post("/docs/search.post.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)); - } - - /** - * 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())); - } - - /** - * 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())); - } - - /** - * 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}. - */ - @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); - } - - /** - * 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. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public long count(RequestOptions requestOptions) { - return countWithResponse(requestOptions, Context.NONE).getValue(); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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 along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> searchPostWithResponseAsync(SearchRequest searchRequest, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> searchPostWithResponseAsync(searchRequest, xMsQuerySourceAuthorization, - xMsEnableElevatedRead, requestOptions, context)); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, 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, xMsQuerySourceAuthorization, xMsEnableElevatedRead, accept, searchRequest, context); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono searchPostAsync(SearchRequest searchRequest, String xMsQuerySourceAuthorization, - Boolean xMsEnableElevatedRead, RequestOptions requestOptions) { - return searchPostWithResponseAsync(searchRequest, xMsQuerySourceAuthorization, xMsEnableElevatedRead, - requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono searchPostAsync(SearchRequest searchRequest, String xMsQuerySourceAuthorization, - Boolean xMsEnableElevatedRead, RequestOptions requestOptions, Context context) { - return searchPostWithResponseAsync(searchRequest, xMsQuerySourceAuthorization, xMsEnableElevatedRead, - requestOptions, context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response searchPostWithResponse(SearchRequest searchRequest, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, 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, xMsQuerySourceAuthorization, xMsEnableElevatedRead, accept, - searchRequest, context); - } - - /** - * Searches for documents in the index. - * - * @param searchRequest The definition of the Search request. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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, String xMsQuerySourceAuthorization, - Boolean xMsEnableElevatedRead, RequestOptions requestOptions) { - return searchPostWithResponse(searchRequest, xMsQuerySourceAuthorization, xMsEnableElevatedRead, 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 xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(key, selectedFields, xMsQuerySourceAuthorization, - xMsEnableElevatedRead, requestOptions, 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 xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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 along with {@link Response} on successful completion - * of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono>> getWithResponseAsync(String key, List selectedFields, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, 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, xMsQuerySourceAuthorization, xMsEnableElevatedRead, 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 xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, RequestOptions requestOptions) { - return getWithResponseAsync(key, selectedFields, xMsQuerySourceAuthorization, xMsEnableElevatedRead, - 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 xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, RequestOptions requestOptions, - Context context) { - return getWithResponseAsync(key, selectedFields, xMsQuerySourceAuthorization, xMsEnableElevatedRead, - requestOptions, context).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 xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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 along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response> getWithResponse(String key, List selectedFields, - String xMsQuerySourceAuthorization, Boolean xMsEnableElevatedRead, 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, xMsQuerySourceAuthorization, xMsEnableElevatedRead, 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 xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @param xMsEnableElevatedRead A value that enables elevated read that bypass document level permission checks for - * the query operation. - * @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, String xMsQuerySourceAuthorization, - Boolean xMsEnableElevatedRead, RequestOptions requestOptions) { - return getWithResponse(key, selectedFields, xMsQuerySourceAuthorization, xMsEnableElevatedRead, requestOptions, - Context.NONE).getValue(); - } - - /** - * 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. - * @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); - } - - /** - * 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}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono suggestPostAsync(SuggestRequest suggestRequest, RequestOptions requestOptions) { - return suggestPostWithResponseAsync(suggestRequest, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * 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. - * @return response containing suggestion query results from an index 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())); - } - - /** - * 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. - * @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, - 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())); - } - - /** - * 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}. - */ - @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); - } - - /** - * 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. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public IndexDocumentsResult index(IndexBatch batch, RequestOptions requestOptions) { - return indexWithResponse(batch, requestOptions, Context.NONE).getValue(); - } - - /** - * 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. - * @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); - } - - /** - * 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}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono autocompletePostAsync(AutocompleteRequest autocompleteRequest, - RequestOptions requestOptions) { - return autocompletePostWithResponseAsync(autocompleteRequest, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * 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. - * @return the result of Autocomplete query 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())); - } - - /** - * 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. - * @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(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/FieldBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/FieldBuilder.java new file mode 100644 index 000000000000..715853758f99 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/FieldBuilder.java @@ -0,0 +1,388 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.search.documents.implementation; + +import com.azure.core.models.GeoPoint; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; +import com.azure.search.documents.indexes.BasicField; +import com.azure.search.documents.indexes.ComplexField; +import com.azure.search.documents.indexes.models.LexicalAnalyzerName; +import com.azure.search.documents.indexes.models.LexicalNormalizerName; +import com.azure.search.documents.indexes.models.PermissionFilter; +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 java.lang.reflect.AccessibleObject; +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.List; +import java.util.Map; +import java.util.Stack; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * Helper to convert model class to {@link SearchField SearchFields}. + *

+ * {@link FieldBuilder} only inspects {@link Field fields} and {@link Method methods} declared by the model, and uses + * the following rules for creating {@link SearchField SearchFields}: + *

    + *
  • If the field or method is annotated with {@link BasicField} the {@link SearchFieldDataType} inferred by the + * type of the field or return type of the method cannot be {@link SearchFieldDataType#COMPLEX}. It may be a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} though.
  • + *
  • If the field or method is annotated with {@link ComplexField} the {@link SearchFieldDataType} inferred by the + * type of the field or return type of the method must be {@link SearchFieldDataType#COMPLEX}. It may be a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} of {@link SearchFieldDataType#COMPLEX}.
  • + *
  • If the field or method isn't annotated with either {@link BasicField} or {@link ComplexField} it will be + * ignored.
  • + *
+ *

+ * If the type of the field or return type of the method is an array or {@link Iterable} it will be considered a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} type. Nested + * {@link SearchFieldDataType#collection(SearchFieldDataType)} aren't allowed and will throw an exception, ex. + * {@code String[][]} or {@code List>}. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Conversion of Java type to {@link SearchFieldDataType}
Java type{@link SearchFieldDataType}
{@code byte}{@link SearchFieldDataType#SBYTE}
{@link Byte}{@link SearchFieldDataType#SBYTE}
{@code boolean}{@link SearchFieldDataType#BOOLEAN}
{@link Boolean}{@link SearchFieldDataType#BOOLEAN}
{@code short}{@link SearchFieldDataType#INT16}
{@link Short}{@link SearchFieldDataType#INT16}
{@code int}{@link SearchFieldDataType#INT32}
{@link Integer}{@link SearchFieldDataType#INT32}
{@code long}{@link SearchFieldDataType#INT64}
{@link Long}{@link SearchFieldDataType#INT64}
{@code float}{@link SearchFieldDataType#SINGLE}
{@link Float}{@link SearchFieldDataType#SINGLE}
{@code double}{@link SearchFieldDataType#DOUBLE}
{@link Double}{@link SearchFieldDataType#DOUBLE}
{@code char}{@link SearchFieldDataType#STRING}
{@link Character}{@link SearchFieldDataType#STRING}
{@link CharSequence}{@link SearchFieldDataType#STRING}
{@link String}{@link SearchFieldDataType#STRING}
{@link Date}{@link SearchFieldDataType#DATE_TIME_OFFSET}
{@link OffsetDateTime}{@link SearchFieldDataType#DATE_TIME_OFFSET}
{@link GeoPoint}{@link SearchFieldDataType#GEOGRAPHY_POINT}
Any other typeAttempted to be consumed as {@link SearchFieldDataType#COMPLEX}
+ *

+ * {@link SearchFieldDataType#HALF} and {@link SearchFieldDataType#BYTE} aren't supported by {@link Field} given there + * isn't a built-in Java type that represents them. + *

+ * When generating {@link SearchField SearchFields} there is a maximum class depth limit of {@code 1000} before an + * exception will be thrown. + */ +public final class FieldBuilder { + private static final ClientLogger LOGGER = new ClientLogger(FieldBuilder.class); + + private static final int MAX_DEPTH = 1000; + private static final Map SUPPORTED_NONE_PARAMETERIZED_TYPE = new HashMap<>(); + + 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); + 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); + //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); + } + + /** + * 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. + * @return A collection of fields. + */ + public static List build(Class modelClass) { + return build(modelClass, new Stack<>()); + } + + /** + * 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) { + if (classChain.contains(currentClass)) { + LOGGER.warning("There is circular dependencies {}, {}", classChain, currentClass); + return null; + } + + if (classChain.size() > MAX_DEPTH) { + throw LOGGER.atError() + .log(new IllegalStateException("The dependency graph is too deep. Please review your schema.")); + } + + classChain.push(currentClass); + List searchFields = new ArrayList<>(); + for (Field field : currentClass.getDeclaredFields()) { + SearchField searchField = createSearchField(field, Field::getGenericType, classChain); + if (searchField != null) { + searchFields.add(searchField); + } + } + for (Method method : currentClass.getDeclaredMethods()) { + SearchField searchField = createSearchField(method, Method::getGenericReturnType, classChain); + if (searchField != null) { + searchFields.add(searchField); + } + } + classChain.pop(); + return searchFields; + } + + private static SearchField createSearchField(T fieldOrMethod, + Function typeGetter, Stack> stack) { + BasicField basicField = fieldOrMethod.getAnnotation(BasicField.class); + ComplexField complexField = fieldOrMethod.getAnnotation(ComplexField.class); + + if (basicField != null && complexField != null) { + throw LOGGER.atError() + .addKeyValue("fieldOrMethodName", fieldOrMethod.getName()) + .addKeyValue("fieldOrMemberDeclaringClass", fieldOrMethod.getDeclaringClass()) + .log(new IllegalStateException("Field or method may only be annotated with one of 'BasicField', " + + "or 'ComplexField' at a time.")); + } else if (basicField != null) { + return generateBasicField(typeGetter.apply(fieldOrMethod), basicField, fieldOrMethod); + } else if (complexField != null) { + return generateComplexField(typeGetter.apply(fieldOrMethod), complexField, fieldOrMethod, stack); + } + + return null; + } + + private static SearchField generateBasicField(Type type, BasicField basicField, Member member) { + SearchFieldDataType basicDataType = SUPPORTED_NONE_PARAMETERIZED_TYPE.get(type); + if (basicDataType != null) { + SearchField searchField = new SearchField(basicField.name(), basicDataType); + return enrichBasicSearchField(searchField, basicField, member); + } + + Type collectionType = getCollectionType(type, member); + if (collectionType != null) { + SearchFieldDataType collectionDataType = SUPPORTED_NONE_PARAMETERIZED_TYPE.get(collectionType); + if (collectionDataType != null) { + SearchField searchField + = new SearchField(basicField.name(), SearchFieldDataType.collection(collectionDataType)); + return enrichBasicSearchField(searchField, basicField, member); + } + } + + throw LOGGER.atError() + .addKeyValue("fieldOrMethodName", member.getName()) + .addKeyValue("fieldOrMemberDeclaringClass", member.getDeclaringClass()) + .log(new IllegalStateException( + "'BasicField' cannot be used on fields or methods which result in 'SearchFieldDataType.COMPLEX'.")); + } + + private static SearchField generateComplexField(Type type, ComplexField complexField, Member member, + Stack> stack) { + if (SUPPORTED_NONE_PARAMETERIZED_TYPE.containsKey(type)) { + throw LOGGER.atError() + .addKeyValue("fieldOrMethodName", member.getName()) + .addKeyValue("fieldOrMemberDeclaringClass", member.getDeclaringClass()) + .log(new IllegalStateException("'ComplexField' cannot be used on fields or methods which don't result " + + "in 'SearchFieldDataType.COMPLEX'.")); + } + + Type collectionType = getCollectionType(type, member); + if (collectionType != null) { + if (SUPPORTED_NONE_PARAMETERIZED_TYPE.containsKey(collectionType)) { + throw LOGGER.atError() + .addKeyValue("fieldOrMethodName", member.getName()) + .addKeyValue("fieldOrMemberDeclaringClass", member.getDeclaringClass()) + .log(new IllegalStateException("'ComplexField' cannot be used on fields or methods which don't " + + "result in 'SearchFieldDataType.COMPLEX'.")); + } + + return new SearchField(complexField.name(), SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)) + .setFields(build((Class) collectionType, stack)); + } + + return new SearchField(complexField.name(), SearchFieldDataType.COMPLEX) + .setFields(build((Class) type, stack)); + } + + private static Type getCollectionType(Type type, Member member) { + Type collectionType = null; + if (isArrayOrIterable(type)) { + collectionType = getComponentOrElementType(type); + } + + if (collectionType != null && isArrayOrIterable(collectionType)) { + throw LOGGER.atError() + .addKeyValue("fieldOrMethodName", member.getName()) + .addKeyValue("fieldOrMemberDeclaringClass", member.getDeclaringClass()) + .log(new IllegalStateException("Field or method annotated with 'BasicField' or 'ComplexField' cannot " + + "be a nested array or Iterable.")); + } + + return collectionType; + } + + private static boolean isArrayOrIterable(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 Iterable.class.isAssignableFrom((Class) rawType); + } + + 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 enrichBasicSearchField(SearchField searchField, BasicField basicField, Member member) { + searchField.setKey(toBoolean(basicField.isKey())) + .setHidden(toBoolean(basicField.isHidden())) + .setRetrievable(toBoolean(basicField.isRetrievable())) + .setStored(toBoolean(basicField.isStored())) + .setSearchable(toBoolean(basicField.isSearchable())) + .setFilterable(toBoolean(basicField.isFilterable())) + .setSortable(toBoolean(basicField.isSortable())) + .setFacetable(toBoolean(basicField.isFacetable())) + .setPermissionFilter(nullOrT(basicField.permissionFilter(), PermissionFilter::fromString)) + .setSensitivityLabel(toBoolean(basicField.isSensitivityLabel())) + .setAnalyzerName(nullOrT(basicField.analyzerName(), LexicalAnalyzerName::fromString)) + .setSearchAnalyzerName(nullOrT(basicField.searchAnalyzerName(), LexicalAnalyzerName::fromString)) + .setIndexAnalyzerName(nullOrT(basicField.indexAnalyzerName(), LexicalAnalyzerName::fromString)) + .setNormalizerName(nullOrT(basicField.normalizerName(), LexicalNormalizerName::fromString)) + .setVectorSearchDimensions( + basicField.vectorSearchDimensions() > 0 ? basicField.vectorSearchDimensions() : null) + .setVectorSearchProfileName(nullOrT(basicField.vectorSearchProfileName(), Function.identity())) + .setVectorEncodingFormat(nullOrT(basicField.vectorEncodingFormat(), VectorEncodingFormat::fromString)) + .setSynonymMapNames(synonymMapNames(basicField.synonymMapNames())); + + StringBuilder errorMessage = new StringBuilder(); + boolean isStringOrCollectionString + = searchField.getType() == SearchFieldDataType.STRING || searchField.getType() == COLLECTION_STRING; + boolean isSearchableType = isStringOrCollectionString || searchField.getType() == COLLECTION_SINGLE; + boolean hasAnalyzerName = searchField.getAnalyzerName() != null; + boolean hasSearchAnalyzerName = searchField.getSearchAnalyzerName() != null; + boolean hasIndexAnalyzerName = searchField.getIndexAnalyzerName() != null; + if (searchField.isHidden() != null + && searchField.isRetrievable() != null + && searchField.isHidden() == searchField.isRetrievable()) { + errorMessage.append("'isHidden' and 'isRetrievable' were set to the same boolean value, this is " + + "invalid as they have opposite meanings and therefore the configuration is ambiguous."); + } + if (Boolean.TRUE.equals(searchField.isSearchable())) { + 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. "); + } + } + + // Any field is allowed to have a normalizer, but it must be either a STRING or Collection(STRING) and have one + // of filterable, sortable, or facetable set to true. + if (searchField.getNormalizerName() != null + && (!isStringOrCollectionString + || !(Boolean.TRUE.equals(searchField.isFilterable()) + || Boolean.TRUE.equals(searchField.isSortable()) + || Boolean.TRUE.equals(searchField.isFacetable())))) { + errorMessage.append("A field with a normalizer name can only be used on string properties and must have ") + .append("one of filterable, sortable, or facetable set to true. "); + } + + if ((searchField.getVectorSearchDimensions() != null && searchField.getVectorSearchProfileName() == null) + || (searchField.getVectorSearchDimensions() == null && searchField.getVectorSearchProfileName() != null)) { + errorMessage + .append("Please specify both vectorSearchDimensions and vectorSearchProfileName for vector field. "); + } + + if (errorMessage.length() > 0) { + throw LOGGER.logExceptionAsError(new IllegalStateException(errorMessage.toString())); + } + + return searchField; + } + + private static Boolean toBoolean(BasicField.BooleanHelper booleanHelper) { + if (booleanHelper == null || booleanHelper == BasicField.BooleanHelper.NULL) { + return null; + } else { + return booleanHelper == BasicField.BooleanHelper.TRUE; + } + } + + private static T nullOrT(String raw, Function converter) { + return CoreUtils.isNullOrEmpty(raw) ? null : converter.apply(raw); + } + + private static List synonymMapNames(String[] synonyms) { + if (CoreUtils.isNullOrEmpty(synonyms)) { + return null; + } + return Arrays.stream(synonyms).filter(synonym -> !synonym.trim().isEmpty()).collect(Collectors.toList()); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/KnowledgeBaseRetrievalClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/KnowledgeBaseRetrievalClientImpl.java new file mode 100644 index 000000000000..d19ff13c588d --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/KnowledgeBaseRetrievalClientImpl.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.implementation; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +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.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.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 reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the KnowledgeBaseRetrievalClient type. + */ +public final class KnowledgeBaseRetrievalClientImpl { + /** + * The proxy service used to perform REST calls. + */ + private final KnowledgeBaseRetrievalClientService 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; + } + + /** + * Initializes an instance of KnowledgeBaseRetrievalClient client. + * + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public KnowledgeBaseRetrievalClientImpl(String endpoint, SearchServiceVersion serviceVersion) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of KnowledgeBaseRetrievalClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public KnowledgeBaseRetrievalClientImpl(HttpPipeline httpPipeline, String endpoint, + SearchServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of KnowledgeBaseRetrievalClient 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 KnowledgeBaseRetrievalClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, + String endpoint, SearchServiceVersion serviceVersion) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.serviceVersion = serviceVersion; + this.service = RestProxy.create(KnowledgeBaseRetrievalClientService.class, this.httpPipeline, + this.getSerializerAdapter()); + } + + /** + * The interface defining all the services for KnowledgeBaseRetrievalClient to be used by the proxy service to + * perform REST calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "KnowledgeBaseRetrievalClient") + public interface KnowledgeBaseRetrievalClientService { + @Post("/retrieve/{knowledgeBaseName}") + @ExpectedResponses({ 200, 206 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> retrieve(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("knowledgeBaseName") String knowledgeBaseName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData retrievalRequest, RequestOptions requestOptions, Context context); + + @Post("/retrieve/{knowledgeBaseName}") + @ExpectedResponses({ 200, 206 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response retrieveSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("knowledgeBaseName") String knowledgeBaseName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData retrievalRequest, RequestOptions requestOptions, Context context); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     messages (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     intents (Optional): [
+     *          (Optional){
+     *             type: String(semantic) (Required)
+     *         }
+     *     ]
+     *     maxRuntimeInSeconds: Integer (Optional)
+     *     maxOutputSize: Integer (Optional)
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     includeActivity: Boolean (Optional)
+     *     outputMode: String(extractiveData/answerSynthesis) (Optional)
+     *     knowledgeSourceParams (Optional): [
+     *          (Optional){
+     *             kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             knowledgeSourceName: String (Required)
+     *             includeReferences: Boolean (Optional)
+     *             includeReferenceSourceData: Boolean (Optional)
+     *             alwaysQuerySource: Boolean (Optional)
+     *             rerankerThreshold: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     response (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     activity (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint/modelQueryPlanning/modelAnswerSynthesis/agenticReasoning) (Required)
+     *             id: int (Required)
+     *             elapsedMs: Integer (Optional)
+     *             error (Optional): {
+     *                 code: String (Optional)
+     *                 message: String (Optional)
+     *                 target: String (Optional)
+     *                 details (Optional): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *                 additionalInfo (Optional): [
+     *                      (Optional){
+     *                         type: String (Optional)
+     *                         info (Optional): {
+     *                             String: Object (Required)
+     *                         }
+     *                     }
+     *                 ]
+     *             }
+     *         }
+     *     ]
+     *     references (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             id: String (Required)
+     *             activitySource: int (Required)
+     *             sourceData (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *             rerankerScore: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @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 output contract for the retrieval response along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> retrieveWithResponseAsync(String knowledgeBaseName, BinaryData retrievalRequest, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil + .withContext(context -> service.retrieve(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + knowledgeBaseName, contentType, retrievalRequest, requestOptions, context)); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     messages (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     intents (Optional): [
+     *          (Optional){
+     *             type: String(semantic) (Required)
+     *         }
+     *     ]
+     *     maxRuntimeInSeconds: Integer (Optional)
+     *     maxOutputSize: Integer (Optional)
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     includeActivity: Boolean (Optional)
+     *     outputMode: String(extractiveData/answerSynthesis) (Optional)
+     *     knowledgeSourceParams (Optional): [
+     *          (Optional){
+     *             kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             knowledgeSourceName: String (Required)
+     *             includeReferences: Boolean (Optional)
+     *             includeReferenceSourceData: Boolean (Optional)
+     *             alwaysQuerySource: Boolean (Optional)
+     *             rerankerThreshold: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     response (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     activity (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint/modelQueryPlanning/modelAnswerSynthesis/agenticReasoning) (Required)
+     *             id: int (Required)
+     *             elapsedMs: Integer (Optional)
+     *             error (Optional): {
+     *                 code: String (Optional)
+     *                 message: String (Optional)
+     *                 target: String (Optional)
+     *                 details (Optional): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *                 additionalInfo (Optional): [
+     *                      (Optional){
+     *                         type: String (Optional)
+     *                         info (Optional): {
+     *                             String: Object (Required)
+     *                         }
+     *                     }
+     *                 ]
+     *             }
+     *         }
+     *     ]
+     *     references (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             id: String (Required)
+     *             activitySource: int (Required)
+     *             sourceData (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *             rerankerScore: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @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 output contract for the retrieval response along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response retrieveWithResponse(String knowledgeBaseName, BinaryData retrievalRequest, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.retrieveSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + knowledgeBaseName, contentType, retrievalRequest, requestOptions, Context.NONE); + } +} 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..6638ba3600e5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchClientImpl.java @@ -0,0 +1,2395 @@ +// 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.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.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.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 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Initializes an instance of SearchClient client. + * + * @param endpoint Service host. + * @param indexName The name of the index. + * @param serviceVersion Service version. + */ + public SearchClientImpl(String endpoint, String indexName, SearchServiceVersion serviceVersion) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, indexName, serviceVersion); + } + + /** + * Initializes an instance of SearchClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param endpoint Service host. + * @param indexName The name of the index. + * @param serviceVersion Service version. + */ + public SearchClientImpl(HttpPipeline httpPipeline, String endpoint, String indexName, + SearchServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, indexName, 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 indexName The name of the index. + * @param serviceVersion Service version. + */ + public SearchClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, + String indexName, SearchServiceVersion serviceVersion) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.indexName = indexName; + this.serviceVersion = serviceVersion; + 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("/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> getDocumentCount(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @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) + Response getDocumentCountSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/docs") + @ExpectedResponses({ 200, 206 }) + @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, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/docs") + @ExpectedResponses({ 200, 206 }) + @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, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @Post("/indexes('{indexName}')/docs/search.post.search") + @ExpectedResponses({ 200, 206 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> search(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData searchPostRequest, RequestOptions requestOptions, + Context context); + + @Post("/indexes('{indexName}')/docs/search.post.search") + @ExpectedResponses({ 200, 206 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response searchSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData searchPostRequest, 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) + Mono> getDocument(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("key") String key, @PathParam("indexName") String indexName, 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 getDocumentSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("key") String key, @PathParam("indexName") String indexName, RequestOptions requestOptions, + Context context); + + @Get("/indexes('{indexName}')/docs/search.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> suggestGet(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @QueryParam("search") String searchText, @QueryParam("suggesterName") String suggesterName, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/docs/search.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 suggestGetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @QueryParam("search") String searchText, @QueryParam("suggesterName") String suggesterName, + @PathParam("indexName") String indexName, 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) + Mono> suggest(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData suggestPostRequest, 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 suggestSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData suggestPostRequest, RequestOptions requestOptions, + Context context); + + @Post("/indexes('{indexName}')/docs/search.index") + @ExpectedResponses({ 200, 207 }) + @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, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData batch, RequestOptions requestOptions, Context context); + + @Post("/indexes('{indexName}')/docs/search.index") + @ExpectedResponses({ 200, 207 }) + @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, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData batch, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/docs/search.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> autocompleteGet(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @QueryParam("search") String searchText, @QueryParam("suggesterName") String suggesterName, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @Get("/indexes('{indexName}')/docs/search.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 autocompleteGetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @QueryParam("search") String searchText, @QueryParam("suggesterName") String suggesterName, + @PathParam("indexName") String indexName, RequestOptions requestOptions, Context context); + + @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> autocomplete(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData autocompletePostRequest, RequestOptions requestOptions, + Context context); + + @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 autocompleteSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String indexName, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData autocompletePostRequest, RequestOptions requestOptions, + Context context); + } + + /** + * Queries the number of documents in the index. + *

Response Body Schema

+ * + *
+     * {@code
+     * long
+     * }
+     * 
+ * + * @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 64-bit integer along with {@link Response} on successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getDocumentCountWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return FluxUtil.withContext(context -> service.getDocumentCount(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, this.getIndexName(), requestOptions, context)); + } + + /** + * Queries the number of documents in the index. + *

Response Body Schema

+ * + *
+     * {@code
+     * long
+     * }
+     * 
+ * + * @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 64-bit integer along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getDocumentCountWithResponse(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return service.getDocumentCountSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + this.getIndexName(), requestOptions, Context.NONE); + } + + /** + * 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", "innerHits", "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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (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 containing search results from an index along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> searchGetWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return FluxUtil.withContext(context -> service.searchGet(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, this.getIndexName(), requestOptions, context)); + } + + /** + * 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", "innerHits", "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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     @odata.count: Long (Optional)
+     *     @search.coverage: Double (Optional)
+     *     @search.facets (Optional): {
+     *         String (Required): [
+     *              (Required){
+     *                 count: Long (Optional)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (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 containing search results from an index along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response searchGetWithResponse(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return service.searchGetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + this.getIndexName(), requestOptions, Context.NONE); + } + + /** + * Searches for documents in the index. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight (Optional): [
+     *         String (Optional)
+     *     ]
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby (Optional): [
+     *         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/innerHits/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields (Optional): [
+     *         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 (Optional): [
+     *         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 (Optional): [
+     *         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: Float (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *             perDocumentVectorLimit: Integer (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (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)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param searchPostRequest The searchPostRequest parameter. + * @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> searchWithResponseAsync(BinaryData searchPostRequest, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.search(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, this.getIndexName(), contentType, searchPostRequest, requestOptions, context)); + } + + /** + * Searches for documents in the index. + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     count: Boolean (Optional)
+     *     facets (Optional): [
+     *         String (Optional)
+     *     ]
+     *     filter: String (Optional)
+     *     highlight (Optional): [
+     *         String (Optional)
+     *     ]
+     *     highlightPostTag: String (Optional)
+     *     highlightPreTag: String (Optional)
+     *     minimumCoverage: Double (Optional)
+     *     orderby (Optional): [
+     *         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/innerHits/all) (Optional)
+     *     search: String (Optional)
+     *     searchFields (Optional): [
+     *         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 (Optional): [
+     *         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 (Optional): [
+     *         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: Float (Optional)
+     *             threshold (Optional): {
+     *                 kind: String(vectorSimilarity/searchScore) (Required)
+     *             }
+     *             filterOverride: String (Optional)
+     *             perDocumentVectorLimit: Integer (Optional)
+     *         }
+     *     ]
+     *     vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (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)
+     *                 avg: Double (Optional)
+     *                 min: Double (Optional)
+     *                 max: Double (Optional)
+     *                 sum: Double (Optional)
+     *                 cardinality: Long (Optional)
+     *                 @search.facets (Optional): {
+     *                     String (Required): [
+     *                         (recursive schema, see above)
+     *                     ]
+     *                 }
+     *                  (Optional): {
+     *                     String: Object (Required)
+     *                 }
+     *             }
+     *         ]
+     *     }
+     *     @search.answers (Optional): [
+     *          (Optional){
+     *             score: Double (Optional)
+     *             key: String (Optional)
+     *             text: String (Optional)
+     *             highlights: String (Optional)
+     *              (Optional): {
+     *                 String: Object (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 (Optional): [
+     *             String (Optional)
+     *         ]
+     *         highlightPostTag: String (Optional)
+     *         highlightPreTag: String (Optional)
+     *         minimumCoverage: Double (Optional)
+     *         orderby (Optional): [
+     *             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/innerHits/all) (Optional)
+     *         search: String (Optional)
+     *         searchFields (Optional): [
+     *             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 (Optional): [
+     *             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 (Optional): [
+     *             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: Float (Optional)
+     *                 threshold (Optional): {
+     *                     kind: String(vectorSimilarity/searchScore) (Required)
+     *                 }
+     *                 filterOverride: String (Optional)
+     *                 perDocumentVectorLimit: Integer (Optional)
+     *             }
+     *         ]
+     *         vectorFilterMode: String(postFilter/preFilter/strictPostFilter) (Optional)
+     *         hybridSearch (Optional): {
+     *             maxTextRecallSize: Integer (Optional)
+     *             countAndFacetMode: String(countRetrievableResults/countAllResults) (Optional)
+     *         }
+     *     }
+     *     value (Required): [
+     *          (Required){
+     *             @search.score: double (Required)
+     *             @search.rerankerScore: Double (Optional)
+     *             @search.rerankerBoostedScore: Double (Optional)
+     *             @search.highlights (Optional): {
+     *                 String (Required): [
+     *                     String (Required)
+     *                 ]
+     *             }
+     *             @search.captions (Optional): [
+     *                  (Optional){
+     *                     text: String (Optional)
+     *                     highlights: String (Optional)
+     *                      (Optional): {
+     *                         String: Object (Required)
+     *                     }
+     *                 }
+     *             ]
+     *             @search.documentDebugInfo (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)
+     *                     }
+     *                 }
+     *                 innerHits (Optional): {
+     *                     String (Required): [
+     *                          (Required){
+     *                             ordinal: Long (Optional)
+     *                             vectors (Optional): [
+     *                                  (Optional){
+     *                                     String (Required): (recursive schema, see String above)
+     *                                 }
+     *                             ]
+     *                         }
+     *                     ]
+     *                 }
+     *             }
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @odata.nextLink: String (Optional)
+     *     @search.semanticPartialResponseReason: String(maxWaitExceeded/capacityOverloaded/transient) (Optional)
+     *     @search.semanticPartialResponseType: String(baseResults/rerankedResults) (Optional)
+     *     @search.semanticQueryRewritesResultType: String(originalQueryOnly) (Optional)
+     * }
+     * }
+     * 
+ * + * @param searchPostRequest The searchPostRequest parameter. + * @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 searchWithResponse(BinaryData searchPostRequest, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return service.searchSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + this.getIndexName(), contentType, searchPostRequest, 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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: Object (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param key The key of the document to retrieve. + * @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> getDocumentWithResponseAsync(String key, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return FluxUtil.withContext(context -> service.getDocument(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, key, this.getIndexName(), 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} + *

Header Parameters

+ * + * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
x-ms-enable-elevated-readBooleanNoA value that enables elevated read that + * bypass document level permission checks for the query operation.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *      (Optional): {
+     *         String: Object (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param key The key of the document to retrieve. + * @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 getDocumentWithResponse(String key, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return service.getDocumentSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, key, + this.getIndexName(), requestOptions, Context.NONE); + } + + /** + * 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: Object (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 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> suggestGetWithResponseAsync(String searchText, String suggesterName, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return FluxUtil + .withContext(context -> service.suggestGet(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, searchText, suggesterName, this.getIndexName(), requestOptions, context)); + } + + /** + * 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: Object (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 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 suggestGetWithResponse(String searchText, String suggesterName, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return service.suggestGetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, searchText, + suggesterName, this.getIndexName(), 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 (Optional): [
+     *         String (Optional)
+     *     ]
+     *     search: String (Required)
+     *     searchFields (Optional): [
+     *         String (Optional)
+     *     ]
+     *     select (Optional): [
+     *         String (Optional)
+     *     ]
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param suggestPostRequest The suggestPostRequest parameter. + * @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> suggestWithResponseAsync(BinaryData suggestPostRequest, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return FluxUtil + .withContext(context -> service.suggest(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + this.getIndexName(), contentType, suggestPostRequest, 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 (Optional): [
+     *         String (Optional)
+     *     ]
+     *     search: String (Required)
+     *     searchFields (Optional): [
+     *         String (Optional)
+     *     ]
+     *     select (Optional): [
+     *         String (Optional)
+     *     ]
+     *     suggesterName: String (Required)
+     *     top: Integer (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             @search.text: String (Required)
+     *              (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *         }
+     *     ]
+     *     @search.coverage: Double (Optional)
+     * }
+     * }
+     * 
+ * + * @param suggestPostRequest The suggestPostRequest parameter. + * @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 suggestWithResponse(BinaryData suggestPostRequest, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return service.suggestSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + this.getIndexName(), contentType, suggestPostRequest, 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: Object (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> indexWithResponseAsync(BinaryData batch, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.index(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, this.getIndexName(), contentType, 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: Object (Required)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             key: String (Required)
+     *             errorMessage: String (Optional)
+     *             status: boolean (Required)
+     *             statusCode: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response indexWithResponse(BinaryData batch, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return service.indexSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, this.getIndexName(), + contentType, batch, requestOptions, Context.NONE); + } + + /** + * 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 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> autocompleteGetWithResponseAsync(String searchText, String suggesterName, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return FluxUtil + .withContext(context -> service.autocompleteGet(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, searchText, suggesterName, this.getIndexName(), requestOptions, context)); + } + + /** + * 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 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 autocompleteGetWithResponse(String searchText, String suggesterName, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + return service.autocompleteGetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + searchText, suggesterName, this.getIndexName(), requestOptions, Context.NONE); + } + + /** + * 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 (Optional): [
+     *         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 autocompletePostRequest The autocompletePostRequest parameter. + * @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> autocompleteWithResponseAsync(BinaryData autocompletePostRequest, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return FluxUtil + .withContext(context -> service.autocomplete(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, this.getIndexName(), contentType, autocompletePostRequest, requestOptions, context)); + } + + /** + * 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 (Optional): [
+     *         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 autocompletePostRequest The autocompletePostRequest parameter. + * @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 autocompleteWithResponse(BinaryData autocompletePostRequest, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=none"; + final String contentType = "application/json"; + return service.autocompleteSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + this.getIndexName(), contentType, autocompletePostRequest, requestOptions, Context.NONE); + } +} 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 index 7b9f74684079..349f769c51cd 100644 --- 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 @@ -1,29 +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. +// 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.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 SearchIndexClient type. */ public final class SearchIndexClientImpl { /** - * The endpoint URL of the search service. + * The proxy service used to perform REST calls. + */ + private final SearchIndexClientService service; + + /** + * Service host. */ private final String endpoint; /** - * Gets The endpoint URL of the search service. + * Gets Service host. * * @return the endpoint value. */ @@ -32,31 +69,17 @@ public String getEndpoint() { } /** - * 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. + * Service version. */ - private final String apiVersion; + private final SearchServiceVersion serviceVersion; /** - * Gets Api Version. + * Gets Service version. * - * @return the apiVersion value. + * @return the serviceVersion value. */ - public String getApiVersion() { - return this.apiVersion; + public SearchServiceVersion getServiceVersion() { + return this.serviceVersion; } /** @@ -87,42 +110,26 @@ 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. + * @param endpoint Service host. + * @param serviceVersion Service version. */ - public SearchIndexClientImpl(String endpoint, String indexName, String apiVersion) { + public SearchIndexClientImpl(String endpoint, SearchServiceVersion serviceVersion) { this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), endpoint, indexName, apiVersion); + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); } /** * 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. + * @param endpoint Service host. + * @param serviceVersion Service version. */ - public SearchIndexClientImpl(HttpPipeline httpPipeline, String endpoint, String indexName, String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, indexName, apiVersion); + public SearchIndexClientImpl(HttpPipeline httpPipeline, String endpoint, SearchServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); } /** @@ -130,17 +137,6405 @@ public SearchIndexClientImpl(HttpPipeline httpPipeline, String endpoint, String * * @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. + * @param endpoint Service host. + * @param serviceVersion Service version. */ public SearchIndexClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, - String indexName, String apiVersion) { + SearchServiceVersion serviceVersion) { this.httpPipeline = httpPipeline; this.serializerAdapter = serializerAdapter; this.endpoint = endpoint; - this.indexName = indexName; - this.apiVersion = apiVersion; - this.documents = new DocumentsImpl(this); + this.serviceVersion = serviceVersion; + this.service = RestProxy.create(SearchIndexClientService.class, this.httpPipeline, this.getSerializerAdapter()); + } + + /** + * The interface defining all the services for SearchIndexClient to be used by the proxy service to perform REST + * calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchIndexClient") + public interface SearchIndexClientService { + @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> createOrUpdateSynonymMap(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("synonymMapName") String name, + @HeaderParam("Content-Type") String contentType, @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 createOrUpdateSynonymMapSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("synonymMapName") String name, + @HeaderParam("Content-Type") String contentType, @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> deleteSynonymMap(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("synonymMapName") String name, 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 deleteSynonymMapSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("synonymMapName") String name, 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> getSynonymMap(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("synonymMapName") String name, 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 getSynonymMapSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("synonymMapName") String name, 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> getSynonymMaps(@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 getSynonymMapsSync(@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> createSynonymMap(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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 createSynonymMapSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData synonymMap, + 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> createOrUpdateIndex(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("indexName") String name, + @HeaderParam("Content-Type") String contentType, @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 createOrUpdateIndexSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("indexName") String name, + @HeaderParam("Content-Type") String contentType, @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> deleteIndex(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, 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 deleteIndexSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, 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> getIndex(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, 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 getIndexSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, 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> listIndexes(@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 listIndexesSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + 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) + Mono> createIndex(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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 createIndexSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData index, + 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> getIndexStatistics(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, 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 getIndexStatisticsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, 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> analyzeText(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, @HeaderParam("Content-Type") String contentType, + @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 analyzeTextSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexName") String name, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData request, 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> createOrUpdateAlias(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("aliasName") String name, + @HeaderParam("Content-Type") String contentType, @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 createOrUpdateAliasSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("aliasName") String name, + @HeaderParam("Content-Type") String contentType, @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> deleteAlias(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("aliasName") String name, 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 deleteAliasSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("aliasName") String name, 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> getAlias(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("aliasName") String name, 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 getAliasSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("aliasName") String name, 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> listAliases(@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 listAliasesSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + 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) + Mono> createAlias(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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 createAliasSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData alias, + RequestOptions requestOptions, Context context); + + @Put("/knowledgebases('{knowledgeBaseName}')") + @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> createOrUpdateKnowledgeBase(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("knowledgeBaseName") String name, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeBase, + RequestOptions requestOptions, Context context); + + @Put("/knowledgebases('{knowledgeBaseName}')") + @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 createOrUpdateKnowledgeBaseSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("knowledgeBaseName") String name, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeBase, + RequestOptions requestOptions, Context context); + + @Delete("/knowledgebases('{knowledgeBaseName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteKnowledgeBase(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("knowledgeBaseName") String name, RequestOptions requestOptions, Context context); + + @Delete("/knowledgebases('{knowledgeBaseName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteKnowledgeBaseSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("knowledgeBaseName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgebases('{knowledgeBaseName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKnowledgeBase(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("knowledgeBaseName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgebases('{knowledgeBaseName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKnowledgeBaseSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("knowledgeBaseName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgebases") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listKnowledgeBases(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/knowledgebases") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listKnowledgeBasesSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/knowledgebases") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createKnowledgeBase(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeBase, + RequestOptions requestOptions, Context context); + + @Post("/knowledgebases") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createKnowledgeBaseSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeBase, + RequestOptions requestOptions, Context context); + + @Put("/knowledgesources('{sourceName}')") + @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> createOrUpdateKnowledgeSource(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("sourceName") String name, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeSource, + RequestOptions requestOptions, Context context); + + @Put("/knowledgesources('{sourceName}')") + @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 createOrUpdateKnowledgeSourceSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("sourceName") String name, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeSource, + RequestOptions requestOptions, Context context); + + @Delete("/knowledgesources('{sourceName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> deleteKnowledgeSource(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("sourceName") String name, RequestOptions requestOptions, Context context); + + @Delete("/knowledgesources('{sourceName}')") + @ExpectedResponses({ 204, 404 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response deleteKnowledgeSourceSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("sourceName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgesources('{sourceName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> getKnowledgeSource(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("sourceName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgesources('{sourceName}')") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response getKnowledgeSourceSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("sourceName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgesources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> listKnowledgeSources(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Get("/knowledgesources") + @ExpectedResponses({ 200 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response listKnowledgeSourcesSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + RequestOptions requestOptions, Context context); + + @Post("/knowledgesources") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> createKnowledgeSource(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeSource, + RequestOptions requestOptions, Context context); + + @Post("/knowledgesources") + @ExpectedResponses({ 201 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response createKnowledgeSourceSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData knowledgeSource, + RequestOptions requestOptions, Context context); + + @Get("/knowledgesources('{sourceName}')/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> getKnowledgeSourceStatus(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("sourceName") String name, RequestOptions requestOptions, Context context); + + @Get("/knowledgesources('{sourceName}')/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 getKnowledgeSourceStatusSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("sourceName") String name, 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) + 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> listIndexStatsSummary(@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 listIndexStatsSummarySync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + 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 (Required): [
+     *         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 (Required): [
+     *         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 name 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> createOrUpdateSynonymMapWithResponseAsync(String name, BinaryData synonymMap, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdateSynonymMap(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, prefer, name, contentType, 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 (Required): [
+     *         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 (Required): [
+     *         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 name 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 createOrUpdateSynonymMapWithResponse(String name, BinaryData synonymMap, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateSynonymMapSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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 name 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> deleteSynonymMapWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteSynonymMap(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 deleteSynonymMapWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteSynonymMapSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Retrieves a synonym map definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 name 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> getSynonymMapWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getSynonymMap(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Retrieves a synonym map definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 name 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 getSynonymMapWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getSynonymMapSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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 (Required): [
+     *                 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> getSynonymMapsWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getSynonymMaps(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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 (Required): [
+     *                 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 getSynonymMapsWithResponse(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getSynonymMapsSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + requestOptions, Context.NONE); + } + + /** + * Creates a new synonym map. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 (Required): [
+     *         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> createSynonymMapWithResponseAsync(BinaryData synonymMap, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createSynonymMap(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, synonymMap, requestOptions, context)); + } + + /** + * Creates a new synonym map. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 (Required): [
+     *         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 createSynonymMapWithResponse(BinaryData synonymMap, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createSynonymMapSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + contentType, synonymMap, requestOptions, Context.NONE); + } + + /** + * 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)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name 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> createOrUpdateIndexWithResponseAsync(String name, BinaryData index, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createOrUpdateIndex(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, prefer, name, contentType, 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)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name 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 createOrUpdateIndexWithResponse(String name, BinaryData index, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateIndexSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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 name 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> deleteIndexWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteIndex(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 deleteIndexWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteIndexSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Retrieves an index definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name 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> getIndexWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getIndex(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Retrieves an index definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name 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 getIndexWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getIndexSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (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> listIndexesSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil + .withContext(context -> service.listIndexes(this.getEndpoint(), this.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
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (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 listIndexesAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listIndexesSinglePageAsync(requestOptions)); + } + + /** + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (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 listIndexesSinglePage(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + Response res = service.listIndexesSync(this.getEndpoint(), this.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
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (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 listIndexes(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listIndexesSinglePage(requestOptions)); + } + + /** + * Creates a new search index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (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> createIndexWithResponseAsync(BinaryData index, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createIndex(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, index, requestOptions, context)); + } + + /** + * Creates a new search index. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (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 createIndexWithResponse(BinaryData index, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createIndexSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, contentType, + index, 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 name 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> getIndexStatisticsWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getIndexStatistics(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 getIndexStatisticsWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getIndexStatisticsSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + 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 name 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> analyzeTextWithResponseAsync(String name, BinaryData request, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.analyzeText(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, contentType, 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 name 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 analyzeTextWithResponse(String name, BinaryData request, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.analyzeTextSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + contentType, request, requestOptions, Context.NONE); + } + + /** + * 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 name 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> createOrUpdateAliasWithResponseAsync(String name, BinaryData alias, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createOrUpdateAlias(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, prefer, name, contentType, 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 name 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 createOrUpdateAliasWithResponse(String name, BinaryData alias, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateAliasSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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 name 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> deleteAliasWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteAlias(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 deleteAliasWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteAliasSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name 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> getAliasWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getAlias(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name 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 getAliasWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getAliasSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + 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> listAliasesSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil + .withContext(context -> service.listAliases(this.getEndpoint(), this.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 listAliasesAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listAliasesSinglePageAsync(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 listAliasesSinglePage(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + Response res = service.listAliasesSync(this.getEndpoint(), this.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 listAliases(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listAliasesSinglePage(requestOptions)); + } + + /** + * 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> createAliasWithResponseAsync(BinaryData alias, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createAlias(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, 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 createAliasWithResponse(BinaryData alias, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createAliasSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, contentType, + alias, requestOptions, Context.NONE); + } + + /** + * Creates a new knowledge base or updates a knowledge base 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)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateKnowledgeBaseWithResponseAsync(String name, + BinaryData knowledgeBase, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdateKnowledgeBase(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, prefer, name, contentType, knowledgeBase, requestOptions, context)); + } + + /** + * Creates a new knowledge base or updates a knowledge base 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)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateKnowledgeBaseWithResponse(String name, BinaryData knowledgeBase, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateKnowledgeBaseSync(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, prefer, name, contentType, knowledgeBase, requestOptions, Context.NONE); + } + + /** + * Deletes a knowledge base. + *

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 name The name of the knowledge base. + * @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> deleteKnowledgeBaseWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteKnowledgeBase(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Deletes a knowledge base. + *

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 name The name of the knowledge base. + * @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 deleteKnowledgeBaseWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteKnowledgeBaseSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Retrieves a knowledge base definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge base. + * @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 knowledge base definition along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getKnowledgeBaseWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getKnowledgeBase(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Retrieves a knowledge base definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge base. + * @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 knowledge base definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getKnowledgeBaseWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getKnowledgeBaseSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Lists all knowledge bases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: 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 result from listing knowledge bases along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listKnowledgeBasesSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil + .withContext(context -> service.listKnowledgeBases(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null)); + } + + /** + * Lists all knowledge bases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: 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 result from listing knowledge bases as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listKnowledgeBasesAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listKnowledgeBasesSinglePageAsync(requestOptions)); + } + + /** + * Lists all knowledge bases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: 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 result from listing knowledge bases along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listKnowledgeBasesSinglePage(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + Response res = service.listKnowledgeBasesSync(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null); + } + + /** + * Lists all knowledge bases available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: 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 result from listing knowledge bases as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listKnowledgeBases(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listKnowledgeBasesSinglePage(requestOptions)); + } + + /** + * Creates a new knowledge base. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createKnowledgeBaseWithResponseAsync(BinaryData knowledgeBase, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createKnowledgeBase(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, knowledgeBase, requestOptions, context)); + } + + /** + * Creates a new knowledge base. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
+ * + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createKnowledgeBaseWithResponse(BinaryData knowledgeBase, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createKnowledgeBaseSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + contentType, knowledgeBase, requestOptions, Context.NONE); + } + + /** + * Creates a new knowledge source or updates an knowledge source 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
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge source. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateKnowledgeSourceWithResponseAsync(String name, + BinaryData knowledgeSource, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdateKnowledgeSource(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, prefer, name, contentType, knowledgeSource, requestOptions, context)); + } + + /** + * Creates a new knowledge source or updates an knowledge source 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
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge source. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateKnowledgeSourceWithResponse(String name, BinaryData knowledgeSource, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateKnowledgeSourceSync(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, prefer, name, contentType, knowledgeSource, requestOptions, Context.NONE); + } + + /** + * Deletes an existing knowledge source. + *

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 name The name of the knowledge source. + * @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> deleteKnowledgeSourceWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteKnowledgeSource(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Deletes an existing knowledge source. + *

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 name The name of the knowledge source. + * @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 deleteKnowledgeSourceWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteKnowledgeSourceSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + name, requestOptions, Context.NONE); + } + + /** + * Retrieves a knowledge source definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge source. + * @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 knowledge source definition along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getKnowledgeSourceWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getKnowledgeSource(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Retrieves a knowledge source definition. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge source. + * @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 knowledge source definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getKnowledgeSourceWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getKnowledgeSourceSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Lists all knowledge sources available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @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 result from listing knowledge sources along with {@link PagedResponse} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private Mono> listKnowledgeSourcesSinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil + .withContext(context -> service.listKnowledgeSources(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)) + .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null)); + } + + /** + * Lists all knowledge sources available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @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 result from listing knowledge sources as paginated response with {@link PagedFlux}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listKnowledgeSourcesAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listKnowledgeSourcesSinglePageAsync(requestOptions)); + } + + /** + * Lists all knowledge sources available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @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 result from listing knowledge sources along with {@link PagedResponse}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + private PagedResponse listKnowledgeSourcesSinglePage(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + Response res = service.listKnowledgeSourcesSync(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, Context.NONE); + return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), + getValues(res.getValue(), "value"), null, null); + } + + /** + * Lists all knowledge sources available for a search service. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @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 result from listing knowledge sources as paginated response with {@link PagedIterable}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listKnowledgeSources(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listKnowledgeSourcesSinglePage(requestOptions)); + } + + /** + * Creates a new knowledge source. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createKnowledgeSourceWithResponseAsync(BinaryData knowledgeSource, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createKnowledgeSource(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, knowledgeSource, requestOptions, context)); + } + + /** + * Creates a new knowledge source. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createKnowledgeSourceWithResponse(BinaryData knowledgeSource, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createKnowledgeSourceSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + contentType, knowledgeSource, requestOptions, Context.NONE); + } + + /** + * Retrieves the status of a knowledge source. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     synchronizationStatus: String(creating/active/deleting) (Required)
+     *     synchronizationInterval: String (Optional)
+     *     currentSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     lastSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         endTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     statistics (Optional): {
+     *         totalSynchronization: int (Required)
+     *         averageSynchronizationDuration: String (Required)
+     *         averageItemsProcessedPerSynchronization: int (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge source. + * @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 status and synchronization history of a knowledge source along with {@link Response} on + * successful completion of {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getKnowledgeSourceStatusWithResponseAsync(String name, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getKnowledgeSourceStatus(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Retrieves the status of a knowledge source. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     synchronizationStatus: String(creating/active/deleting) (Required)
+     *     synchronizationInterval: String (Optional)
+     *     currentSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     lastSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         endTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     statistics (Optional): {
+     *         totalSynchronization: int (Required)
+     *         averageSynchronizationDuration: String (Required)
+     *         averageItemsProcessedPerSynchronization: int (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name The name of the knowledge source. + * @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 status and synchronization history of a knowledge source along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getKnowledgeSourceStatusWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getKnowledgeSourceStatusSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + name, requestOptions, Context.NONE); + } + + /** + * 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)
+     *         maxCumulativeIndexerRuntimeSeconds: Long (Optional)
+     *     }
+     *     indexersRuntime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @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;odata.metadata=minimal"; + 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)
+     *         maxCumulativeIndexerRuntimeSeconds: Long (Optional)
+     *     }
+     *     indexersRuntime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @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;odata.metadata=minimal"; + 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 (Required)
+     * }
+     * }
+     * 
+ * + * @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> listIndexStatsSummarySinglePageAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil + .withContext(context -> service.listIndexStatsSummary(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 (Required)
+     * }
+     * }
+     * 
+ * + * @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 listIndexStatsSummaryAsync(RequestOptions requestOptions) { + return new PagedFlux<>(() -> listIndexStatsSummarySinglePageAsync(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 (Required)
+     * }
+     * }
+     * 
+ * + * @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 listIndexStatsSummarySinglePage(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + Response res = service.listIndexStatsSummarySync(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 (Required)
+     * }
+     * }
+     * 
+ * + * @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 listIndexStatsSummary(RequestOptions requestOptions) { + return new PagedIterable<>(() -> listIndexStatsSummarySinglePage(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/SearchIndexerClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchIndexerClientImpl.java new file mode 100644 index 000000000000..e44d3536bc26 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchIndexerClientImpl.java @@ -0,0 +1,4803 @@ +// 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.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.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 reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the SearchIndexerClient type. + */ +public final class SearchIndexerClientImpl { + /** + * The proxy service used to perform REST calls. + */ + private final SearchIndexerClientService 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; + } + + /** + * Initializes an instance of SearchIndexerClient client. + * + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public SearchIndexerClientImpl(String endpoint, SearchServiceVersion serviceVersion) { + this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), + JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of SearchIndexerClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + * @param endpoint Service host. + * @param serviceVersion Service version. + */ + public SearchIndexerClientImpl(HttpPipeline httpPipeline, String endpoint, SearchServiceVersion serviceVersion) { + this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion); + } + + /** + * Initializes an instance of SearchIndexerClient 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 SearchIndexerClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, String endpoint, + SearchServiceVersion serviceVersion) { + this.httpPipeline = httpPipeline; + this.serializerAdapter = serializerAdapter; + this.endpoint = endpoint; + this.serviceVersion = serviceVersion; + this.service + = RestProxy.create(SearchIndexerClientService.class, this.httpPipeline, this.getSerializerAdapter()); + } + + /** + * The interface defining all the services for SearchIndexerClient to be used by the proxy service to perform REST + * calls. + */ + @Host("{endpoint}") + @ServiceInterface(name = "SearchIndexerClient") + public interface SearchIndexerClientService { + @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> createOrUpdateDataSourceConnection(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("dataSourceName") String name, + @HeaderParam("Content-Type") String contentType, @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 createOrUpdateDataSourceConnectionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("dataSourceName") String name, + @HeaderParam("Content-Type") String contentType, @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> deleteDataSourceConnection(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("dataSourceName") String name, 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 deleteDataSourceConnectionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("dataSourceName") String name, 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> getDataSourceConnection(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("dataSourceName") String name, 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 getDataSourceConnectionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("dataSourceName") String name, 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> getDataSourceConnections(@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 getDataSourceConnectionsSync(@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> createDataSourceConnection(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData dataSourceConnection, 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 createDataSourceConnectionSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData dataSourceConnection, 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) + Mono> resetIndexer(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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 resetIndexerSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.resync") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> resync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData indexerResync, RequestOptions requestOptions, Context context); + + @Post("/indexers('{indexerName}')/search.resync") + @ExpectedResponses({ 204 }) + @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) + @UnexpectedResponseExceptionType(value = ResourceNotFoundException.class, code = { 404 }) + @UnexpectedResponseExceptionType(value = ResourceModifiedException.class, code = { 409 }) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Response resyncSync(@HostParam("endpoint") String endpoint, @QueryParam("api-version") String apiVersion, + @HeaderParam("Accept") String accept, @PathParam("indexerName") String name, + @HeaderParam("Content-Type") String contentType, @BodyParam("application/json") BinaryData indexerResync, + 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> resetDocuments(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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 resetDocumentsSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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> runIndexer(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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 runIndexerSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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> createOrUpdateIndexer(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("indexerName") String name, + @HeaderParam("Content-Type") String contentType, @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 createOrUpdateIndexerSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("indexerName") String name, + @HeaderParam("Content-Type") String contentType, @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> deleteIndexer(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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 deleteIndexerSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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> getIndexer(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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 getIndexerSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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> getIndexers(@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 getIndexersSync(@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> createIndexer(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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 createIndexerSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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> getIndexerStatus(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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 getIndexerStatusSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("indexerName") String name, 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) + Mono> createOrUpdateSkillset(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("skillsetName") String name, + @HeaderParam("Content-Type") String contentType, @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 createOrUpdateSkillsetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Prefer") String prefer, @PathParam("skillsetName") String name, + @HeaderParam("Content-Type") String contentType, @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> deleteSkillset(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("skillsetName") String name, 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 deleteSkillsetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("skillsetName") String name, 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> getSkillset(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("skillsetName") String name, 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 getSkillsetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @PathParam("skillsetName") String name, 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> getSkillsets(@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 getSkillsetsSync(@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> createSkillset(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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 createSkillsetSync(@HostParam("endpoint") String endpoint, + @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, + @HeaderParam("Content-Type") String contentType, @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, @HeaderParam("Accept") String accept, + @PathParam("skillsetName") String name, @HeaderParam("Content-Type") String contentType, + @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, @HeaderParam("Accept") String accept, + @PathParam("skillsetName") String name, @HeaderParam("Content-Type") String contentType, + @BodyParam("application/json") BinaryData skillNames, 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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 name 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> createOrUpdateDataSourceConnectionWithResponseAsync(String name, + BinaryData dataSource, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createOrUpdateDataSourceConnection(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, prefer, name, contentType, 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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 name 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 createOrUpdateDataSourceConnectionWithResponse(String name, BinaryData dataSource, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateDataSourceConnectionSync(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, prefer, name, contentType, 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 name 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> deleteDataSourceConnectionWithResponseAsync(String name, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteDataSourceConnection(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 deleteDataSourceConnectionWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteDataSourceConnectionSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + name, 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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 name 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> getDataSourceConnectionWithResponseAsync(String name, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getDataSourceConnection(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 name 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 getDataSourceConnectionWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getDataSourceConnectionSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + name, requestOptions, Context.NONE); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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/sharepoint) (Required)
+     *             subType: String (Optional)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             indexerPermissionOptions (Optional): [
+     *                 String(userIds/groupIds/rbacScope) (Optional)
+     *             ]
+     *             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> getDataSourceConnectionsWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getDataSourceConnections(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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/sharepoint) (Required)
+     *             subType: String (Optional)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             indexerPermissionOptions (Optional): [
+     *                 String(userIds/groupIds/rbacScope) (Optional)
+     *             ]
+     *             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 getDataSourceConnectionsWithResponse(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getDataSourceConnectionsSync(this.getEndpoint(), this.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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 dataSourceConnection 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> createDataSourceConnectionWithResponseAsync(BinaryData dataSourceConnection, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createDataSourceConnection(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, dataSourceConnection, 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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 dataSourceConnection 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 createDataSourceConnectionWithResponse(BinaryData dataSourceConnection, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createDataSourceConnectionSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + contentType, dataSourceConnection, requestOptions, Context.NONE); + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param name 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> resetIndexerWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.resetIndexer(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Resets the change tracking state associated with an indexer. + * + * @param name 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 resetIndexerWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.resetIndexerSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer.". + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     options (Optional): [
+     *         String(permissions) (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param name The name of the indexer. + * @param indexerResync The definition of the indexer resync options. + * @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> resyncWithResponseAsync(String name, BinaryData indexerResync, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.resync(this.getEndpoint(), this.getServiceVersion().getVersion(), + accept, name, contentType, indexerResync, requestOptions, context)); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer.". + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     options (Optional): [
+     *         String(permissions) (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param name The name of the indexer. + * @param indexerResync The definition of the indexer resync options. + * @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 resyncWithResponse(String name, BinaryData indexerResync, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.resyncSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, contentType, + indexerResync, 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 name 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> resetDocumentsWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + 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.resetDocuments(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 resetDocumentsWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + 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.resetDocumentsSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptionsLocal, Context.NONE); + } + + /** + * Runs an indexer on-demand. + * + * @param name 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> runIndexerWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.runIndexer(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Runs an indexer on-demand. + * + * @param name 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 runIndexerWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.runIndexerSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + 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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name 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> createOrUpdateIndexerWithResponseAsync(String name, BinaryData indexer, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdateIndexer(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name 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 createOrUpdateIndexerWithResponse(String name, BinaryData indexer, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateIndexerSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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 name 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> deleteIndexerWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteIndexer(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 deleteIndexerWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteIndexerSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + 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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name 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> getIndexerWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getIndexer(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name 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 getIndexerWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getIndexerSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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: Object (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: Object (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): {
+     *                 id: String (Optional)
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (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 Indexers request along with {@link Response} on successful completion of + * {@link Mono}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getIndexersWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getIndexers(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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: Object (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: Object (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): {
+     *                 id: String (Optional)
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (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 Indexers request along with {@link Response}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getIndexersWithResponse(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getIndexersSync(this.getEndpoint(), this.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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @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> createIndexerWithResponseAsync(BinaryData indexer, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createIndexer(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, 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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + *

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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
+ * + * @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 createIndexerWithResponse(BinaryData indexer, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createIndexerSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, contentType, + indexer, requestOptions, Context.NONE); + } + + /** + * Returns the current status and execution history of an indexer. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     status: String(unknown/error/running) (Required)
+     *     runtime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs/resync) (Optional)
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (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)
+     *     }
+     *     currentState (Optional): {
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (Optional)
+     *         allDocsInitialTrackingState: String (Optional)
+     *         allDocsFinalTrackingState: String (Optional)
+     *         resetDocsInitialTrackingState: String (Optional)
+     *         resetDocsFinalTrackingState: String (Optional)
+     *         resyncInitialTrackingState: String (Optional)
+     *         resyncFinalTrackingState: String (Optional)
+     *         resetDocumentKeys (Optional): [
+     *             String (Optional)
+     *         ]
+     *         resetDatasourceDocumentIds (Optional): [
+     *             String (Optional)
+     *         ]
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name 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> getIndexerStatusWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getIndexerStatus(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, requestOptions, context)); + } + + /** + * Returns the current status and execution history of an indexer. + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     status: String(unknown/error/running) (Required)
+     *     runtime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs/resync) (Optional)
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (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)
+     *     }
+     *     currentState (Optional): {
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (Optional)
+     *         allDocsInitialTrackingState: String (Optional)
+     *         allDocsFinalTrackingState: String (Optional)
+     *         resetDocsInitialTrackingState: String (Optional)
+     *         resetDocsFinalTrackingState: String (Optional)
+     *         resyncInitialTrackingState: String (Optional)
+     *         resyncFinalTrackingState: String (Optional)
+     *         resetDocumentKeys (Optional): [
+     *             String (Optional)
+     *         ]
+     *         resetDatasourceDocumentIds (Optional): [
+     *             String (Optional)
+     *         ]
+     *     }
+     * }
+     * }
+     * 
+ * + * @param name 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 getIndexerStatusWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getIndexerStatusSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * 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 (Required)
+     *                         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: Object (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: Object (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 (Required)
+     *                         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: Object (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: Object (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 name 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> createOrUpdateSkillsetWithResponseAsync(String name, BinaryData skillset, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return FluxUtil.withContext( + context -> service.createOrUpdateSkillset(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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 (Required)
+     *                         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: Object (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: Object (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 (Required)
+     *                         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: Object (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: Object (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 name 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 createOrUpdateSkillsetWithResponse(String name, BinaryData skillset, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String prefer = "return=representation"; + final String contentType = "application/json"; + return service.createOrUpdateSkillsetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + prefer, name, contentType, 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 name 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> deleteSkillsetWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.deleteSkillset(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 name 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 deleteSkillsetWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.deleteSkillsetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + 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 (Required)
+     *                         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: Object (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: Object (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 name 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> getSkillsetWithResponseAsync(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getSkillset(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, 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 (Required)
+     *                         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: Object (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: Object (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 name 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 getSkillsetWithResponse(String name, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getSkillsetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + requestOptions, Context.NONE); + } + + /** + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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 (Required)
+     *                                 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: Object (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: Object (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> getSkillsetsWithResponseAsync(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return FluxUtil.withContext(context -> service.getSkillsets(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, requestOptions, context)); + } + + /** + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * 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 (Required)
+     *                                 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: Object (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: Object (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 getSkillsetsWithResponse(RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + return service.getSkillsetsSync(this.getEndpoint(), this.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 (Required)
+     *                         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: Object (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: Object (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 (Required)
+     *                         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: Object (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: Object (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> createSkillsetWithResponseAsync(BinaryData skillset, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.createSkillset(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, contentType, 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 (Required)
+     *                         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: Object (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: Object (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 (Required)
+     *                         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: Object (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: Object (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 createSkillsetWithResponse(BinaryData skillset, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.createSkillsetSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, + contentType, skillset, requestOptions, Context.NONE); + } + + /** + * Reset an existing skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param name 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 name, BinaryData skillNames, + RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return FluxUtil.withContext(context -> service.resetSkills(this.getEndpoint(), + this.getServiceVersion().getVersion(), accept, name, contentType, skillNames, requestOptions, context)); + } + + /** + * Reset an existing skillset in a search service. + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param name 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 name, BinaryData skillNames, RequestOptions requestOptions) { + final String accept = "application/json;odata.metadata=minimal"; + final String contentType = "application/json"; + return service.resetSkillsSync(this.getEndpoint(), this.getServiceVersion().getVersion(), accept, name, + contentType, skillNames, requestOptions, Context.NONE); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchUtils.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchUtils.java new file mode 100644 index 000000000000..10e6baa86455 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/SearchUtils.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.implementation; + +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.rest.RequestOptions; +import com.azure.core.util.CoreUtils; +import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SearchRequest; + +/** + * Implementation utilities helper class. + */ +public final class SearchUtils { + private static final HttpHeaderName X_MS_QUERY_SOURCE_AUTHORIZATION + = HttpHeaderName.fromString("x-ms-query-source-authorization"); + private static final HttpHeaderName X_MS_ENABLE_ELEVATED_READ + = HttpHeaderName.fromString("x-ms-enable-elevated-read"); + + /** + * Converts the public API {@link SearchOptions} into {@link SearchRequest}. + * + * @param options The {@link SearchOptions}. + * @return An instance of {@link SearchRequest}. + */ + public static SearchRequest fromSearchOptions(SearchOptions options) { + if (options == null) { + return null; + } + + return new SearchRequest().setIncludeTotalCount(options.isIncludeTotalCount()) + .setFacets(options.getFacets()) + .setFilter(options.getFilter()) + .setHighlightFields(options.getHighlightFields()) + .setHighlightPostTag(options.getHighlightPostTag()) + .setHighlightPreTag(options.getHighlightPreTag()) + .setMinimumCoverage(options.getMinimumCoverage()) + .setOrderBy(options.getOrderBy()) + .setQueryType(options.getQueryType()) + .setScoringStatistics(options.getScoringStatistics()) + .setSessionId(options.getSessionId()) + .setScoringParameters(options.getScoringParameters()) + .setScoringProfile(options.getScoringProfile()) + .setDebug(options.getDebug()) + .setSearchText(options.getSearchText()) + .setSearchFields(options.getSearchFields()) + .setSearchMode(options.getSearchMode()) + .setQueryLanguage(options.getQueryLanguage()) + .setQuerySpeller(options.getQuerySpeller()) + .setSelect(options.getSelect()) + .setSkip(options.getSkip()) + .setTop(options.getTop()) + .setSemanticConfigurationName(options.getSemanticConfigurationName()) + .setSemanticErrorHandling(options.getSemanticErrorHandling()) + .setSemanticMaxWaitInMilliseconds(options.getSemanticMaxWaitInMilliseconds()) + .setSemanticQuery(options.getSemanticQuery()) + .setAnswers(options.getAnswers()) + .setCaptions(options.getCaptions()) + .setQueryRewrites(options.getQueryRewrites()) + .setSemanticFields(options.getSemanticFields()) + .setVectorQueries(options.getVectorQueries()) + .setVectorFilterMode(options.getVectorFilterMode()) + .setHybridSearch(options.getHybridSearch()); + } + + public static RequestOptions addSearchHeaders(RequestOptions requestOptions, SearchOptions searchOptions) { + // If SearchOptions is null or is both query source authorization and enable elevated read aren't set + // return requestOptions as-is. + if (searchOptions == null + || (CoreUtils.isNullOrEmpty(searchOptions.getQuerySourceAuthorization()) + && searchOptions.isEnableElevatedRead() == null)) { + return requestOptions; + } + + if (requestOptions == null) { + requestOptions = new RequestOptions(); + } + + if (!CoreUtils.isNullOrEmpty(searchOptions.getQuerySourceAuthorization())) { + requestOptions.setHeader(X_MS_QUERY_SOURCE_AUTHORIZATION, searchOptions.getQuerySourceAuthorization()); + } + + if (searchOptions.isEnableElevatedRead() != null) { + requestOptions.setHeader(X_MS_ENABLE_ELEVATED_READ, Boolean.toString(searchOptions.isEnableElevatedRead())); + } + + return requestOptions; + } + + private SearchUtils() { + } +} 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 index 585bb2c9e2a5..30d2f73e61b4 100644 --- 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 @@ -14,6 +14,7 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Consumer; @@ -22,11 +23,9 @@ /** * 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<>(); +final class IndexingDocumentManager { + private final LinkedList actions = new LinkedList<>(); private final ReentrantLock lock = new ReentrantLock(); IndexingDocumentManager() { @@ -37,18 +36,18 @@ final class IndexingDocumentManager { * 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<>(); + private final Deque inFlightActions = new LinkedList<>(); - Collection> getActions() { + Collection getActions() { lock.lock(); try { - List> actions = new ArrayList<>(inFlightActions.size() + this.actions.size()); + List actions = new ArrayList<>(inFlightActions.size() + this.actions.size()); - for (TryTrackingIndexAction inFlightAction : inFlightActions) { + for (TryTrackingIndexAction inFlightAction : inFlightActions) { actions.add(inFlightAction.getAction()); } - for (TryTrackingIndexAction action : this.actions) { + for (TryTrackingIndexAction action : this.actions) { actions.add(action.getAction()); } @@ -70,18 +69,18 @@ Collection> getActions() { * @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) { + Tuple2 addAndCheckForBatch(Collection actions, + Function, String> documentKeyRetriever, + Consumer onActionAddedConsumer, int batchSize) { lock.lock(); try { - for (IndexAction action : actions) { - this.actions - .addLast(new TryTrackingIndexAction<>(action, documentKeyRetriever.apply(action.getDocument()))); + for (IndexAction action : actions) { + this.actions.addLast( + new TryTrackingIndexAction(action, documentKeyRetriever.apply(action.getAdditionalProperties()))); if (onActionAddedConsumer != null) { - onActionAddedConsumer.accept(new OnActionAddedOptions<>(action)); + onActionAddedConsumer.accept(new OnActionAddedOptions(action)); } } @@ -105,7 +104,7 @@ Tuple2 addAndCheckForBatch(Collection> actions, * actions available. * @return A list of documents to be sent to the service for indexing. */ - List> tryCreateBatch(int batchSize, boolean ignoreBatchSize) { + List tryCreateBatch(int batchSize, boolean ignoreBatchSize) { lock.lock(); try { @@ -116,7 +115,7 @@ List> tryCreateBatch(int batchSize, boolean ignoreBatc } int size = Math.min(batchSize, actionSize + inFlightActionSize); - final List> batchActions = new ArrayList<>(size); + 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. @@ -127,7 +126,7 @@ List> tryCreateBatch(int batchSize, boolean ignoreBatc // 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; + TryTrackingIndexAction inflightAction; while ((inflightAction = inFlightActions.pollLast()) != null) { actions.push(inflightAction); } @@ -142,13 +141,13 @@ List> tryCreateBatch(int batchSize, boolean ignoreBatc } } - private int fillFromQueue(List> batch, Collection> queue, + private int fillFromQueue(List batch, Collection queue, int requested, Set duplicateKeyTracker) { int actionsAdded = 0; - Iterator> iterator = queue.iterator(); + Iterator iterator = queue.iterator(); while (actionsAdded < requested && iterator.hasNext()) { - TryTrackingIndexAction potentialDocumentToAdd = iterator.next(); + TryTrackingIndexAction potentialDocumentToAdd = iterator.next(); if (duplicateKeyTracker.contains(potentialDocumentToAdd.getKey())) { continue; @@ -163,7 +162,7 @@ private int fillFromQueue(List> batch, Collection> actionsInFlight) { + void reinsertCancelledActions(List actionsInFlight) { lock.lock(); try { inFlightActions.addAll(actionsInFlight); @@ -172,7 +171,7 @@ void reinsertCancelledActions(List> actionsInFlight) { } } - void reinsertFailedActions(List> actionsToRetry) { + void reinsertFailedActions(List actionsToRetry) { lock.lock(); try { 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 index 772de7455f8d..9c370eaa212a 100644 --- 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 @@ -4,16 +4,14 @@ package com.azure.search.documents.implementation.batching; import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.rest.RequestOptions; 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.SearchAsyncClient; import com.azure.search.documents.models.IndexAction; import com.azure.search.documents.models.IndexBatchException; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.IndexDocumentsResult; import com.azure.search.documents.models.IndexingResult; import com.azure.search.documents.options.OnActionAddedOptions; @@ -29,6 +27,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicInteger; @@ -45,14 +44,11 @@ /** * 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 { +public final class SearchIndexingAsyncPublisher { private static final ClientLogger LOGGER = new ClientLogger(SearchIndexingAsyncPublisher.class); - private final SearchIndexClientImpl restClient; - private final JsonSerializer serializer; + private final SearchAsyncClient searchAsyncClient; private final boolean autoFlush; private int batchSize; @@ -60,31 +56,30 @@ public final class SearchIndexingAsyncPublisher { 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 Consumer onActionAdded; + private final Consumer onActionSent; + private final Consumer onActionSucceeded; + private final Consumer onActionError; - private final Function documentKeyRetriever; + private final Function, String> documentKeyRetriever; private final Function scaleDownFunction = size -> size / 2; - private final IndexingDocumentManager documentManager; + 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, + public SearchIndexingAsyncPublisher(SearchAsyncClient searchAsyncClient, + Function, String> documentKeyRetriever, boolean autoFlush, int initialBatchActionCount, int maxRetriesPerAction, Duration throttlingDelay, Duration maxThrottlingDelay, - Consumer> onActionAdded, Consumer> onActionSucceeded, - Consumer> onActionError, Consumer> onActionSent) { + 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.searchAsyncClient = searchAsyncClient; + this.documentManager = new IndexingDocumentManager(); this.autoFlush = autoFlush; this.batchSize = initialBatchActionCount; @@ -100,7 +95,7 @@ public SearchIndexingAsyncPublisher(SearchIndexClientImpl restClient, JsonSerial this.onActionError = onActionError; } - public Collection> getActions() { + public Collection getActions() { return documentManager.getActions(); } @@ -112,7 +107,8 @@ public Duration getCurrentRetryDelay() { return currentRetryDelay; } - public Mono addActions(Collection> actions, Context context, Runnable rescheduleFlush) { + public Mono addActions(Collection actions, RequestOptions requestOptions, + Runnable rescheduleFlush) { Tuple2 batchSizeAndAvailable = documentManager.addAndCheckForBatch(actions, documentKeyRetriever, onActionAdded, batchSize); @@ -121,13 +117,13 @@ public Mono addActions(Collection> actions, Context context if (autoFlush && batchSizeAndAvailable.getT2()) { rescheduleFlush.run(); LOGGER.verbose("Adding documents triggered batch size limit, sending documents for indexing."); - return flush(false, false, context); + return flush(false, false, requestOptions); } return Mono.empty(); } - public Mono flush(boolean awaitLock, boolean isClose, Context context) { + public Mono flush(boolean awaitLock, boolean isClose, RequestOptions requestOptions) { if (awaitLock) { try { processingSemaphore.acquire(); @@ -135,34 +131,35 @@ public Mono flush(boolean awaitLock, boolean isClose, Context context) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } - return Mono.using(() -> processingSemaphore, ignored -> flushLoop(isClose, context), Semaphore::release); + return Mono.using(() -> processingSemaphore, ignored -> flushLoop(isClose, requestOptions), + Semaphore::release, true); } else if (processingSemaphore.tryAcquire()) { - return Mono.using(() -> processingSemaphore, ignored -> flushLoop(isClose, context), Semaphore::release); + return Mono.using(() -> processingSemaphore, ignored -> flushLoop(isClose, requestOptions), + Semaphore::release, true); } 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))) + private Mono flushLoop(boolean isClosed, RequestOptions requestOptions) { + return createAndProcessBatch(requestOptions, true) + .expand(ignored -> Flux.defer(() -> createAndProcessBatch(requestOptions, isClosed))) .then(); } - private Mono createAndProcessBatch(Context context, boolean ignoreBatchSize) { - List> batchActions = documentManager.tryCreateBatch(batchSize, ignoreBatchSize); + private Mono createAndProcessBatch(RequestOptions requestOptions, 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()); + List convertedActions + = batchActions.stream().map(TryTrackingIndexAction::getAction).collect(Collectors.toList()); - return sendBatch(convertedActions, batchActions, context).map(response -> { + return sendBatch(convertedActions, batchActions, requestOptions).map(response -> { handleResponse(batchActions, response); return response; @@ -173,17 +170,16 @@ private Mono createAndProcessBatch(Context context, boolean * 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) { + private Mono sendBatch(List actions, List batchActions, + RequestOptions requestOptions) { LOGGER.verbose("Sending a batch of size {}.", batchActions.size()); if (onActionSent != null) { - batchActions.forEach(action -> onActionSent.accept(new OnActionSentOptions<>(action.getAction()))); + batchActions.forEach(action -> onActionSent.accept(new OnActionSentOptions(action.getAction()))); } Mono> batchCall - = Utility.indexDocumentsWithResponseAsync(restClient, actions, true, context, LOGGER); + = searchAsyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch(actions), null, requestOptions); if (!currentRetryDelay.isZero() && !currentRetryDelay.isNegative()) { batchCall = batchCall.delaySubscription(currentRetryDelay); @@ -225,12 +221,12 @@ private Mono sendBatch( } int splitOffset = Math.min(actions.size(), batchSize); - List> batchActionsToRemove + List batchActionsToRemove = batchActions.subList(splitOffset, batchActions.size()); documentManager.reinsertFailedActions(batchActionsToRemove); batchActionsToRemove.clear(); - return sendBatch(actions.subList(0, splitOffset), batchActions, context); + return sendBatch(actions.subList(0, splitOffset), batchActions, requestOptions); } return Mono.just(new IndexBatchResponse(statusCode, null, actions.size(), true)); @@ -240,20 +236,19 @@ private Mono sendBatch( ignored -> Mono.just(new IndexBatchResponse(0, null, actions.size(), true))); } - private void handleResponse(List> actions, IndexBatchResponse batchResponse) { + 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(); + IndexAction action = actions.get(0).getAction(); if (onActionError != null) { - onActionError - .accept(new OnActionErrorOptions<>(action).setThrowable(createDocumentTooLargeException())); + onActionError.accept(new OnActionErrorOptions(action).setThrowable(createDocumentTooLargeException())); } return; } - List> actionsToRetry = new ArrayList<>(); + List actionsToRetry = new ArrayList<>(); boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (batchResponse.getResults() == null) { /* @@ -267,7 +262,7 @@ private void handleResponse(List> actions, IndexBatchR */ for (IndexingResult result : batchResponse.getResults()) { String key = result.getKey(); - TryTrackingIndexAction action + TryTrackingIndexAction action = actions.stream().filter(a -> key.equals(a.getKey())).findFirst().orElse(null); if (action == null) { @@ -277,7 +272,7 @@ private void handleResponse(List> actions, IndexBatchR if (isSuccess(result.getStatusCode())) { if (onActionSucceeded != null) { - onActionSucceeded.accept(new OnActionSucceededOptions<>(action.getAction())); + onActionSucceeded.accept(new OnActionSucceededOptions(action.getAction())); } } else if (isRetryable(result.getStatusCode())) { has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; @@ -286,14 +281,14 @@ private void handleResponse(List> actions, IndexBatchR actionsToRetry.add(action); } else { if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()) + onActionError.accept(new OnActionErrorOptions(action.getAction()) .setThrowable(createDocumentHitRetryLimitException()) .setIndexingResult(result)); } } } else { if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()).setIndexingResult(result)); + onActionError.accept(new OnActionErrorOptions(action.getAction()).setIndexingResult(result)); } } } 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 index 55dab982b93a..1dc83a0e062f 100644 --- 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 @@ -4,17 +4,15 @@ package com.azure.search.documents.implementation.batching; import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.rest.RequestOptions; 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.SearchClient; import com.azure.search.documents.models.IndexAction; import com.azure.search.documents.models.IndexBatchException; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.IndexDocumentsResult; import com.azure.search.documents.models.IndexingResult; import com.azure.search.documents.options.OnActionAddedOptions; @@ -28,6 +26,7 @@ import java.util.Collection; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -54,8 +53,7 @@ public final class SearchIndexingPublisher { private static final ClientLogger LOGGER = new ClientLogger(SearchIndexingPublisher.class); - private final SearchIndexClientImpl restClient; - private final JsonSerializer serializer; + private final SearchClient searchClient; private final boolean autoFlush; private int batchSize; @@ -63,31 +61,30 @@ public final class SearchIndexingPublisher { 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 Consumer onActionAdded; + private final Consumer onActionSent; + private final Consumer onActionSucceeded; + private final Consumer onActionError; - private final Function documentKeyRetriever; + private final Function, String> documentKeyRetriever; private final Function scaleDownFunction = size -> size / 2; - private final IndexingDocumentManager documentManager; + 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, + public SearchIndexingPublisher(SearchClient searchClient, + Function, String> documentKeyRetriever, boolean autoFlush, int initialBatchActionCount, int maxRetriesPerAction, Duration throttlingDelay, Duration maxThrottlingDelay, - Consumer> onActionAdded, Consumer> onActionSucceeded, - Consumer> onActionError, Consumer> onActionSent) { + 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.searchClient = searchClient; + this.documentManager = new IndexingDocumentManager(); this.autoFlush = autoFlush; this.batchSize = initialBatchActionCount; @@ -103,7 +100,7 @@ public SearchIndexingPublisher(SearchIndexClientImpl restClient, JsonSerializer this.onActionError = onActionError; } - public Collection> getActions() { + public Collection getActions() { return documentManager.getActions(); } @@ -115,7 +112,7 @@ public Duration getCurrentRetryDelay() { return currentRetryDelay; } - public void addActions(Collection> actions, Duration timeout, Context context, + public void addActions(Collection actions, Duration timeout, RequestOptions requestOptions, Runnable rescheduleFlush) { Tuple2 batchSizeAndAvailable = documentManager.addAndCheckForBatch(actions, documentKeyRetriever, onActionAdded, batchSize); @@ -125,22 +122,22 @@ public void addActions(Collection> actions, Duration timeout, Con if (autoFlush && batchSizeAndAvailable.getT2()) { rescheduleFlush.run(); LOGGER.verbose("Adding documents triggered batch size limit, sending documents for indexing."); - flush(false, false, timeout, context); + flush(false, false, timeout, requestOptions); } } - public void flush(boolean awaitLock, boolean isClose, Duration timeout, Context context) { + public void flush(boolean awaitLock, boolean isClose, Duration timeout, RequestOptions requestOptions) { if (awaitLock) { lock.lock(); try { - flushLoop(isClose, timeout, context); + flushLoop(isClose, timeout, requestOptions); } finally { lock.unlock(); } } else if (lock.tryLock()) { try { - flushLoop(isClose, timeout, context); + flushLoop(isClose, timeout, requestOptions); } finally { lock.unlock(); } @@ -149,11 +146,11 @@ public void flush(boolean awaitLock, boolean isClose, Duration timeout, Context } } - private void flushLoop(boolean isClosed, Duration timeout, Context context) { + private void flushLoop(boolean isClosed, Duration timeout, RequestOptions requestOptions) { if (timeout != null && !timeout.isNegative() && !timeout.isZero()) { - final AtomicReference>> batchActions = new AtomicReference<>(); - Future future - = SharedExecutorService.getInstance().submit(() -> flushLoopHelper(isClosed, context, batchActions)); + final AtomicReference> batchActions = new AtomicReference<>(); + Future future = SharedExecutorService.getInstance() + .submit(() -> flushLoopHelper(isClosed, requestOptions, batchActions)); try { CoreUtils.getResultWithTimeout(future, timeout); @@ -174,19 +171,19 @@ private void flushLoop(boolean isClosed, Duration timeout, Context context) { throw LOGGER.logExceptionAsError(new RuntimeException(e)); } } else { - flushLoopHelper(isClosed, context, null); + flushLoopHelper(isClosed, requestOptions, null); } } - private void flushLoopHelper(boolean isClosed, Context context, - AtomicReference>> batchActions) { - List> batch = documentManager.tryCreateBatch(batchSize, true); + private void flushLoopHelper(boolean isClosed, RequestOptions requestOptions, + AtomicReference> batchActions) { + List batch = documentManager.tryCreateBatch(batchSize, true); if (batchActions != null) { batchActions.set(batch); } // Process the current batch. - IndexBatchResponse response = processBatch(batch, context); + IndexBatchResponse response = processBatch(batch, requestOptions); // 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) { @@ -194,21 +191,20 @@ private void flushLoopHelper(boolean isClosed, Context context, batchActions.set(batch); } - response = processBatch(batch, context); + response = processBatch(batch, requestOptions); } } - private IndexBatchResponse processBatch(List> batchActions, Context context) { + private IndexBatchResponse processBatch(List batchActions, RequestOptions requestOptions) { // 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()); + List convertedActions + = batchActions.stream().map(TryTrackingIndexAction::getAction).collect(Collectors.toList()); - IndexBatchResponse response = sendBatch(convertedActions, batchActions, context); + IndexBatchResponse response = sendBatch(convertedActions, batchActions, requestOptions); handleResponse(batchActions, response); return response; @@ -218,12 +214,12 @@ private IndexBatchResponse processBatch(List> batchAct * 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) { + private IndexBatchResponse sendBatch(List actions, List batchActions, + RequestOptions requestOptions) { LOGGER.verbose("Sending a batch of size {}.", batchActions.size()); if (onActionSent != null) { - batchActions.forEach(action -> onActionSent.accept(new OnActionSentOptions<>(action.getAction()))); + batchActions.forEach(action -> onActionSent.accept(new OnActionSentOptions(action.getAction()))); } if (!currentRetryDelay.isZero() && !currentRetryDelay.isNegative()) { @@ -232,7 +228,7 @@ private IndexBatchResponse sendBatch(List batchCall - = Utility.indexDocumentsWithResponse(restClient, actions, true, context, LOGGER); + = searchClient.indexDocumentsWithResponse(new IndexDocumentsBatch(actions), null, requestOptions); return new IndexBatchResponse(batchCall.getStatusCode(), batchCall.getValue().getResults(), actions.size(), false); } catch (IndexBatchException exception) { @@ -264,12 +260,12 @@ private IndexBatchResponse sendBatch(List> batchActionsToRemove + List batchActionsToRemove = batchActions.subList(splitOffset, batchActions.size()); documentManager.reinsertFailedActions(batchActionsToRemove); batchActionsToRemove.clear(); - return sendBatch(actions.subList(0, splitOffset), batchActions, context); + return sendBatch(actions.subList(0, splitOffset), batchActions, requestOptions); } return new IndexBatchResponse(statusCode, null, actions.size(), true); @@ -279,20 +275,19 @@ private IndexBatchResponse sendBatch(List> actions, IndexBatchResponse batchResponse) { + 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(); + IndexAction action = actions.get(0).getAction(); if (onActionError != null) { - onActionError - .accept(new OnActionErrorOptions<>(action).setThrowable(createDocumentTooLargeException())); + onActionError.accept(new OnActionErrorOptions(action).setThrowable(createDocumentTooLargeException())); } return; } - LinkedList> actionsToRetry = new LinkedList<>(); + LinkedList actionsToRetry = new LinkedList<>(); boolean has503 = batchResponse.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; if (batchResponse.getResults() == null) { /* @@ -306,7 +301,7 @@ private void handleResponse(List> actions, IndexBatchR */ for (IndexingResult result : batchResponse.getResults()) { String key = result.getKey(); - TryTrackingIndexAction action + TryTrackingIndexAction action = actions.stream().filter(a -> key.equals(a.getKey())).findFirst().orElse(null); if (action == null) { @@ -316,7 +311,7 @@ private void handleResponse(List> actions, IndexBatchR if (isSuccess(result.getStatusCode())) { if (onActionSucceeded != null) { - onActionSucceeded.accept(new OnActionSucceededOptions<>(action.getAction())); + onActionSucceeded.accept(new OnActionSucceededOptions(action.getAction())); } } else if (isRetryable(result.getStatusCode())) { has503 |= result.getStatusCode() == HttpURLConnection.HTTP_UNAVAILABLE; @@ -325,14 +320,14 @@ private void handleResponse(List> actions, IndexBatchR actionsToRetry.add(action); } else { if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()) + onActionError.accept(new OnActionErrorOptions(action.getAction()) .setThrowable(createDocumentHitRetryLimitException()) .setIndexingResult(result)); } } } else { if (onActionError != null) { - onActionError.accept(new OnActionErrorOptions<>(action.getAction()).setIndexingResult(result)); + onActionError.accept(new OnActionErrorOptions(action.getAction()).setIndexingResult(result)); } } } 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 index 376c5994ea51..a7283bd7d6f8 100644 --- 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 @@ -8,18 +8,18 @@ /** * Model class that tracks the number of times an IndexAction has tried to be indexed. */ -final class TryTrackingIndexAction { - private final IndexAction action; +final class TryTrackingIndexAction { + private final IndexAction action; private final String key; private int tryCount = 0; - TryTrackingIndexAction(IndexAction action, String key) { + TryTrackingIndexAction(IndexAction action, String key) { this.action = action; this.key = key; } - public IndexAction getAction() { + public IndexAction getAction() { return action; } 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 9353873bb820..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/converters/SearchResultConverter.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.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(), - obj.getRerankerBoostedScore()); - 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 2f168c8abe95..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, Double rerankerBoostedScore); - - 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, Double rerankerBoostedScore) { - accessor.setSemanticSearchResults(searchResult, rerankerScore, captions, rerankerBoostedScore); - } - - 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/AutocompleteRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/AutocompletePostRequest.java similarity index 78% 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/implementation/models/AutocompletePostRequest.java index 8eceb502a093..54f5f9f22aae 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/implementation/models/AutocompletePostRequest.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -14,14 +11,17 @@ import com.azure.json.JsonWriter; import com.azure.search.documents.models.AutocompleteMode; import java.io.IOException; -import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; import java.util.List; +import java.util.stream.Collectors; /** - * Parameters for fuzzy matching, and other autocomplete query behaviors. + * The AutocompletePostRequest model. */ @Fluent -public final class AutocompleteRequest implements JsonSerializable { +public final class AutocompletePostRequest implements JsonSerializable { + /* * The search text on which to base autocomplete results. */ @@ -77,7 +77,7 @@ public final class AutocompleteRequest implements JsonSerializable searchFields; /* * The name of the suggester as specified in the suggesters collection that's part of the index definition. @@ -92,20 +92,20 @@ public final class AutocompleteRequest implements JsonSerializable getSearchFields() { return this.searchFields; } /** * Set the searchFields property: The comma-separated 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 AutocompleteRequest object itself. + * @return the AutocompletePostRequest object itself. */ @Generated - public AutocompleteRequest setSearchFields(String searchFields) { + public AutocompletePostRequest setSearchFields(List searchFields) { this.searchFields = searchFields; return this; } @@ -290,7 +290,7 @@ public AutocompleteRequest setSearchFields(String searchFields) { /** * Get the suggesterName property: The name of the suggester as specified in the suggesters collection that's part * of the index definition. - * + * * @return the suggesterName value. */ @Generated @@ -301,7 +301,7 @@ public String getSuggesterName() { /** * 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. */ @Generated @@ -312,12 +312,12 @@ public Integer getTop() { /** * 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 AutocompleteRequest object itself. + * @return the AutocompletePostRequest object itself. */ @Generated - public AutocompleteRequest setTop(Integer top) { + public AutocompletePostRequest setTop(Integer top) { this.top = top; return this; } @@ -338,26 +338,29 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("highlightPostTag", this.highlightPostTag); jsonWriter.writeStringField("highlightPreTag", this.highlightPreTag); jsonWriter.writeNumberField("minimumCoverage", this.minimumCoverage); - jsonWriter.writeStringField("searchFields", this.searchFields); + if (this.searchFields != null) { + jsonWriter.writeStringField("searchFields", + this.searchFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } jsonWriter.writeNumberField("top", this.top); return jsonWriter.writeEndObject(); } /** - * Reads an instance of AutocompleteRequest from the JsonReader. - * + * Reads an instance of AutocompletePostRequest from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of AutocompleteRequest if the JsonReader was pointing to an instance of it, or null if it was - * pointing to JSON null. + * @return An instance of AutocompletePostRequest 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 AutocompleteRequest. + * @throws IOException If an error occurs while reading the AutocompletePostRequest. */ @Generated - public static AutocompleteRequest fromJson(JsonReader jsonReader) throws IOException { + public static AutocompletePostRequest fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean searchTextFound = false; String searchText = null; - boolean suggesterNameFound = false; String suggesterName = null; AutocompleteMode autocompleteMode = null; String filter = null; @@ -365,18 +368,15 @@ public static AutocompleteRequest fromJson(JsonReader jsonReader) throws IOExcep String highlightPostTag = null; String highlightPreTag = null; Double minimumCoverage = null; - String searchFields = null; + List searchFields = null; Integer top = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -390,37 +390,29 @@ public static AutocompleteRequest fromJson(JsonReader jsonReader) throws IOExcep } else if ("minimumCoverage".equals(fieldName)) { minimumCoverage = reader.getNullable(JsonReader::getDouble); } else if ("searchFields".equals(fieldName)) { - searchFields = reader.getString(); + searchFields = reader.getNullable(nonNullReader -> { + String searchFieldsEncodedAsString = nonNullReader.getString(); + return searchFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(searchFieldsEncodedAsString.split(",", -1))); + }); } else if ("top".equals(fieldName)) { top = reader.getNullable(JsonReader::getInt); } else { 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)); + AutocompletePostRequest deserializedAutocompletePostRequest + = new AutocompletePostRequest(searchText, suggesterName); + deserializedAutocompletePostRequest.autocompleteMode = autocompleteMode; + deserializedAutocompletePostRequest.filter = filter; + deserializedAutocompletePostRequest.useFuzzyMatching = useFuzzyMatching; + deserializedAutocompletePostRequest.highlightPostTag = highlightPostTag; + deserializedAutocompletePostRequest.highlightPreTag = highlightPreTag; + deserializedAutocompletePostRequest.minimumCoverage = minimumCoverage; + deserializedAutocompletePostRequest.searchFields = searchFields; + deserializedAutocompletePostRequest.top = top; + return deserializedAutocompletePostRequest; }); } } 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 c475bece6945..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorAdditionalInfo.java +++ /dev/null @@ -1,99 +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.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; - -/** - * The resource management error additional info. - */ -@Immutable -public final class ErrorAdditionalInfo implements JsonSerializable { - /* - * The additional info type. - */ - @Generated - private String type; - - /* - * The additional info. - */ - @Generated - private Object info; - - /** - * Creates an instance of ErrorAdditionalInfo class. - */ - @Generated - public ErrorAdditionalInfo() { - } - - /** - * Get the type property: The additional info type. - * - * @return the type value. - */ - @Generated - public String getType() { - return this.type; - } - - /** - * Get the info property: The additional info. - * - * @return the info value. - */ - @Generated - public Object getInfo() { - return this.info; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 4c6e6540f43c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorDetail.java +++ /dev/null @@ -1,157 +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.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.List; - -/** - * The error detail. - */ -@Immutable -public final class ErrorDetail implements JsonSerializable { - /* - * The error code. - */ - @Generated - private String code; - - /* - * The error message. - */ - @Generated - private String message; - - /* - * The error target. - */ - @Generated - private String target; - - /* - * The error details. - */ - @Generated - private List details; - - /* - * The error additional info. - */ - @Generated - private List additionalInfo; - - /** - * Creates an instance of ErrorDetail class. - */ - @Generated - public ErrorDetail() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - @Generated - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - @Generated - public String getMessage() { - return this.message; - } - - /** - * Get the target property: The error target. - * - * @return the target value. - */ - @Generated - public String getTarget() { - return this.target; - } - - /** - * Get the details property: The error details. - * - * @return the details value. - */ - @Generated - public List getDetails() { - return this.details; - } - - /** - * Get the additionalInfo property: The error additional info. - * - * @return the additionalInfo value. - */ - @Generated - public List getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 d8daad91cab4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/ErrorResponse.java +++ /dev/null @@ -1,97 +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.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; - -/** - * 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. - */ - @Generated - private ErrorDetail error; - - /** - * Creates an instance of ErrorResponse class. - */ - @Generated - public ErrorResponse() { - } - - /** - * Get the error property: The error object. - * - * @return the error value. - */ - @Generated - 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. - */ - @Generated - public ErrorResponse setError(ErrorDetail error) { - this.error = error; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 acc7af4cdd65..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/IndexAction.java +++ /dev/null @@ -1,155 +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.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.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. - */ - @Generated - private IndexActionType actionType; - - /* - * Represents an index action that operates on a document. - */ - @Generated - private Map additionalProperties; - - /** - * Creates an instance of IndexAction class. - */ - @Generated - public IndexAction() { - } - - /** - * Get the actionType property: The operation to perform on a document in an indexing batch. - * - * @return the actionType value. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - public IndexAction setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; - } - - /** - * {@inheritDoc} - */ - @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.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. - */ - @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.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 0335195d60ce..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/RequestOptions.java +++ /dev/null @@ -1,52 +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.core.annotation.Generated; -import java.util.UUID; - -/** - * Parameter group. - */ -@Fluent -public final class RequestOptions { - /* - * The tracking ID sent with the request to help with debugging. - */ - @Generated - private UUID xMsClientRequestId; - - /** - * Creates an instance of RequestOptions class. - */ - @Generated - public RequestOptions() { - } - - /** - * Get the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @return the xMsClientRequestId value. - */ - @Generated - 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. - */ - @Generated - 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 aeef5beda04b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchOptions.java +++ /dev/null @@ -1,1048 +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.core.annotation.Generated; -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. - */ - @Generated - 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. - */ - @Generated - private List facets; - - /* - * The OData $filter expression to apply to the search query. - */ - @Generated - private String filter; - - /* - * The list of field names to use for hit highlights. Only searchable fields can be used for hit highlighting. - */ - @Generated - private List highlightFields; - - /* - * 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>. - */ - @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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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). - */ - @Generated - private List scoringParameters; - - /* - * The name of a scoring profile to evaluate match scores for matching documents in order to sort the results. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - private String sessionId; - - /* - * The list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included. - */ - @Generated - 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. - */ - @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. - */ - @Generated - private Integer top; - - /* - * The name of the semantic configuration that lists which fields should be used for semantic ranking, captions, - * highlights, and answers - */ - @Generated - private String semanticConfiguration; - - /* - * Allows the user to choose whether a semantic call should fail completely, or to return partial results (default). - */ - @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. - */ - @Generated - 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'. - */ - @Generated - 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'. - */ - @Generated - 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. - */ - @Generated - 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`. - */ - @Generated - private String queryRewrites; - - /* - * Enables a debugging tool that can be used to further explore your search results. - */ - @Generated - private QueryDebugMode debug; - - /* - * The language of the query. - */ - @Generated - private QueryLanguage queryLanguage; - - /* - * Improve search recall by spell-correcting individual search query terms. - */ - @Generated - private QuerySpellerType speller; - - /* - * The list of field names used for semantic ranking. - */ - @Generated - private List semanticFields; - - /** - * Creates an instance of SearchOptions class. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param facets the facets value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param minimumCoverage the minimumCoverage value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param queryType the queryType value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @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). - * - * @param scoringParameters the scoringParameters value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @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. - * - * @param scoringProfile the scoringProfile value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param searchMode the searchMode value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @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. - * - * @param scoringStatistics the scoringStatistics value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param skip the skip value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @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. - * - * @param top the top value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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. - * - * @param semanticQuery the semanticQuery value to set. - * @return the SearchOptions object itself. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - public SearchOptions setDebug(QueryDebugMode debug) { - this.debug = debug; - return this; - } - - /** - * Get the queryLanguage property: The language of the query. - * - * @return the queryLanguage value. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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/SearchPostRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchPostRequest.java new file mode 100644 index 000000000000..34c340ebe7c8 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchPostRequest.java @@ -0,0 +1,1274 @@ +// 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.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.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.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.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * The SearchPostRequest model. + */ +@Fluent +public final class SearchPostRequest 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. + */ + @Generated + 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. + */ + @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. + */ + @Generated + private List highlightFields; + + /* + * 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>. + */ + @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. + */ + @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. + */ + @Generated + 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. + */ + @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. + */ + @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. + */ + @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). + */ + @Generated + private List scoringParameters; + + /* + * 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. + */ + @Generated + private QueryDebugMode debug; + + /* + * 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. + */ + @Generated + 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. + */ + @Generated + private SearchMode searchMode; + + /* + * A value that specifies the language of the search query. + */ + @Generated + private QueryLanguage queryLanguage; + + /* + * A value that specifies the type of the speller to use to spell-correct individual search query terms. + */ + @Generated + private QuerySpellerType querySpeller; + + /* + * The comma-separated list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema + * are included. + */ + @Generated + 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. + */ + @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. + */ + @Generated + private Integer top; + + /* + * The name of a semantic configuration that will be used when processing documents for queries of type semantic. + */ + @Generated + private String semanticConfigurationName; + + /* + * 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. + */ + @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. + */ + @Generated + private String semanticQuery; + + /* + * A value that specifies whether answers should be returned as part of the search response. + */ + @Generated + private QueryAnswerType answers; + + /* + * A value that specifies whether captions should be returned as part of the search response. + */ + @Generated + private QueryCaptionType captions; + + /* + * A value that specifies whether query rewrites should be generated to augment the search query. + */ + @Generated + private QueryRewritesType queryRewrites; + + /* + * The comma-separated list of field names used for semantic ranking. + */ + @Generated + private List 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. + */ + @Generated + private VectorFilterMode vectorFilterMode; + + /* + * The query parameters to configure hybrid search behaviors. + */ + @Generated + private HybridSearch hybridSearch; + + /** + * Creates an instance of SearchPostRequest class. + */ + @Generated + public SearchPostRequest() { + } + + /** + * 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. + */ + @Generated + public Boolean isIncludeTotalCount() { + 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param facets the facets value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @Generated + 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setFilter(String filter) { + this.filter = filter; + return this; + } + + /** + * Get the highlightFields property: The comma-separated list of field names to use for hit highlights. Only + * searchable fields can be used for hit highlighting. + * + * @return the highlightFields value. + */ + @Generated + public List getHighlightFields() { + return this.highlightFields; + } + + /** + * Set the highlightFields property: The comma-separated 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @Generated + 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @Generated + 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param minimumCoverage the minimumCoverage value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + * + * @return the orderBy value. + */ + @Generated + public List 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. + * + * @param orderBy the orderBy value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param queryType the queryType value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setQueryType(QueryType queryType) { + this.queryType = queryType; + 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. 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. + * + * @param scoringStatistics the scoringStatistics value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + * + * @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. + * + * @param sessionId the sessionId value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSessionId(String sessionId) { + this.sessionId = sessionId; + 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. + */ + @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). + * + * @param scoringParameters the scoringParameters value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param scoringProfile the scoringProfile value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + * + * @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. + * + * @param debug the debug value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + * + * @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. + * + * @param searchText the searchText value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSearchText(String searchText) { + this.searchText = searchText; + return this; + } + + /** + * 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. + * + * @return the searchFields value. + */ + @Generated + public List 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. + * + * @param searchFields the searchFields value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param searchMode the searchMode value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSearchMode(SearchMode searchMode) { + this.searchMode = searchMode; + return this; + } + + /** + * Get the queryLanguage property: A value that specifies the language of the search query. + * + * @return the queryLanguage value. + */ + @Generated + public QueryLanguage getQueryLanguage() { + return this.queryLanguage; + } + + /** + * Set the queryLanguage property: A value that specifies the language of the search query. + * + * @param queryLanguage the queryLanguage value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setQueryLanguage(QueryLanguage queryLanguage) { + this.queryLanguage = queryLanguage; + return this; + } + + /** + * Get the querySpeller property: A value that specifies the type of the speller to use to spell-correct individual + * search query terms. + * + * @return the querySpeller value. + */ + @Generated + public QuerySpellerType getQuerySpeller() { + return this.querySpeller; + } + + /** + * Set the querySpeller property: A value that specifies the type of the speller to use to spell-correct individual + * search query terms. + * + * @param querySpeller the querySpeller value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setQuerySpeller(QuerySpellerType querySpeller) { + this.querySpeller = querySpeller; + 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. + * + * @return the select value. + */ + @Generated + public List 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. + * + * @param select the select value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param skip the skip value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param top the top value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setTop(Integer top) { + this.top = top; + return this; + } + + /** + * Get the semanticConfigurationName property: The name of a semantic configuration that will be used when + * processing documents for queries of type semantic. + * + * @return the semanticConfigurationName value. + */ + @Generated + public String getSemanticConfigurationName() { + return this.semanticConfigurationName; + } + + /** + * Set the semanticConfigurationName property: The name of a semantic configuration that will be used when + * processing documents for queries of type semantic. + * + * @param semanticConfigurationName the semanticConfigurationName value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSemanticConfigurationName(String semanticConfigurationName) { + this.semanticConfigurationName = semanticConfigurationName; + return this; + } + + /** + * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely + * (default / current behavior), or to return partial results. + * + * @return the semanticErrorHandling value. + */ + @Generated + public SemanticErrorMode getSemanticErrorHandling() { + return this.semanticErrorHandling; + } + + /** + * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely + * (default / current behavior), or to return partial results. + * + * @param semanticErrorHandling the semanticErrorHandling value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest 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. + */ + @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. + * + * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { + this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; + 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. + */ + @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. + * + * @param semanticQuery the semanticQuery value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSemanticQuery(String semanticQuery) { + this.semanticQuery = semanticQuery; + return this; + } + + /** + * Get the answers property: A value that specifies whether answers should be returned as part of the search + * response. + * + * @return the answers value. + */ + @Generated + public QueryAnswerType getAnswers() { + return this.answers; + } + + /** + * 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setAnswers(QueryAnswerType answers) { + this.answers = answers; + return this; + } + + /** + * Get the captions property: A value that specifies whether captions should be returned as part of the search + * response. + * + * @return the captions value. + */ + @Generated + public QueryCaptionType getCaptions() { + return this.captions; + } + + /** + * 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setCaptions(QueryCaptionType captions) { + this.captions = captions; + return this; + } + + /** + * Get the queryRewrites property: A value that specifies whether query rewrites should be generated to augment the + * search query. + * + * @return the queryRewrites value. + */ + @Generated + public QueryRewritesType getQueryRewrites() { + return this.queryRewrites; + } + + /** + * 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 SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setQueryRewrites(QueryRewritesType queryRewrites) { + this.queryRewrites = queryRewrites; + return this; + } + + /** + * Get the semanticFields property: The comma-separated list of field names used for semantic ranking. + * + * @return the semanticFields value. + */ + @Generated + public List getSemanticFields() { + return this.semanticFields; + } + + /** + * Set the semanticFields property: The comma-separated list of field names used for semantic ranking. + * + * @param semanticFields the semanticFields value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setSemanticFields(List semanticFields) { + this.semanticFields = semanticFields; + return this; + } + + /** + * Get the vectorQueries property: The query parameters for vector and hybrid search queries. + * + * @return the vectorQueries value. + */ + @Generated + public List getVectorQueries() { + return this.vectorQueries; + } + + /** + * Set the vectorQueries property: The query parameters for vector and hybrid search queries. + * + * @param vectorQueries the vectorQueries value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setVectorQueries(List vectorQueries) { + this.vectorQueries = vectorQueries; + return this; + } + + /** + * 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. + * + * @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. + * + * @param vectorFilterMode the vectorFilterMode value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setVectorFilterMode(VectorFilterMode vectorFilterMode) { + this.vectorFilterMode = vectorFilterMode; + return this; + } + + /** + * Get the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @return the hybridSearch value. + */ + @Generated + public HybridSearch getHybridSearch() { + return this.hybridSearch; + } + + /** + * Set the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @param hybridSearch the hybridSearch value to set. + * @return the SearchPostRequest object itself. + */ + @Generated + public SearchPostRequest setHybridSearch(HybridSearch hybridSearch) { + this.hybridSearch = hybridSearch; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeBooleanField("count", this.includeTotalCount); + jsonWriter.writeArrayField("facets", this.facets, (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("filter", this.filter); + if (this.highlightFields != null) { + jsonWriter.writeStringField("highlight", + this.highlightFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } + jsonWriter.writeStringField("highlightPostTag", this.highlightPostTag); + jsonWriter.writeStringField("highlightPreTag", this.highlightPreTag); + jsonWriter.writeNumberField("minimumCoverage", this.minimumCoverage); + if (this.orderBy != null) { + jsonWriter.writeStringField("orderby", + this.orderBy.stream().map(element -> element == null ? "" : element).collect(Collectors.joining(","))); + } + jsonWriter.writeStringField("queryType", this.queryType == null ? null : this.queryType.toString()); + jsonWriter.writeStringField("scoringStatistics", + this.scoringStatistics == null ? null : this.scoringStatistics.toString()); + jsonWriter.writeStringField("sessionId", this.sessionId); + jsonWriter.writeArrayField("scoringParameters", this.scoringParameters, + (writer, element) -> writer.writeString(element)); + jsonWriter.writeStringField("scoringProfile", this.scoringProfile); + jsonWriter.writeStringField("debug", this.debug == null ? null : this.debug.toString()); + jsonWriter.writeStringField("search", this.searchText); + if (this.searchFields != null) { + jsonWriter.writeStringField("searchFields", + this.searchFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } + jsonWriter.writeStringField("searchMode", this.searchMode == null ? null : this.searchMode.toString()); + jsonWriter.writeStringField("queryLanguage", this.queryLanguage == null ? null : this.queryLanguage.toString()); + jsonWriter.writeStringField("speller", this.querySpeller == null ? null : this.querySpeller.toString()); + if (this.select != null) { + jsonWriter.writeStringField("select", + this.select.stream().map(element -> element == null ? "" : element).collect(Collectors.joining(","))); + } + jsonWriter.writeNumberField("skip", this.skip); + jsonWriter.writeNumberField("top", this.top); + jsonWriter.writeStringField("semanticConfiguration", this.semanticConfigurationName); + jsonWriter.writeStringField("semanticErrorHandling", + this.semanticErrorHandling == null ? null : this.semanticErrorHandling.toString()); + jsonWriter.writeNumberField("semanticMaxWaitInMilliseconds", this.semanticMaxWaitInMilliseconds); + jsonWriter.writeStringField("semanticQuery", this.semanticQuery); + 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()); + if (this.semanticFields != null) { + jsonWriter.writeStringField("semanticFields", + this.semanticFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } + jsonWriter.writeArrayField("vectorQueries", this.vectorQueries, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("vectorFilterMode", + this.vectorFilterMode == null ? null : this.vectorFilterMode.toString()); + jsonWriter.writeJsonField("hybridSearch", this.hybridSearch); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of SearchPostRequest from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchPostRequest 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 SearchPostRequest. + */ + @Generated + public static SearchPostRequest fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + SearchPostRequest deserializedSearchPostRequest = new SearchPostRequest(); + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("count".equals(fieldName)) { + deserializedSearchPostRequest.includeTotalCount = reader.getNullable(JsonReader::getBoolean); + } else if ("facets".equals(fieldName)) { + List facets = reader.readArray(reader1 -> reader1.getString()); + deserializedSearchPostRequest.facets = facets; + } else if ("filter".equals(fieldName)) { + deserializedSearchPostRequest.filter = reader.getString(); + } else if ("highlight".equals(fieldName)) { + List highlightFields = reader.getNullable(nonNullReader -> { + String highlightFieldsEncodedAsString = nonNullReader.getString(); + return highlightFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(highlightFieldsEncodedAsString.split(",", -1))); + }); + deserializedSearchPostRequest.highlightFields = highlightFields; + } else if ("highlightPostTag".equals(fieldName)) { + deserializedSearchPostRequest.highlightPostTag = reader.getString(); + } else if ("highlightPreTag".equals(fieldName)) { + deserializedSearchPostRequest.highlightPreTag = reader.getString(); + } else if ("minimumCoverage".equals(fieldName)) { + deserializedSearchPostRequest.minimumCoverage = reader.getNullable(JsonReader::getDouble); + } else if ("orderby".equals(fieldName)) { + List orderBy = reader.getNullable(nonNullReader -> { + String orderByEncodedAsString = nonNullReader.getString(); + return orderByEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(orderByEncodedAsString.split(",", -1))); + }); + deserializedSearchPostRequest.orderBy = orderBy; + } else if ("queryType".equals(fieldName)) { + deserializedSearchPostRequest.queryType = QueryType.fromString(reader.getString()); + } else if ("scoringStatistics".equals(fieldName)) { + deserializedSearchPostRequest.scoringStatistics = ScoringStatistics.fromString(reader.getString()); + } else if ("sessionId".equals(fieldName)) { + deserializedSearchPostRequest.sessionId = reader.getString(); + } else if ("scoringParameters".equals(fieldName)) { + List scoringParameters = reader.readArray(reader1 -> reader1.getString()); + deserializedSearchPostRequest.scoringParameters = scoringParameters; + } else if ("scoringProfile".equals(fieldName)) { + deserializedSearchPostRequest.scoringProfile = reader.getString(); + } else if ("debug".equals(fieldName)) { + deserializedSearchPostRequest.debug = QueryDebugMode.fromString(reader.getString()); + } else if ("search".equals(fieldName)) { + deserializedSearchPostRequest.searchText = reader.getString(); + } else if ("searchFields".equals(fieldName)) { + List searchFields = reader.getNullable(nonNullReader -> { + String searchFieldsEncodedAsString = nonNullReader.getString(); + return searchFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(searchFieldsEncodedAsString.split(",", -1))); + }); + deserializedSearchPostRequest.searchFields = searchFields; + } else if ("searchMode".equals(fieldName)) { + deserializedSearchPostRequest.searchMode = SearchMode.fromString(reader.getString()); + } else if ("queryLanguage".equals(fieldName)) { + deserializedSearchPostRequest.queryLanguage = QueryLanguage.fromString(reader.getString()); + } else if ("speller".equals(fieldName)) { + deserializedSearchPostRequest.querySpeller = QuerySpellerType.fromString(reader.getString()); + } else if ("select".equals(fieldName)) { + List select = reader.getNullable(nonNullReader -> { + String selectEncodedAsString = nonNullReader.getString(); + return selectEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(selectEncodedAsString.split(",", -1))); + }); + deserializedSearchPostRequest.select = select; + } else if ("skip".equals(fieldName)) { + deserializedSearchPostRequest.skip = reader.getNullable(JsonReader::getInt); + } else if ("top".equals(fieldName)) { + deserializedSearchPostRequest.top = reader.getNullable(JsonReader::getInt); + } else if ("semanticConfiguration".equals(fieldName)) { + deserializedSearchPostRequest.semanticConfigurationName = reader.getString(); + } else if ("semanticErrorHandling".equals(fieldName)) { + deserializedSearchPostRequest.semanticErrorHandling + = SemanticErrorMode.fromString(reader.getString()); + } else if ("semanticMaxWaitInMilliseconds".equals(fieldName)) { + deserializedSearchPostRequest.semanticMaxWaitInMilliseconds + = reader.getNullable(JsonReader::getInt); + } else if ("semanticQuery".equals(fieldName)) { + deserializedSearchPostRequest.semanticQuery = reader.getString(); + } else if ("answers".equals(fieldName)) { + deserializedSearchPostRequest.answers = QueryAnswerType.fromString(reader.getString()); + } else if ("captions".equals(fieldName)) { + deserializedSearchPostRequest.captions = QueryCaptionType.fromString(reader.getString()); + } else if ("queryRewrites".equals(fieldName)) { + deserializedSearchPostRequest.queryRewrites = QueryRewritesType.fromString(reader.getString()); + } else if ("semanticFields".equals(fieldName)) { + List semanticFields = reader.getNullable(nonNullReader -> { + String semanticFieldsEncodedAsString = nonNullReader.getString(); + return semanticFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(semanticFieldsEncodedAsString.split(",", -1))); + }); + deserializedSearchPostRequest.semanticFields = semanticFields; + } else if ("vectorQueries".equals(fieldName)) { + List vectorQueries = reader.readArray(reader1 -> VectorQuery.fromJson(reader1)); + deserializedSearchPostRequest.vectorQueries = vectorQueries; + } else if ("vectorFilterMode".equals(fieldName)) { + deserializedSearchPostRequest.vectorFilterMode = VectorFilterMode.fromString(reader.getString()); + } else if ("hybridSearch".equals(fieldName)) { + deserializedSearchPostRequest.hybridSearch = HybridSearch.fromJson(reader); + } else { + reader.skipChildren(); + } + } + return deserializedSearchPostRequest; + }); + } +} 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 aae5e343dfb8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SearchResult.java +++ /dev/null @@ -1,247 +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.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.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. - */ - @Generated - 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'. - */ - @Generated - private Double rerankerScore; - - /* - * The relevance score computed by boosting the Reranker Score. Search results are sorted by the - * RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic Config. - * RerankerBoostedScore is only returned for queries of type 'semantic' - */ - @Generated - private Double rerankerBoostedScore; - - /* - * 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; - - /* - * 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'. - */ - @Generated - private List captions; - - /* - * Contains debugging information that can be used to further explore your search results. - */ - @Generated - private DocumentDebugInfo documentDebugInfo; - - /* - * Contains a document found by a search query, plus associated metadata. - */ - @Generated - private Map additionalProperties; - - /** - * Creates an instance of SearchResult class. - * - * @param score the score value to set. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - public Double getRerankerScore() { - return this.rerankerScore; - } - - /** - * Get the rerankerBoostedScore property: The relevance score computed by boosting the Reranker Score. Search - * results are sorted by the RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the - * Semantic Config. RerankerBoostedScore is only returned for queries of type 'semantic'. - * - * @return the rerankerBoostedScore value. - */ - @Generated - public Double getRerankerBoostedScore() { - return this.rerankerBoostedScore; - } - - /** - * 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 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. - * - * @return the documentDebugInfo value. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - public SearchResult setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - public static SearchResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean scoreFound = false; - double score = 0.0; - Double rerankerScore = null; - Double rerankerBoostedScore = 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.rerankerBoostedScore".equals(fieldName)) { - rerankerBoostedScore = 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.rerankerBoostedScore = rerankerBoostedScore; - 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/SuggestRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestPostRequest.java similarity index 74% 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/implementation/models/SuggestPostRequest.java index 53810e74055a..bc598f8eea70 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/implementation/models/SuggestPostRequest.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,14 +10,17 @@ 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.LinkedList; import java.util.List; +import java.util.stream.Collectors; /** - * Parameters for filtering, sorting, fuzzy matching, and other suggestions query behaviors. + * The SuggestPostRequest model. */ @Fluent -public final class SuggestRequest implements JsonSerializable { +public final class SuggestPostRequest implements JsonSerializable { + /* * An OData expression that filters the documents considered for suggestions. */ @@ -66,7 +66,7 @@ public final class SuggestRequest implements JsonSerializable { * descending by document match score. There can be at most 32 $orderby clauses. */ @Generated - private String orderBy; + private List orderBy; /* * The search text to use to suggest documents. Must be at least 1 character, and no more than 100 characters. @@ -79,14 +79,14 @@ public final class SuggestRequest implements JsonSerializable { * in the specified suggester. */ @Generated - private String searchFields; + private List searchFields; /* * The comma-separated list of fields to retrieve. If unspecified, only the key field will be included in the * results. */ @Generated - private String select; + private List select; /* * The name of the suggester as specified in the suggesters collection that's part of the index definition. @@ -101,20 +101,20 @@ public final class SuggestRequest implements JsonSerializable { private Integer top; /** - * Creates an instance of SuggestRequest class. - * + * Creates an instance of SuggestPostRequest class. + * * @param searchText the searchText value to set. * @param suggesterName the suggesterName value to set. */ @Generated - public SuggestRequest(String searchText, String suggesterName) { + public SuggestPostRequest(String searchText, String suggesterName) { this.searchText = searchText; this.suggesterName = suggesterName; } /** * Get the filter property: An OData expression that filters the documents considered for suggestions. - * + * * @return the filter value. */ @Generated @@ -124,12 +124,12 @@ public String getFilter() { /** * Set the filter property: An OData expression that filters the documents considered for suggestions. - * + * * @param filter the filter value to set. - * @return the SuggestRequest object itself. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setFilter(String filter) { + public SuggestPostRequest setFilter(String filter) { this.filter = filter; return this; } @@ -139,7 +139,7 @@ public SuggestRequest setFilter(String filter) { * 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 @@ -152,12 +152,12 @@ public Boolean isUseFuzzyMatching() { * 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. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setUseFuzzyMatching(Boolean useFuzzyMatching) { + public SuggestPostRequest setUseFuzzyMatching(Boolean useFuzzyMatching) { this.useFuzzyMatching = useFuzzyMatching; return this; } @@ -165,7 +165,7 @@ public SuggestRequest setUseFuzzyMatching(Boolean useFuzzyMatching) { /** * 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. */ @Generated @@ -176,12 +176,12 @@ public String getHighlightPostTag() { /** * 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 SuggestRequest object itself. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setHighlightPostTag(String highlightPostTag) { + public SuggestPostRequest setHighlightPostTag(String highlightPostTag) { this.highlightPostTag = highlightPostTag; return this; } @@ -189,7 +189,7 @@ public SuggestRequest setHighlightPostTag(String highlightPostTag) { /** * 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. */ @Generated @@ -200,12 +200,12 @@ public String getHighlightPreTag() { /** * 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 SuggestRequest object itself. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setHighlightPreTag(String highlightPreTag) { + public SuggestPostRequest setHighlightPreTag(String highlightPreTag) { this.highlightPreTag = highlightPreTag; return this; } @@ -214,7 +214,7 @@ 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. - * + * * @return the minimumCoverage value. */ @Generated @@ -226,12 +226,12 @@ public Double getMinimumCoverage() { * 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. - * + * * @param minimumCoverage the minimumCoverage value to set. - * @return the SuggestRequest object itself. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setMinimumCoverage(Double minimumCoverage) { + public SuggestPostRequest setMinimumCoverage(Double minimumCoverage) { this.minimumCoverage = minimumCoverage; return this; } @@ -242,11 +242,11 @@ public SuggestRequest setMinimumCoverage(Double minimumCoverage) { * 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() { + public List getOrderBy() { return this.orderBy; } @@ -256,12 +256,12 @@ public String getOrderBy() { * 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. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setOrderBy(String orderBy) { + public SuggestPostRequest setOrderBy(List orderBy) { this.orderBy = orderBy; return this; } @@ -269,7 +269,7 @@ public SuggestRequest setOrderBy(String orderBy) { /** * 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 @@ -280,23 +280,23 @@ public String getSearchText() { /** * 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() { + public List 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. - * + * * @param searchFields the searchFields value to set. - * @return the SuggestRequest object itself. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setSearchFields(String searchFields) { + public SuggestPostRequest setSearchFields(List searchFields) { this.searchFields = searchFields; return this; } @@ -304,23 +304,23 @@ public SuggestRequest setSearchFields(String searchFields) { /** * 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() { + public List 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. - * + * * @param select the select value to set. - * @return the SuggestRequest object itself. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setSelect(String select) { + public SuggestPostRequest setSelect(List select) { this.select = select; return this; } @@ -328,7 +328,7 @@ public SuggestRequest setSelect(String select) { /** * Get the suggesterName property: The name of the suggester as specified in the suggesters collection that's part * of the index definition. - * + * * @return the suggesterName value. */ @Generated @@ -339,7 +339,7 @@ public String getSuggesterName() { /** * 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 @@ -350,12 +350,12 @@ public Integer getTop() { /** * 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. + * @return the SuggestPostRequest object itself. */ @Generated - public SuggestRequest setTop(Integer top) { + public SuggestPostRequest setTop(Integer top) { this.top = top; return this; } @@ -374,48 +374,54 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("highlightPostTag", this.highlightPostTag); jsonWriter.writeStringField("highlightPreTag", this.highlightPreTag); jsonWriter.writeNumberField("minimumCoverage", this.minimumCoverage); - jsonWriter.writeStringField("orderby", this.orderBy); - jsonWriter.writeStringField("searchFields", this.searchFields); - jsonWriter.writeStringField("select", this.select); + if (this.orderBy != null) { + jsonWriter.writeStringField("orderby", + this.orderBy.stream().map(element -> element == null ? "" : element).collect(Collectors.joining(","))); + } + if (this.searchFields != null) { + jsonWriter.writeStringField("searchFields", + this.searchFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } + if (this.select != null) { + jsonWriter.writeStringField("select", + this.select.stream().map(element -> element == null ? "" : element).collect(Collectors.joining(","))); + } jsonWriter.writeNumberField("top", this.top); return jsonWriter.writeEndObject(); } /** - * Reads an instance of SuggestRequest from the JsonReader. - * + * Reads an instance of SuggestPostRequest from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of SuggestRequest if the JsonReader was pointing to an instance of it, or null if it was + * @return An instance of SuggestPostRequest 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 SuggestRequest. + * @throws IOException If an error occurs while reading the SuggestPostRequest. */ @Generated - public static SuggestRequest fromJson(JsonReader jsonReader) throws IOException { + public static SuggestPostRequest 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; String highlightPostTag = null; String highlightPreTag = null; Double minimumCoverage = null; - String orderBy = null; - String searchFields = null; - String select = null; + List orderBy = null; + List searchFields = null; + List select = null; Integer top = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -427,41 +433,43 @@ public static SuggestRequest fromJson(JsonReader jsonReader) throws IOException } else if ("minimumCoverage".equals(fieldName)) { minimumCoverage = reader.getNullable(JsonReader::getDouble); } else if ("orderby".equals(fieldName)) { - orderBy = reader.getString(); + orderBy = reader.getNullable(nonNullReader -> { + String orderByEncodedAsString = nonNullReader.getString(); + return orderByEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(orderByEncodedAsString.split(",", -1))); + }); } else if ("searchFields".equals(fieldName)) { - searchFields = reader.getString(); + searchFields = reader.getNullable(nonNullReader -> { + String searchFieldsEncodedAsString = nonNullReader.getString(); + return searchFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(searchFieldsEncodedAsString.split(",", -1))); + }); } else if ("select".equals(fieldName)) { - select = reader.getString(); + select = reader.getNullable(nonNullReader -> { + String selectEncodedAsString = nonNullReader.getString(); + return selectEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(selectEncodedAsString.split(",", -1))); + }); } else if ("top".equals(fieldName)) { top = reader.getNullable(JsonReader::getInt); } else { 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)); + SuggestPostRequest deserializedSuggestPostRequest = new SuggestPostRequest(searchText, suggesterName); + deserializedSuggestPostRequest.filter = filter; + deserializedSuggestPostRequest.useFuzzyMatching = useFuzzyMatching; + deserializedSuggestPostRequest.highlightPostTag = highlightPostTag; + deserializedSuggestPostRequest.highlightPreTag = highlightPreTag; + deserializedSuggestPostRequest.minimumCoverage = minimumCoverage; + deserializedSuggestPostRequest.orderBy = orderBy; + deserializedSuggestPostRequest.searchFields = searchFields; + deserializedSuggestPostRequest.select = select; + deserializedSuggestPostRequest.top = top; + return deserializedSuggestPostRequest; }); } } 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 18ded45dff6b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/models/SuggestResult.java +++ /dev/null @@ -1,134 +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.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.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. - */ - @Generated - private final String text; - - /* - * A result containing a document found by a suggestion query, plus associated metadata. - */ - @Generated - private Map additionalProperties; - - /** - * Creates an instance of SuggestResult class. - * - * @param text the text value to set. - */ - @Generated - public SuggestResult(String text) { - this.text = text; - } - - /** - * Get the text property: The text of the suggestion result. - * - * @return the text value. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - public SuggestResult setAdditionalProperties(Map additionalProperties) { - this.additionalProperties = additionalProperties; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 index 6909eb5abf62..bcdb4c7a4c8b 100644 --- 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 @@ -1,11 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.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..336e33b2a248 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,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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 4689a09cc55a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/FieldBuilder.java +++ /dev/null @@ -1,466 +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.LexicalNormalizerName; -import com.azure.search.documents.indexes.models.PermissionFilter; -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; - String permissionFilter = null; - boolean sensitivityLabel; - boolean stored; - boolean searchable = searchableField != null; - String analyzerName = null; - String searchAnalyzerName = null; - String indexAnalyzerName = null; - String[] synonymMapNames = null; - String normalizerName = 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(); - normalizerName = simpleField.normalizerName(); - permissionFilter = simpleField.permissionFilter(); - sensitivityLabel = simpleField.isSensitivityLabel(); - } else { - key = searchableField.isKey(); - hidden = searchableField.isHidden(); - stored = searchableField.isStored(); - filterable = searchableField.isFilterable(); - sortable = searchableField.isSortable(); - facetable = searchableField.isFacetable(); - permissionFilter = searchableField.permissionFilter(); - sensitivityLabel = searchableField.isSensitivityLabel(); - analyzerName = searchableField.analyzerName(); - searchAnalyzerName = searchableField.searchAnalyzerName(); - indexAnalyzerName = searchableField.indexAnalyzerName(); - synonymMapNames = searchableField.synonymMapNames(); - normalizerName = searchableField.normalizerName(); - 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 hasNormalizerName = !CoreUtils.isNullOrEmpty(normalizerName); - 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. "); - } - - // Any field is allowed to have a normalizer, but it must be either a STRING or Collection(STRING) and have one - // of filterable, sortable, or facetable set to true. - if (hasNormalizerName && (!isStringOrCollectionString || !(filterable || sortable || facetable))) { - errorMessage.append("A field with a normalizer name can only be used on string properties and must have ") - .append("one of filterable, sortable, or facetable set to true. "); - } - - 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 (hasNormalizerName) { - searchField.setNormalizerName(LexicalNormalizerName.fromString(normalizerName)); - } - - if (hasVectorEncodingFormat) { - searchField.setVectorEncodingFormat(VectorEncodingFormat.fromString(vectorEncodingFormat)); - } - - if (!CoreUtils.isNullOrEmpty(permissionFilter)) { - searchField.setPermissionFilter(PermissionFilter.fromString(permissionFilter)); - } - - searchField.setSensitivityLabel(sensitivityLabel); - - 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 5115bef5ae6a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/MappingUtils.java +++ /dev/null @@ -1,253 +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; - -public class MappingUtils { - - public static PagedResponse - mapPagedDataSources(Response response) { - return pagedResponse(response, response.getValue().getDataSources()); - } - - public static PagedResponse mapPagedDataSourceNames(Response response) { - return pagedResponse(response, - mapToNames(response.getValue().getDataSources(), SearchIndexerDataSourceConnection::getName)); - } - - public static PagedResponse mapPagedSearchIndexNames(PagedResponse response) { - return new PagedResponseBase(response.getRequest(), response.getStatusCode(), - response.getHeaders(), mapToNames(response.getValue(), SearchIndex::getName), - response.getContinuationToken(), null); - } - - public static PagedResponse mapPagedSearchIndexers(Response response) { - return pagedResponse(response, response.getValue().getIndexers()); - } - - public static PagedResponse mapPagedSearchIndexerNames(Response response) { - return pagedResponse(response, mapToNames(response.getValue().getIndexers(), SearchIndexer::getName)); - } - - public static PagedResponse mapPagedSkillsets(Response response) { - return pagedResponse(response, response.getValue().getSkillsets()); - } - - public static PagedResponse mapPagedSkillsetNames(Response response) { - return pagedResponse(response, mapToNames(response.getValue().getSkillsets(), SearchIndexerSkillset::getName)); - } - - public static PagedResponse mapPagedSynonymMaps(Response response) { - return pagedResponse(response, response.getValue().getSynonymMaps()); - } - - public static PagedResponse mapPagedSynonymMapNames(Response response) { - return pagedResponse(response, mapToNames(response.getValue().getSynonymMaps(), SynonymMap::getName)); - } - - public static PagedResponse mapPagedTokenInfos(Response response) { - return pagedResponse(response, response.getValue().getTokens()); - } - - 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)); - } - - private static PagedResponse pagedResponse(Response response, List values) { - return new PagedResponseBase(response.getRequest(), response.getStatusCode(), - response.getHeaders(), values, null, null); - } - - private static List mapToNames(List values, Function mapper) { - return values.stream().map(mapper).collect(() -> new ArrayList<>(values.size()), List::add, List::addAll); - } -} 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 c99d29f4e2a9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/implementation/util/SemanticSearchResultsAccessHelper.java +++ /dev/null @@ -1,48 +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.QueryAnswerResult; -import com.azure.search.documents.models.SemanticErrorReason; -import com.azure.search.documents.models.SemanticQueryRewritesResultType; -import com.azure.search.documents.models.SemanticSearchResults; -import com.azure.search.documents.models.SemanticSearchResultsType; - -import java.util.List; - -/** - * Helper class to access internals of {@link SemanticSearchResults}. - */ -public final class SemanticSearchResultsAccessHelper { - private SemanticSearchResultsAccessHelper() { - } - - private static SemanticSearchResultsAccessor accessor; - - public interface SemanticSearchResultsAccessor { - SemanticSearchResults create(List queryAnswers, SemanticErrorReason semanticErrorReason, - SemanticSearchResultsType semanticSearchResultsType, - SemanticQueryRewritesResultType semanticQueryRewritesResultType); - } - - public static void setAccessor(final SemanticSearchResultsAccessor newAccessor) { - accessor = newAccessor; - } - - public static SemanticSearchResults create(List queryAnswers, - SemanticErrorReason semanticErrorReason, SemanticSearchResultsType semanticSearchResultsType, - SemanticQueryRewritesResultType semanticQueryRewritesResultType) { - 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(queryAnswers, semanticErrorReason, semanticSearchResultsType, - semanticQueryRewritesResultType); - } -} 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/SearchableField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/BasicField.java similarity index 70% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchableField.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/BasicField.java index 683333d279db..afda163f8935 100644 --- 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/BasicField.java @@ -3,10 +3,10 @@ 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.LexicalNormalizerName; import com.azure.search.documents.indexes.models.SearchField; +import com.azure.search.documents.indexes.models.SearchIndex; import com.azure.search.documents.indexes.models.SynonymMap; import com.azure.search.documents.indexes.models.VectorEncodingFormat; @@ -16,68 +16,100 @@ 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}. + * Annotation used to create {@link SearchField SearchFields} using {@link SearchIndexClient#buildSearchFields(Class)} + * or {@link SearchIndexAsyncClient#buildSearchFields(Class)}. + *

+ * Only fields or methods annotated with this annotation or {@link ComplexField} will be used to create + * {@link SearchField SearchFields}. */ @Target({ ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) -public @interface SearchableField { +public @interface BasicField { + /** + * The {@link SearchField#getName()} used in the {@link SearchIndex}. + * + * @return The name of the field. + */ + String name(); + /** * 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; + BooleanHelper isKey() default BooleanHelper.NULL; /** * Indicates if the field or method should generate as a hidden {@link SearchField field}. + *

+ * When building fields, unless {@link BooleanHelper#NULL} is set, this must have the opposite value of + * {@link #isRetrievable()}. * * @return A flag indicating if the field or method should generate as a hidden {@link SearchField field}. + * @deprecated Use {@link #isRetrievable()} instead and flip the boolean value. */ - boolean isHidden() default false; + @Deprecated + BooleanHelper isHidden() default BooleanHelper.NULL; /** - * Indicates if the field or method should generate as a facetable {@link SearchField field}. + * Indicates if the field or method should generate as a retrievable {@link SearchField field}. + *

+ * When building fields, unless {@link BooleanHelper#NULL} is set, this must have the opposite value of + * {@link #isHidden()}. * - * @return A flag indicating 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 retrievable {@link SearchField field}. */ - boolean isFacetable() default false; + BooleanHelper isRetrievable() default BooleanHelper.NULL; /** - * Indicates if the field or method should be used as a permission filter {@link SearchField field}. + * 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 filterable {@link SearchField field}. + * @return A flag indicating if the field or method should generate as a stored {@link SearchField field}. */ - String permissionFilter() default ""; + BooleanHelper isStored() default BooleanHelper.NULL; /** - * Indicates if the field or method should be used for sensitivity label filtering. This enables document-level - * filtering based on Microsoft Purview sensitivity labels. + * Indicates whether the field can be searched against. * - * @return A flag indicating if the field or method should generate as a sensitivity label {@link SearchField field}. + * @return Indicates whether the field can be searched against. */ - boolean isSensitivityLabel() default false; + BooleanHelper isSearchable() default BooleanHelper.NULL; + + /** + * 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}. + */ + BooleanHelper isFilterable() default BooleanHelper.NULL; /** * 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; + BooleanHelper isSortable() default BooleanHelper.NULL; /** - * Indicates if whether the field will be persisted separately on disk to be returned in a search result. + * 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 stored {@link SearchField field}. + * @return A flag indicating if the field or method should generate as a facetable {@link SearchField field}. */ - boolean isStored() default true; + BooleanHelper isFacetable() default BooleanHelper.NULL; /** - * Indicates if the field or method should generate as a filterable {@link SearchField field}. + * Indicates if the field or method should be used as a permission filter {@link SearchField field}. * * @return A flag indicating if the field or method should generate as a filterable {@link SearchField field}. */ - boolean isFilterable() default false; + String permissionFilter() default ""; + + /** + * Indicates if the field or method should be used for sensitivity label filtering. This enables document-level + * filtering based on Microsoft Purview sensitivity labels. + * + * @return A flag indicating if the field or method should generate as a sensitivity label {@link SearchField field}. + */ + BooleanHelper isSensitivityLabel() default BooleanHelper.NULL; /** * A {@link LexicalAnalyzerName} to associate as the search and index analyzer for the {@link SearchField field}. @@ -111,18 +143,6 @@ */ String normalizerName() 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. *

@@ -150,4 +170,37 @@ * @return The {@link VectorEncodingFormat} that will be associated with the {@link SearchField field}. */ String vectorEncodingFormat() 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 { }; + + /** + * Enum helper for boolean values to allow for nullness. + */ + enum BooleanHelper { + /** + * Equivalent to {@code Boolean b = null}, used when the Azure AI Search default for the field type should be + * used. + */ + NULL, + + /** + * Equivalent to {@code Boolean b = false}. + */ + FALSE, + + /** + * Equivalent to {@code Boolean b = true}. + */ + TRUE + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/ComplexField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/ComplexField.java new file mode 100644 index 000000000000..1c69d1a1f4af --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/ComplexField.java @@ -0,0 +1,30 @@ +// 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 com.azure.search.documents.indexes.models.SearchFieldDataType; +import com.azure.search.documents.indexes.models.SearchIndex; + +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)} to turn the field or method into a + * {@link SearchFieldDataType#COMPLEX complex} {@link SearchField field}. + *

+ * Only fields or methods annotated with this annotation or {@link BasicField} will be used to create + * {@link SearchField SearchFields}. + */ +@Target({ ElementType.FIELD, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +public @interface ComplexField { + /** + * The {@link SearchField#getName()} used in the {@link SearchIndex}. + * + * @return The name of the field. + */ + String name(); +} 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 index 5b09d0db6316..1908d80d2693 100644 --- 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 @@ -1,1908 +1,4405 @@ // 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.indexes; +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.HttpPipeline; 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.Context; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.models.GeoPoint; +import com.azure.core.util.BinaryData; 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.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListSynonymMapsResult; +import com.azure.search.documents.implementation.FieldBuilder; +import com.azure.search.documents.implementation.SearchIndexClientImpl; +import com.azure.search.documents.indexes.models.AnalyzeResult; 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.GetIndexStatisticsResult; import com.azure.search.documents.indexes.models.IndexStatisticsSummary; import com.azure.search.documents.indexes.models.KnowledgeBase; import com.azure.search.documents.indexes.models.KnowledgeSource; +import com.azure.search.documents.indexes.models.ListSynonymMapsResult; import com.azure.search.documents.indexes.models.SearchAlias; 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.SynonymMap; +import com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatus; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Date; 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; +import java.util.stream.Collectors; /** - * 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 of 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 + * Initializes a new instance of the asynchronous SearchIndexClient type. */ @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; + @Generated + private final SearchIndexClientImpl serviceClient; /** - * The endpoint for the Azure AI Search service. + * Initializes an instance of SearchIndexAsyncClient class. + * + * @param serviceClient the service client implementation. */ - private final String endpoint; + @Generated + SearchIndexAsyncClient(SearchIndexClientImpl serviceClient) { + this.serviceClient = serviceClient; + } /** - * The underlying AutoRest client used to interact with the Search service + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. + * + * @return the pipeline. */ - private final SearchServiceClientImpl restClient; - - private final JsonSerializer serializer; + HttpPipeline getHttpPipeline() { + return serviceClient.getHttpPipeline(); + } /** - * The pipeline that powers this client. + * Gets the endpoint used to communicate with the Azure AI Search service. + * + * @return The endpoint. */ - 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()); + public String getEndpoint() { + return serviceClient.getEndpoint(); } /** - * Gets the {@link HttpPipeline} powering this client. + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. * - * @return the pipeline. + * @return The service version. */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); } /** - * Gets the endpoint for the Azure AI Search service. + * Convenience method to convert a {@link Class Class's} {@link Field Fields} and {@link Method Methods} annotated + * with either {@link BasicField} or {@link ComplexField} into {@link SearchField SearchFields} to help aid the + * creation of a {@link SearchField} which represents the {@link Class}. + *

+ * This helper only inspects {@link Field fields} and {@link Method methods} declared by the model, and uses + * the following rules for creating {@link SearchField SearchFields}: + *

    + *
  • If the field or method is annotated with {@link BasicField} the {@link SearchFieldDataType} inferred by the + * type of the field or return type of the method cannot be {@link SearchFieldDataType#COMPLEX}. It may be a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} though.
  • + *
  • If the field or method is annotated with {@link ComplexField} the {@link SearchFieldDataType} inferred by the + * type of the field or return type of the method must be {@link SearchFieldDataType#COMPLEX}. It may be a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} of {@link SearchFieldDataType#COMPLEX}.
  • + *
  • If the field or method isn't annotated with either {@link BasicField} or {@link ComplexField} it will be + * ignored.
  • + *
+ *

+ * If the type of the field or return type of the method is an array or {@link Iterable} it will be considered a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} type. Nested + * {@link SearchFieldDataType#collection(SearchFieldDataType)} aren't allowed and will throw an exception, ex. + * {@code String[][]}, {@code List>}, {@code List}, {@code List[]}, etc. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Conversion of Java type to {@link SearchFieldDataType}
Java type{@link SearchFieldDataType}
{@code byte}{@link SearchFieldDataType#SBYTE}
{@link Byte}{@link SearchFieldDataType#SBYTE}
{@code boolean}{@link SearchFieldDataType#BOOLEAN}
{@link Boolean}{@link SearchFieldDataType#BOOLEAN}
{@code short}{@link SearchFieldDataType#INT16}
{@link Short}{@link SearchFieldDataType#INT16}
{@code int}{@link SearchFieldDataType#INT32}
{@link Integer}{@link SearchFieldDataType#INT32}
{@code long}{@link SearchFieldDataType#INT64}
{@link Long}{@link SearchFieldDataType#INT64}
{@code float}{@link SearchFieldDataType#SINGLE}
{@link Float}{@link SearchFieldDataType#SINGLE}
{@code double}{@link SearchFieldDataType#DOUBLE}
{@link Double}{@link SearchFieldDataType#DOUBLE}
{@code char}{@link SearchFieldDataType#STRING}
{@link Character}{@link SearchFieldDataType#STRING}
{@link CharSequence}{@link SearchFieldDataType#STRING}
{@link String}{@link SearchFieldDataType#STRING}
{@link Date}{@link SearchFieldDataType#DATE_TIME_OFFSET}
{@link OffsetDateTime}{@link SearchFieldDataType#DATE_TIME_OFFSET}
{@link GeoPoint}{@link SearchFieldDataType#GEOGRAPHY_POINT}
Any other typeAttempted to be consumed as {@link SearchFieldDataType#COMPLEX}
+ *

+ * {@link SearchFieldDataType#HALF} and {@link SearchFieldDataType#BYTE} aren't supported by {@link Field} given there + * isn't a built-in Java type that represents them. + *

+ * When generating {@link SearchField SearchFields} there is a maximum class depth limit of {@code 1000} before an + * exception will be thrown. + *

+ * This helper method performs a few basic validation on the created {@link SearchField SearchFields}, they are the + * following: + *

    + *
  • If {@link BasicField#isHidden()} and {@link BasicField#isRetrievable()} must have different + * {@link BasicField.BooleanHelper} values or both be set to {@link BasicField.BooleanHelper#NULL}.
  • + *
  • If {@link BasicField#isSearchable()} is true, then the inferred {@link SearchFieldDataType} must be one + * of {@link SearchFieldDataType#STRING}, {@link SearchFieldDataType#collection(SearchFieldDataType)} of + * {@link SearchFieldDataType#STRING}, or {@link SearchFieldDataType#collection(SearchFieldDataType)} + * of {@link SearchFieldDataType#SINGLE}.
  • + *
  • If {@link BasicField#analyzerName()} is set, both {@link BasicField#searchAnalyzerName()} and + * {@link BasicField#indexAnalyzerName()} must be empty.
  • + *
  • If {@link BasicField#searchAnalyzerName()} is set then {@link BasicField#indexAnalyzerName()} must be + * set and vice versa.
  • + *
  • If {@link BasicField#normalizerName()} is set the inferred {@link SearchFieldDataType} must be either + * {@link SearchFieldDataType#STRING} or {@link SearchFieldDataType#collection(SearchFieldDataType)} of + * {@link SearchFieldDataType#STRING} and have one or more of {@link BasicField#isFacetable()} , + * {@link BasicField#isFilterable()}, or {@link BasicField#isSortable()} set to true.
  • + *
  • If one of {@link BasicField#vectorSearchDimensions()} or {@link BasicField#vectorSearchProfileName()} is + * set the other must be set as well.
  • + *
* - * @return the endpoint value. + * @param model The model {@link Class} that will have {@link SearchField SearchFields} generated from its + * structure. + * @return A list {@link SearchField SearchFields} which represent the model {@link Class}. + * @throws IllegalStateException If fields or methods are annotated with an improper {@link BasicField} or + * {@link ComplexField} annotation, the model exceeds the nesting limit, or {@link SearchField} validation fails. */ - public String getEndpoint() { - return this.endpoint; + public static List buildSearchFields(Class model) { + return FieldBuilder.build(model); } /** - * Initializes a new {@link SearchAsyncClient} using the given Index name and the same configuration as the - * SearchServiceAsyncClient. + * Initializes a new {@link SearchAsyncClient} using the given index name and the same configuration as the + * SearchIndexAsyncClient. * - * @param indexName the name of the Index for the client - * @return a {@link SearchAsyncClient} created from the service client configuration + * @param indexName the name of the index for the client + * @return a {@link SearchAsyncClient} created from the SearchIndexAsyncClient 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); + return new SearchClientBuilder().indexName(indexName) + .endpoint(serviceClient.getEndpoint()) + .serviceVersion(serviceClient.getServiceVersion()) + .pipeline(serviceClient.getHttpPipeline()) + .buildAsyncClient(); } /** - * Creates a new Azure AI Search index. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Create search index named "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 index definition of the index to create. - * @return the created Index. + * @param name 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 createIndex(SearchIndex index) { - return createIndexWithResponse(index).map(Response::getValue); + Mono> createOrUpdateSynonymMapWithResponse(String name, BinaryData synonymMap, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateSynonymMapWithResponseAsync(name, synonymMap, requestOptions); } /** - * Creates a new Azure AI Search index. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Create search index named "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 index definition of the index to create - * @return a response containing the created Index. + * @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> createIndexWithResponse(SearchIndex index) { - return withContext(context -> createIndexWithResponse(index, context)); + public Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, + RequestOptions requestOptions) { + return this.serviceClient + .createOrUpdateSynonymMapWithResponseAsync(synonymMap.getName(), BinaryData.fromObject(synonymMap), + requestOptions) + .map(response -> new SimpleResponse<>(response, response.getValue().toObject(SynonymMap.class))); } - 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); - } + /** + * 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 name 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> deleteSynonymMapWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteSynonymMapWithResponseAsync(name, requestOptions); } /** - * Retrieves an index definition from the Azure AI Search. + * Retrieves a synonym map definition. + *

Response Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Get search index with name "searchIndex".

+ * @param name 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> getSynonymMapWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getSynonymMapWithResponseAsync(name, requestOptions); + } + + /** + * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             format: String (Required)
+     *             synonyms (Required): [
+     *                 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 indexName The name of the index to retrieve - * @return 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 from a List SynonymMaps request along with {@link Response} on successful completion of + * {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getIndex(String indexName) { - return getIndexWithResponse(indexName).map(Response::getValue); + Mono> getSynonymMapsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getSynonymMapsWithResponseAsync(requestOptions); } /** - * Retrieves an index definition from the Azure AI Search. + * Creates a new synonym map. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Get search index with "searchIndex.

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 indexName the name of the index to retrieve - * @return a response containing the Index. + * @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> 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); - } + public Mono> createSynonymMapWithResponse(BinaryData synonymMap, + RequestOptions requestOptions) { + return this.serviceClient.createSynonymMapWithResponseAsync(synonymMap, requestOptions); } /** - * Returns statistics for the given index, including a document count and storage usage. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
* - *

Get search index "searchIndex" statistics.

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param indexName the name of the index for which to retrieve statistics - * @return the index statistics result. + * @param name 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 getIndexStatistics(String indexName) { - return getIndexStatisticsWithResponse(indexName).map(Response::getValue); + Mono> createOrUpdateIndexWithResponse(String name, BinaryData index, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateIndexWithResponseAsync(name, index, requestOptions); } /** - * Returns statistics for the given index, including a document count and storage usage. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
* - *

Get search index "searchIndex" statistics.

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param indexName the name of the index for which to retrieve statistics - * @return a response containing the index statistics result. + * @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> getIndexStatisticsWithResponse(String indexName) { - return withContext(context -> getIndexStatisticsWithResponse(indexName, context)); + public Mono> createOrUpdateIndexWithResponse(SearchIndex index, + RequestOptions requestOptions) { + return this.serviceClient + .createOrUpdateIndexWithResponseAsync(index.getName(), BinaryData.fromObject(index), requestOptions) + .map(response -> new SimpleResponse<>(response, response.getValue().toObject(SearchIndex.class))); } - Mono> getIndexStatisticsWithResponse(String indexName, Context context) { - try { - return restClient.getIndexes() - .getStatisticsWithResponseAsync(indexName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * 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 name 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> deleteIndexWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteIndexWithResponseAsync(name, requestOptions); } /** - * Lists all indexes available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes.

+ * Retrieves an index definition. + *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @return a reactive response emitting the list of indexes. + * @param name 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.COLLECTION) - public PagedFlux listIndexes() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexesWithResponse(null, context))); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getIndexWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexWithResponseAsync(name, requestOptions); } /** - * Lists all indexes names for an Azure AI Search service. + * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - *

Code Sample

- * - *

List all search indexes names.

- * - * *
-     * SEARCH_INDEX_ASYNC_CLIENT.listIndexNames()
-     *     .subscribe(indexName -> System.out.printf("The index name is %s.%n", indexName));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @return a reactive response emitting the list of index names. + * @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 listIndexNames() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexesWithResponse("name", context)) - .map(MappingUtils::mapPagedSearchIndexNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listIndexesWithResponse(String select, Context context) { - return restClient.getIndexes() - .listSinglePageAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); + public PagedFlux listIndexes(RequestOptions requestOptions) { + return this.serviceClient.listIndexesAsync(requestOptions); } /** - * Creates a new Azure AI Search index or updates an index if it already exists. + * Creates a new search index. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
* - *

Create or update search index named "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param index the definition of the {@link SearchIndex} to create or update. - * @return the index that was created or updated. + * @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 createOrUpdateIndex(SearchIndex index) { - return createOrUpdateIndexWithResponse(index, false, false).map(Response::getValue); + public Mono> createIndexWithResponse(BinaryData index, RequestOptions requestOptions) { + return this.serviceClient.createIndexWithResponseAsync(index, requestOptions); } /** - * Creates a new Azure AI Search index or updates an index if it already exists. - * - *

Code Sample

- * - *

Create or update search index named "searchIndex".

+ * Returns statistics for the given index, including a document count and storage usage. + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
      * 
- * * - * @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); - } + * @param name 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> getIndexStatisticsWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexStatisticsWithResponseAsync(name, requestOptions); } /** - * Deletes an Azure AI Search index and all the documents it contains. + * Shows how an analyzer breaks text into tokens. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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)
+     *     ]
+     * }
+     * }
+     * 
* - *

Delete search index with name "searchIndex".

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEX_ASYNC_CLIENT.deleteIndex("searchIndex")
-     *     .subscribe();
+     * {@code
+     * {
+     *     tokens (Required): [
+     *          (Required){
+     *             token: String (Required)
+     *             startOffset: int (Required)
+     *             endOffset: int (Required)
+     *             position: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @param indexName the name of the index to delete - * @return a response signalling completion. + * @param name 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 deleteIndex(String indexName) { - return deleteIndexWithResponse(indexName, null, null).flatMap(FluxUtil::toMono); + public Mono> analyzeTextWithResponse(String name, BinaryData request, + RequestOptions requestOptions) { + return this.serviceClient.analyzeTextWithResponseAsync(name, request, requestOptions); } /** - * Deletes an Azure AI Search index and all the documents it contains. + * 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 Sample

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

Delete search index with name "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @param name 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> 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); - } + Mono> createOrUpdateAliasWithResponse(String name, BinaryData alias, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateAliasWithResponseAsync(name, alias, requestOptions); } /** - * Shows how an analyzer breaks text into tokens. + * 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 Sample

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

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

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @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.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); - } + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateAliasWithResponse(SearchAlias alias, + RequestOptions requestOptions) { + return this.serviceClient + .createOrUpdateAliasWithResponseAsync(alias.getName(), BinaryData.fromObject(alias), requestOptions) + .map(response -> new SimpleResponse<>(response, response.getValue().toObject(SearchAlias.class))); } - private Mono> analyzeTextWithResponse(String indexName, - AnalyzeTextOptions analyzeTextOptions, Context context) { - return restClient.getIndexes() - .analyzeWithResponseAsync(indexName, AnalyzeRequestConverter.map(analyzeTextOptions), null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mapPagedTokenInfos); + /** + * 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 name 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> deleteAliasWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteAliasWithResponseAsync(name, requestOptions); } /** - * Creates a new Azure AI Search synonym map. + * Retrieves an alias definition. + *

Response Body Schema

* - *

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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMap the definition of the synonym map to create - * @return the created {@link SynonymMap}. + * @param name 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 createSynonymMap(SynonymMap synonymMap) { - return createSynonymMapWithResponse(synonymMap).map(Response::getValue); + public Mono> getAliasWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getAliasWithResponseAsync(name, requestOptions); } /** - * Creates a new Azure AI Search synonym map. - * - *

Code Sample

+ * Lists all aliases available for a search service. + *

Response Body Schema

* - *

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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMap the definition of the {@link SynonymMap} to create - * @return a response containing the created SynonymMap. + * @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.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); - } + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listAliases(RequestOptions requestOptions) { + return this.serviceClient.listAliasesAsync(requestOptions); } /** - * Retrieves a synonym map definition. + * Creates a new search alias. + *

Request Body Schema

* - *

Code Sample

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

Get synonym map with name "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMapName name of the synonym map to retrieve - * @return the {@link SynonymMap} definition + * @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 getSynonymMap(String synonymMapName) { - return getSynonymMapWithResponse(synonymMapName).map(Response::getValue); + public Mono> createAliasWithResponse(BinaryData alias, RequestOptions requestOptions) { + return this.serviceClient.createAliasWithResponseAsync(alias, requestOptions); } /** - * Retrieves a synonym map definition. + * Creates a new knowledge base or updates a knowledge base 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
* - *

Get synonym map with name "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMapName name of the synonym map to retrieve - * @return a response containing the SynonymMap. + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response} on successful completion of + * {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getSynonymMapWithResponse(String synonymMapName) { - return withContext(context -> getSynonymMapWithResponse(synonymMapName, context)); + Mono> createOrUpdateKnowledgeBaseWithResponse(String name, BinaryData knowledgeBase, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateKnowledgeBaseWithResponseAsync(name, knowledgeBase, requestOptions); } - Mono> getSynonymMapWithResponse(String synonymMapName, Context context) { - try { - return restClient.getSynonymMaps() - .getWithResponseAsync(synonymMapName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * Deletes a knowledge base. + *

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 name The name of the knowledge base. + * @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> deleteKnowledgeBaseWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteKnowledgeBaseWithResponseAsync(name, requestOptions); } /** - * Lists all synonym maps available for an Azure AI Search service. - * - *

Code Sample

+ * Retrieves a knowledge base definition. + *

Response Body Schema

* - *

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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @return a reactive response emitting the list of synonym maps. + * @param name The name of the knowledge base. + * @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 knowledge base definition along with {@link Response} on successful completion of + * {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSynonymMaps() { - try { - return new PagedFlux<>(() -> withContext(context -> listSynonymMapsWithResponse(null, context)) - .map(MappingUtils::mapPagedSynonymMaps)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> getKnowledgeBaseWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getKnowledgeBaseWithResponseAsync(name, requestOptions); } /** - * Lists all synonym map names for an Azure AI Search service. + * Lists all knowledge bases available for a search service. + *

Response Body Schema

* - *

Code Sample

- * - *

List all synonym map names.

- * - * *
-     * SEARCH_INDEX_ASYNC_CLIENT.listSynonymMapNames()
-     *     .subscribe(synonymMap -> System.out.printf("The synonymMap name is %s.%n", synonymMap));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @return a reactive response emitting the list of synonym map names. + * @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 result from listing knowledge bases as paginated response with {@link PagedFlux}. */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSynonymMapNames() { - try { - return new PagedFlux<>(() -> withContext(context -> listSynonymMapsWithResponse("name", context)) - .map(MappingUtils::mapPagedSynonymMapNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listSynonymMapsWithResponse(String select, Context context) { - return restClient.getSynonymMaps() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); + public PagedFlux listKnowledgeBases(RequestOptions requestOptions) { + return this.serviceClient.listKnowledgeBasesAsync(requestOptions); } /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. + * Creates a new knowledge base. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
* - *

Create or update synonym map named "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMap the definition of the {@link SynonymMap} to create or update - * @return the synonym map that was created or updated. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response} on successful completion of + * {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateSynonymMap(SynonymMap synonymMap) { - return createOrUpdateSynonymMapWithResponse(synonymMap, false).map(Response::getValue); + public Mono> createKnowledgeBaseWithResponse(BinaryData knowledgeBase, + RequestOptions requestOptions) { + return this.serviceClient.createKnowledgeBaseWithResponseAsync(knowledgeBase, requestOptions); } /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. + * Creates a new knowledge source or updates an knowledge source 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 Sample

+ *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
* - *

Create or update synonym map named "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @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. + * @param name The name of the knowledge source. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of + * {@link Mono}. */ + @Generated @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); - } + Mono> createOrUpdateKnowledgeSourceWithResponse(String name, BinaryData knowledgeSource, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateKnowledgeSourceWithResponseAsync(name, knowledgeSource, requestOptions); } /** - * 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. + * Deletes an existing knowledge source. + *

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 name The name of the knowledge source. + * @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 deleteSynonymMap(String synonymMapName) { - return withContext( - context -> deleteSynonymMapWithResponse(synonymMapName, null, context).flatMap(FluxUtil::toMono)); + public Mono> deleteKnowledgeSourceWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteKnowledgeSourceWithResponseAsync(name, requestOptions); } /** - * Deletes an Azure AI Search synonym map. - * - *

Code Sample

+ * Retrieves a knowledge source definition. + *

Response Body Schema

* - *

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()));
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @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. + * @param name The name of the knowledge source. + * @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 knowledge source definition along with {@link Response} on successful completion of + * {@link Mono}. */ + @Generated @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)); + public Mono> getKnowledgeSourceWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getKnowledgeSourceWithResponseAsync(name, requestOptions); } /** - * 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}. + * Lists all knowledge sources available for a search service. + *

Response Body Schema

* - * @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}. + *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
+ * + * @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 result from listing knowledge sources as paginated response with {@link PagedFlux}. */ - 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); - } + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listKnowledgeSources(RequestOptions requestOptions) { + return this.serviceClient.listKnowledgeSourcesAsync(requestOptions); } /** - * 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 + * Creates a new knowledge source. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
* - *

Get service statistics.

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEX_ASYNC_CLIENT.getServiceStatistics()
-     *     .subscribe(serviceStatistics -> System.out.printf("There are %s search indexes in your service.%n",
-     *         serviceStatistics.getCounters().getIndexCounter()));
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @return the search service statistics result. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of + * {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getServiceStatistics() { - return getServiceStatisticsWithResponse().map(Response::getValue); + public Mono> createKnowledgeSourceWithResponse(BinaryData knowledgeSource, + RequestOptions requestOptions) { + return this.serviceClient.createKnowledgeSourceWithResponseAsync(knowledgeSource, requestOptions); } /** - * Returns service level statistics for a search service, including service counters and limits. - * - *

Code Sample

- * - *

Get service statistics.

+ * Retrieves the status of a knowledge source. + *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     synchronizationStatus: String(creating/active/deleting) (Required)
+     *     synchronizationInterval: String (Optional)
+     *     currentSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     lastSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         endTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     statistics (Optional): {
+     *         totalSynchronization: int (Required)
+     *         averageSynchronizationDuration: String (Required)
+     *         averageItemsProcessedPerSynchronization: int (Required)
+     *     }
+     * }
+     * }
      * 
- * * - * @return the search service statistics result. + * @param name The name of the knowledge source. + * @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 status and synchronization history of a knowledge source along with {@link Response} on + * successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getServiceStatisticsWithResponse() { - return withContext(this::getServiceStatisticsWithResponse); + public Mono> getKnowledgeSourceStatusWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getKnowledgeSourceStatusWithResponseAsync(name, requestOptions); } - Mono> getServiceStatisticsWithResponse(Context context) { - try { - return restClient.getServiceStatisticsWithResponseAsync(null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * 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)
+     *         maxCumulativeIndexerRuntimeSeconds: Long (Optional)
+     *     }
+     *     indexersRuntime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     * }
+     * }
+     * 
+ * + * @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> getServiceStatisticsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getServiceStatisticsWithResponseAsync(requestOptions); } /** * Retrieves a summary of statistics for all indexes in the search service. + *

Response Body Schema

* - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
+     * 
+ * + * @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 PagedFlux getIndexStatsSummary() { - return getIndexStatsSummary(Context.NONE); + public PagedFlux listIndexStatsSummary(RequestOptions requestOptions) { + return this.serviceClient.listIndexStatsSummaryAsync(requestOptions); } - PagedFlux getIndexStatsSummary(Context context) { - try { - return restClient.getIndexStatsSummaryAsync(null, context); - } catch (RuntimeException ex) { - RuntimeException mappedException = (RuntimeException) MappingUtils.exceptionMapper(ex); - return pagedFluxError(LOGGER, mappedException); + /** + * Creates a new synonym map or updates a synonym map if it already exists. + * + * @param name 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) + Mono createOrUpdateSynonymMap(String name, SynonymMap synonymMap, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateSynonymMapWithResponse + 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 createOrUpdateSynonymMapWithResponse(name, BinaryData.fromObject(synonymMap), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); } /** - * Creates a new Azure AI Search alias. - * - *

Code Sample

- * - *

Create the search alias named "my-alias".

+ * Creates a new synonym map or updates a synonym map if it already exists. * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.createAlias(new SearchAlias("my-alias", Collections.singletonList("index-to-alias")))
-     *     .subscribe(searchAlias -> System.out.printf("Created alias '%s' that aliases index '%s'.",
-     *         searchAlias.getName(), searchAlias.getIndexes().get(0)));
-     * 
- * - * - * @param alias definition of the alias to create. - * @return the created alias. + * @param name 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}. */ - public Mono createAlias(SearchAlias alias) { - return createAliasWithResponse(alias).flatMap(FluxUtil::toMono); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono createOrUpdateSynonymMap(String name, SynonymMap synonymMap) { + // Generated convenience method for createOrUpdateSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateSynonymMapWithResponse(name, BinaryData.fromObject(synonymMap), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); } /** - * Creates a new Azure AI Search alias. - * - *

Code Sample

+ * Creates a new synonym map or updates a synonym map if it already exists. * - *

Create the search alias named "my-alias".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.createAliasWithResponse(new SearchAlias("my-alias",
-     *         Collections.singletonList("index-to-alias")))
-     *     .subscribe(response ->
-     *         System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.",
-     *             response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)));
-     * 
- * - * - * @param alias definition of the alias to create. - * @return the created alias. + * @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}. */ - public Mono> createAliasWithResponse(SearchAlias alias) { - return withContext(context -> createAliasWithResponse(alias, context)); + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateSynonymMap(SynonymMap synonymMap) { + return createOrUpdateSynonymMap(synonymMap.getName(), synonymMap); } - Mono> createAliasWithResponse(SearchAlias alias, Context context) { - try { - return restClient.getAliases().createWithResponseAsync(alias, null, context); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * Deletes a synonym map. + * + * @param name 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 deleteSynonymMap(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteSynonymMapWithResponse + 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 deleteSynonymMapWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Creates or updates an Azure AI Search alias. - * - *

Code Sample

- * - *

Create then update the search alias named "my-alias".

+ * Deletes a synonym map. * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAlias(
-     *         new SearchAlias("my-alias", Collections.singletonList("index-to-alias")))
-     *     .flatMap(searchAlias -> {
-     *         System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(),
-     *             searchAlias.getIndexes().get(0));
-     *
-     *         return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAlias(new SearchAlias(searchAlias.getName(),
-     *             Collections.singletonList("new-index-to-alias")));
-     *     }).subscribe(searchAlias -> System.out.printf("Updated alias '%s' to aliases index '%s'.",
-     *         searchAlias.getName(), searchAlias.getIndexes().get(0)));
-     * 
- * - * - * @param alias definition of the alias to create or update. - * @return the created or updated alias. + * @param name 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. */ - public Mono createOrUpdateAlias(SearchAlias alias) { - return createOrUpdateAliasWithResponse(alias, false).flatMap(FluxUtil::toMono); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteSynonymMap(String name) { + // Generated convenience method for deleteSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteSynonymMapWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Creates or updates an Azure AI Search alias. - * - *

Code Sample

- * - *

Create then update the search alias named "my-alias".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAliasWithResponse(
-     *         new SearchAlias("my-alias", Collections.singletonList("index-to-alias")), false)
-     *     .flatMap(response -> {
-     *         System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.",
-     *             response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0));
-     *
-     *         return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAliasWithResponse(
-     *             new SearchAlias(response.getValue().getName(), Collections.singletonList("new-index-to-alias"))
-     *                 .setETag(response.getValue().getETag()), true);
-     *     }).subscribe(response ->
-     *         System.out.printf("Response status code %d. Updated alias '%s' that aliases index '%s'.",
-     *             response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)));
-     * 
- * + * Retrieves a synonym map definition. * - * @param alias definition of the alias to create or update. - * @param onlyIfUnchanged only update the alias if the eTag matches the alias on the service - * @return the created or updated alias. + * @param name 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}. */ - public Mono> createOrUpdateAliasWithResponse(SearchAlias alias, boolean onlyIfUnchanged) { - if (alias == null) { - return monoError(LOGGER, new NullPointerException("'alias' cannot be null.")); - } - - return withContext( - context -> createOrUpdateAliasWithResponse(alias, onlyIfUnchanged ? alias.getETag() : null, context)); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getSynonymMap(String name) { + // Generated convenience method for getSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSynonymMapWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); } - Mono> createOrUpdateAliasWithResponse(SearchAlias alias, String eTag, Context context) { - try { - return restClient.getAliases() - .createOrUpdateWithResponseAsync(alias.getName(), alias, eTag, null, null, context); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * 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) + Mono getSynonymMaps(List select) { + // Generated convenience method for getSynonymMapsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); } + return getSynonymMapsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSynonymMapsResult.class)); } /** - * Gets the Azure AI Search alias. - * - *

Code Sample

- * - *

Get the search alias named "my-alias".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getAlias("my-alias")
-     *     .subscribe(searchAlias -> System.out.printf("Retrieved alias '%s' that aliases index '%s'.",
-     *         searchAlias.getName(), searchAlias.getIndexes().get(0)));
-     * 
- * + * Lists all synonym maps available for a search service. * - * @param aliasName name of the alias to get. - * @return the retrieved alias. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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}. */ - public Mono getAlias(String aliasName) { - return getAliasWithResponse(aliasName).flatMap(FluxUtil::toMono); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono getSynonymMaps() { + // Generated convenience method for getSynonymMapsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSynonymMapsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSynonymMapsResult.class)); } /** - * Gets the Azure AI Search alias. - * - *

Code Sample

+ * Lists all synonym maps available for a search service. * - *

Get the search alias named "my-alias".

+ * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono listSynonymMaps() { + return getSynonymMaps(); + } + + /** + * Lists the names of all synonym maps available for a search service. * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getAliasWithResponse("my-alias")
-     *     .subscribe(response ->
-     *         System.out.printf("Response status code %d. Retrieved alias '%s' that aliases index '%s'.",
-     *             response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)));
-     * 
- * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listSynonymMapNames() { + return getSynonymMaps(Collections.singletonList("name")) + .map(result -> result.getSynonymMaps().stream().map(SynonymMap::getName).collect(Collectors.toList())); + } + + /** + * Creates a new synonym map. * - * @param aliasName name of the alias to get. - * @return the retrieved alias. + * @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}. */ - public Mono> getAliasWithResponse(String aliasName) { - return withContext(context -> getAliasWithResponse(aliasName, context)); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createSynonymMap(SynonymMap synonymMap) { + // Generated convenience method for createSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createSynonymMapWithResponse(BinaryData.fromObject(synonymMap), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SynonymMap.class)); } - Mono> getAliasWithResponse(String aliasName, Context context) { - try { - return restClient.getAliases().getWithResponseAsync(aliasName, null, context); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * Creates a new search index or updates an index if it already exists. + * + * @param name 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) + Mono createOrUpdateIndex(String name, SearchIndex index, Boolean allowIndexDowntime, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateIndexWithResponse + 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 createOrUpdateIndexWithResponse(name, BinaryData.fromObject(index), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); } /** - * Deletes the Azure AI Search alias. - * - *

Code Sample

+ * Creates a new search index or updates an index if it already exists. * - *

Delete the search alias named "my-alias".

- * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.deleteAlias("my-alias")
-     *     .subscribe(ignored -> System.out.println("Deleted alias 'my-alias'."));
-     * 
- * + * @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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono createOrUpdateIndex(SearchIndex index) { + return createOrUpdateIndex(index.getName(), index); + } + + /** + * Creates a new search index or updates an index if it already exists. * - * @param aliasName name of the alias to delete. - * @return a reactive response indicating deletion has completed. + * @param name 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}. */ - public Mono deleteAlias(String aliasName) { - return withContext(context -> deleteAliasWithResponse(aliasName, null, context)).flatMap(FluxUtil::toMono); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono createOrUpdateIndex(String name, SearchIndex index) { + // Generated convenience method for createOrUpdateIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateIndexWithResponse(name, BinaryData.fromObject(index), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); } /** - * Deletes the Azure AI Search alias. + * 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. * - *

Code Sample

+ * @param name 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 deleteIndex(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteIndexWithResponse + 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 deleteIndexWithResponse(name, 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. * - *

Get the search alias named "my-alias".

+ * @param name 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 deleteIndex(String name) { + // Generated convenience method for deleteIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteIndexWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); + } + + /** + * Retrieves an index definition. * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.getAlias("my-alias")
-     *     .flatMap(searchAlias -> SEARCH_INDEX_ASYNC_CLIENT.deleteAliasWithResponse(searchAlias, true))
-     *     .subscribe(response -> System.out.printf("Response status code %d. Deleted alias 'my-alias'.",
-     *         response.getStatusCode()));
-     * 
- * + * @param name 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 getIndex(String name) { + // Generated convenience method for getIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); + } + + /** + * Lists all indexes available for a search service. * - * @param alias the alias to delete. - * @param onlyIfUnchanged only delete the alias if the eTag matches the alias on the service - * @return a reactive response indicating deletion has completed. + * @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}. */ - public Mono> deleteAliasWithResponse(SearchAlias alias, boolean onlyIfUnchanged) { - if (alias == null) { - return monoError(LOGGER, new NullPointerException("'alias' cannot be null.")); + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listIndexes(List select) { + // Generated convenience method for listIndexes + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); } + PagedFlux pagedFluxResponse = listIndexes(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)); + }); + } - return withContext( - context -> deleteAliasWithResponse(alias.getName(), onlyIfUnchanged ? alias.getETag() : null, context)); + /** + * 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 listIndexes() { + // Generated convenience method for listIndexes + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listIndexes(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)); + }); } - Mono> deleteAliasWithResponse(String aliasName, String eTag, Context context) { - try { - return restClient.getAliases().deleteWithResponseAsync(aliasName, eTag, null, null, context); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * Lists the names of 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}. + */ + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listIndexNames() { + RequestOptions requestOptions = new RequestOptions().addQueryParam("$select", "name"); + PagedFlux pagedFluxResponse = listIndexes(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).getName()) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); } /** - * Lists all aliases in the Azure AI Search service. + * Creates a new search index. * - *

Code Sample

+ * @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 createIndex(SearchIndex index) { + // Generated convenience method for createIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createIndexWithResponse(BinaryData.fromObject(index), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndex.class)); + } + + /** + * Returns statistics for the given index, including a document count and storage usage. * - *

List aliases

+ * @param name 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 getIndexStatistics(String name) { + // Generated convenience method for getIndexStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexStatisticsWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(GetIndexStatisticsResult.class)); + } + + /** + * Shows how an analyzer breaks text into tokens. * - * - *
-     * SEARCH_INDEX_ASYNC_CLIENT.listAliases()
-     *     .doOnNext(searchAlias -> System.out.printf("Listed alias '%s' that aliases index '%s'.",
-     *         searchAlias.getName(), searchAlias.getIndexes().get(0)))
-     *     .subscribe();
-     * 
- * + * @param name 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 analyzeText(String name, AnalyzeTextOptions request) { + // Generated convenience method for analyzeTextWithResponse + RequestOptions requestOptions = new RequestOptions(); + return analyzeTextWithResponse(name, BinaryData.fromObject(request), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(AnalyzeResult.class)); + } + + /** + * Creates a new search alias or updates an alias if it already exists. * - * @return a list of aliases in the service. + * @param name 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}. */ - public PagedFlux listAliases() { - try { - return new PagedFlux<>( - () -> withContext(context -> restClient.getAliases().listSinglePageAsync(null, context))); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono createOrUpdateAlias(String name, SearchAlias alias, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateAliasWithResponse + 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 createOrUpdateAliasWithResponse(name, BinaryData.fromObject(alias), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); } /** - * Creates a new agent. + * Creates a new search alias or updates an alias if it already exists. * - * @param knowledgeBase The definition of the agent to create. + * @param alias The definition of the alias to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body on successful completion of {@link Mono}. + * @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 createKnowledgeBase(KnowledgeBase knowledgeBase) { - return createKnowledgeBaseWithResponse(knowledgeBase).map(Response::getValue); + public Mono createOrUpdateAlias(SearchAlias alias) { + return createOrUpdateAlias(alias.getName(), alias); } /** - * Creates a new agent. + * Creates a new search alias or updates an alias if it already exists. * - * @param knowledgeBase The definition of the agent to create. + * @param name 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 ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body along with {@link Response} on successful completion of {@link Mono}. + * @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> createKnowledgeBaseWithResponse(KnowledgeBase knowledgeBase) { - return withContext(context -> createKnowledgeBaseWithResponse(knowledgeBase, context)); + Mono createOrUpdateAlias(String name, SearchAlias alias) { + // Generated convenience method for createOrUpdateAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateAliasWithResponse(name, BinaryData.fromObject(alias), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); } - Mono> createKnowledgeBaseWithResponse(KnowledgeBase knowledgeBase, Context context) { - try { - return restClient.getKnowledgeBases() - .createWithResponseAsync(knowledgeBase, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * 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 name 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 deleteAlias(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteAliasWithResponse + 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 deleteAliasWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Creates a new agent or updates an agent if it already exists. + * 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 knowledgeBase The definition of the agent to create or update. + * @param name The name of the alias. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 the response body on successful completion of {@link Mono}. + * @return A {@link Mono} that completes when a successful response is received. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateKnowledgeBase(KnowledgeBase knowledgeBase) { - return createOrUpdateKnowledgeBaseWithResponse(knowledgeBase, null).map(Response::getValue); + public Mono deleteAlias(String name) { + // Generated convenience method for deleteAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteAliasWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Creates a new agent or updates an agent if it already exists. + * Retrieves an alias definition. * - * @param knowledgeBase The definition of the agent to create or update. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. + * @param name The name of the alias. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body along with {@link Response} on successful completion of {@link Mono}. + * @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> createOrUpdateKnowledgeBaseWithResponse(KnowledgeBase knowledgeBase, - MatchConditions matchConditions) { - return withContext(context -> createOrUpdateKnowledgeBaseWithResponse(knowledgeBase, matchConditions, context)); - } - - Mono> createOrUpdateKnowledgeBaseWithResponse(KnowledgeBase knowledgeBase, - MatchConditions matchConditions, Context context) { - try { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return restClient.getKnowledgeBases() - .createOrUpdateWithResponseAsync(knowledgeBase.getName(), knowledgeBase, ifMatch, ifNoneMatch, null, - context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + public Mono getAlias(String name) { + // Generated convenience method for getAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getAliasWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); } /** - * Retrieves an agent definition. + * Lists all aliases available for a search service. * - * @param knowledgeBaseName The name of the agent to retrieve. - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body on successful completion of {@link Mono}. + * @return response from a List Aliases request as paginated response with {@link PagedFlux}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKnowledgeBase(String knowledgeBaseName) { - return getKnowledgeBaseWithResponse(knowledgeBaseName).map(Response::getValue); + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listAliases() { + // Generated convenience method for listAliases + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listAliases(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)); + }); } /** - * Retrieves an agent definition. + * Creates a new search alias. * - * @param knowledgeBaseName The name of the agent to retrieve. + * @param alias The definition of the alias to create. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body along with {@link Response} on successful completion of {@link Mono}. + * @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> getKnowledgeBaseWithResponse(String knowledgeBaseName) { - return withContext(context -> getKnowledgeBaseWithResponse(knowledgeBaseName, context)); + public Mono createAlias(SearchAlias alias) { + // Generated convenience method for createAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createAliasWithResponse(BinaryData.fromObject(alias), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchAlias.class)); } - Mono> getKnowledgeBaseWithResponse(String knowledgeBaseName, Context context) { - try { - return restClient.getKnowledgeBases() - .getWithResponseAsync(knowledgeBaseName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * Creates a new knowledge base or updates a knowledge base if it already exists. + * + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono createOrUpdateKnowledgeBase(String name, KnowledgeBase knowledgeBase, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateKnowledgeBaseWithResponse + 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 createOrUpdateKnowledgeBaseWithResponse(name, BinaryData.fromObject(knowledgeBase), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeBase.class)); } /** - * Lists all knowledgebases available for a search service. + * Creates a new knowledge base or updates a knowledge base if it already exists. * + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 paginated response with {@link PagedFlux}. + * @return represents a knowledge base definition on successful completion of {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listKnowledgeBases() { - try { - return restClient.getKnowledgeBases().listAsync(null, Context.NONE); - } catch (RuntimeException ex) { - RuntimeException mappedException = (RuntimeException) MappingUtils.exceptionMapper(ex); - return pagedFluxError(LOGGER, mappedException); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono createOrUpdateKnowledgeBase(String name, KnowledgeBase knowledgeBase) { + // Generated convenience method for createOrUpdateKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateKnowledgeBaseWithResponse(name, BinaryData.fromObject(knowledgeBase), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeBase.class)); } /** - * Deletes an existing agent. + * Deletes a knowledge base. * - * @param knowledgeBaseName The name of the agent to delete. + * @param name The name of the knowledge base. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 deleteKnowledgeBase(String knowledgeBaseName) { - return deleteKnowledgeBaseWithResponse(knowledgeBaseName, null).flatMap(FluxUtil::toMono); + public Mono deleteKnowledgeBase(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteKnowledgeBaseWithResponse + 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 deleteKnowledgeBaseWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Deletes an existing agent. + * Deletes a knowledge base. * - * @param knowledgeBaseName The name of the agent to delete. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. + * @param name The name of the knowledge base. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 the {@link Response} on successful completion of {@link Mono}. + * @return A {@link Mono} that completes when a successful response is received. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteKnowledgeBaseWithResponse(String knowledgeBaseName, - MatchConditions matchConditions) { - return withContext(context -> deleteKnowledgeBaseWithResponse(knowledgeBaseName, matchConditions, context)); - } - - Mono> deleteKnowledgeBaseWithResponse(String knowledgeBaseName, MatchConditions matchConditions, - Context context) { - try { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return restClient.getKnowledgeBases() - .deleteWithResponseAsync(knowledgeBaseName, ifMatch, ifNoneMatch, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + public Mono deleteKnowledgeBase(String name) { + // Generated convenience method for deleteKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteKnowledgeBaseWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Creates a new knowledge source. + * Retrieves a knowledge base definition. * - * @param knowledgeSource The definition of the knowledge source to create. + * @param name The name of the knowledge base. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 will produce the created knowledge source. + * @return represents a knowledge base definition on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createKnowledgeSource(KnowledgeSource knowledgeSource) { - return createKnowledgeSourceWithResponse(knowledgeSource).map(Response::getValue); + public Mono getKnowledgeBase(String name) { + // Generated convenience method for getKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getKnowledgeBaseWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeBase.class)); } /** - * Creates a new knowledge source. + * Lists all knowledge bases available for a search service. * - * @param knowledgeSource The definition of the knowledge source to create. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 result from listing knowledge bases as paginated response with {@link PagedFlux}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedFlux listKnowledgeBases() { + // Generated convenience method for listKnowledgeBases + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listKnowledgeBases(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(KnowledgeBase.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); + } + + /** + * Creates a new knowledge base. + * + * @param knowledgeBase The definition of the knowledge base to create. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 will produce a {@link Response} containing the created knowledge source. + * @return represents a knowledge base definition on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource) { - return withContext(context -> createKnowledgeSourceWithResponse(knowledgeSource, context)); + public Mono createKnowledgeBase(KnowledgeBase knowledgeBase) { + // Generated convenience method for createKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createKnowledgeBaseWithResponse(BinaryData.fromObject(knowledgeBase), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeBase.class)); } - Mono> createKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource, - Context context) { - try { - return restClient.getKnowledgeSources() - .createWithResponseAsync(knowledgeSource, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * Creates a new knowledge source or updates an knowledge source if it already exists. + * + * @param name The name of the knowledge source. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono createOrUpdateKnowledgeSource(String name, KnowledgeSource knowledgeSource, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateKnowledgeSourceWithResponse + 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 createOrUpdateKnowledgeSourceWithResponse(name, BinaryData.fromObject(knowledgeSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeSource.class)); } /** - * Creates or updates a knowledge source. + * Creates a new knowledge source or updates an knowledge source if it already exists. * * @param knowledgeSource The definition of the knowledge source to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 will produce the created or updated knowledge source. + * @return represents a knowledge source definition on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createOrUpdateKnowledgeSource(KnowledgeSource knowledgeSource) { - return createOrUpdateKnowledgeSourceWithResponse(knowledgeSource, null).map(Response::getValue); + return createOrUpdateKnowledgeSource(knowledgeSource.getName(), knowledgeSource); } /** - * Creates or updates a knowledge source. + * Creates a new knowledge source or updates an knowledge source if it already exists. * + * @param name The name of the knowledge source. * @param knowledgeSource The definition of the knowledge source to create or update. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 produces a {@link Response} containing the created or updated knowledge source. + * @return represents a knowledge source definition on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource, - MatchConditions matchConditions) { - return withContext( - context -> createOrUpdateKnowledgeSourceWithResponse(knowledgeSource, matchConditions, context)); - } - - Mono> createOrUpdateKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource, - MatchConditions matchConditions, Context context) { - try { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return restClient.getKnowledgeSources() - .createOrUpdateWithResponseAsync(knowledgeSource.getName(), knowledgeSource, ifMatch, ifNoneMatch, null, - context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + Mono createOrUpdateKnowledgeSource(String name, KnowledgeSource knowledgeSource) { + // Generated convenience method for createOrUpdateKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateKnowledgeSourceWithResponse(name, BinaryData.fromObject(knowledgeSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeSource.class)); } /** - * Retrieves a knowledge source. + * Deletes an existing knowledge source. * - * @param sourceName The name of the knowledge source to retrieve. + * @param name The name of the knowledge source. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 will produce the retrieved knowledge source. + * @return A {@link Mono} that completes when a successful response is received. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getKnowledgeSource(String sourceName) { - return getKnowledgeSourceWithResponse(sourceName).map(Response::getValue); + public Mono deleteKnowledgeSource(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteKnowledgeSourceWithResponse + 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 deleteKnowledgeSourceWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Retrieves a knowledge source. + * Deletes an existing knowledge source. * - * @param sourceName The name of the knowledge source to retrieve. + * @param name The name of the knowledge source. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 will produce a {@link Response} containing the retrieved knowledge source. + * @return A {@link Mono} that completes when a successful response is received. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getKnowledgeSourceWithResponse(String sourceName) { - return withContext(context -> getKnowledgeSourceWithResponse(sourceName, context)); + public Mono deleteKnowledgeSource(String name) { + // Generated convenience method for deleteKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteKnowledgeSourceWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } - Mono> getKnowledgeSourceWithResponse(String sourceName, Context context) { - try { - return restClient.getKnowledgeSources() - .getWithResponseAsync(sourceName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * Retrieves a knowledge source definition. + * + * @param name The name of the knowledge source. + * @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 knowledge source definition on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono getKnowledgeSource(String name) { + // Generated convenience method for getKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getKnowledgeSourceWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeSource.class)); } /** * Lists all knowledge sources available for a search service. * - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 PagedFlux} of knowledge source. + * @return result from listing knowledge sources as paginated response with {@link PagedFlux}. */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listKnowledgeSources() { - try { - return restClient.getKnowledgeSources().listAsync(null, Context.NONE); - } catch (RuntimeException ex) { - RuntimeException mappedException = (RuntimeException) MappingUtils.exceptionMapper(ex); - return pagedFluxError(LOGGER, mappedException); - } + // Generated convenience method for listKnowledgeSources + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listKnowledgeSources(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(KnowledgeSource.class)) + .collect(Collectors.toList()), + pagedResponse.getContinuationToken(), null)); + }); } /** - * Deletes an existing knowledge source. + * Creates a new knowledge source. * - * @param sourceName The name of the knowledge source to delete. + * @param knowledgeSource The definition of the knowledge source to create. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 successfully if the knowledge source was deleted. + * @return represents a knowledge source definition on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono deleteKnowledgeSource(String sourceName) { - return deleteKnowledgeSourceWithResponse(sourceName, null).flatMap(FluxUtil::toMono); + public Mono createKnowledgeSource(KnowledgeSource knowledgeSource) { + // Generated convenience method for createKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createKnowledgeSourceWithResponse(BinaryData.fromObject(knowledgeSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeSource.class)); } /** - * Deletes an existing knowledge source. + * Retrieves the status of a knowledge source. * - * @param sourceName The name of the knowledge source to delete. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. + * @param name The name of the knowledge source. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 produces a {@link Response} if the knowledge source was deleted. + * @return represents the status and synchronization history of a knowledge source on successful completion of + * {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteKnowledgeSourceWithResponse(String sourceName, MatchConditions matchConditions) { - return withContext(context -> deleteKnowledgeSourceWithResponse(sourceName, matchConditions, context)); + public Mono getKnowledgeSourceStatus(String name) { + // Generated convenience method for getKnowledgeSourceStatusWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getKnowledgeSourceStatusWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeSourceStatus.class)); } - Mono> deleteKnowledgeSourceWithResponse(String sourceName, MatchConditions matchConditions, - Context context) { - try { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return restClient.getKnowledgeSources() - .deleteWithResponseAsync(sourceName, ifMatch, ifNoneMatch, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * 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}. + */ + @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)); + } + + /** + * 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 PagedFlux listIndexStatsSummary() { + // Generated convenience method for listIndexStatsSummary + RequestOptions requestOptions = new RequestOptions(); + PagedFlux pagedFluxResponse = listIndexStatsSummary(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)); + }); } } 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 index aec7eb983fb7..5cf215ef46bf 100644 --- 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 @@ -1,1904 +1,4471 @@ // 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.indexes; +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.HttpPipeline; import com.azure.core.http.MatchConditions; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.RequestOptions; 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.core.http.rest.SimpleResponse; +import com.azure.core.models.GeoPoint; +import com.azure.core.util.BinaryData; import com.azure.search.documents.SearchClient; +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.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.ErrorResponseException; -import com.azure.search.documents.indexes.implementation.models.ListSynonymMapsResult; +import com.azure.search.documents.implementation.FieldBuilder; +import com.azure.search.documents.implementation.SearchIndexClientImpl; +import com.azure.search.documents.indexes.models.AnalyzeResult; 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.GetIndexStatisticsResult; import com.azure.search.documents.indexes.models.IndexStatisticsSummary; import com.azure.search.documents.indexes.models.KnowledgeBase; import com.azure.search.documents.indexes.models.KnowledgeSource; -import com.azure.search.documents.indexes.models.LexicalAnalyzerName; -import com.azure.search.documents.indexes.models.LexicalTokenizerName; +import com.azure.search.documents.indexes.models.ListSynonymMapsResult; import com.azure.search.documents.indexes.models.SearchAlias; 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.SynonymMap; +import com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatus; import java.lang.reflect.Field; import java.lang.reflect.Method; +import java.time.OffsetDateTime; +import java.util.Collections; +import java.util.Date; import java.util.List; import java.util.Objects; - -import static com.azure.search.documents.indexes.SearchIndexAsyncClient.getSearchClientBuilder; +import java.util.stream.Collectors; /** - * 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 of 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 + * Initializes a new instance of the synchronous SearchIndexClient type. */ @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; + @Generated + private final SearchIndexClientImpl serviceClient; /** - * The endpoint for the Azure AI Search service. + * Initializes an instance of SearchIndexClient class. + * + * @param serviceClient the service client implementation. */ - private final String endpoint; + @Generated + SearchIndexClient(SearchIndexClientImpl serviceClient) { + this.serviceClient = serviceClient; + } /** - * The underlying AutoRest client used to interact with the Search service + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. + * + * @return the pipeline. */ - private final SearchServiceClientImpl restClient; - - private final JsonSerializer serializer; + HttpPipeline getHttpPipeline() { + return serviceClient.getHttpPipeline(); + } /** - * The pipeline that powers this client. + * Gets the endpoint used to communicate with the Azure AI Search service. + * + * @return The endpoint. */ - 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()); + public String getEndpoint() { + return serviceClient.getEndpoint(); } /** - * Gets the {@link HttpPipeline} powering this client. + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. * - * @return the pipeline. + * @return The service version. */ - HttpPipeline getHttpPipeline() { - return this.httpPipeline; + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); } /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. + * Convenience method to convert a {@link Class Class's} {@link Field Fields} and {@link Method Methods} annotated + * with either {@link BasicField} or {@link ComplexField} into {@link SearchField SearchFields} to help aid the + * creation of a {@link SearchField} which represents the {@link Class}. + *

+ * This helper only inspects {@link Field fields} and {@link Method methods} declared by the model, and uses + * the following rules for creating {@link SearchField SearchFields}: + *

    + *
  • If the field or method is annotated with {@link BasicField} the {@link SearchFieldDataType} inferred by the + * type of the field or return type of the method cannot be {@link SearchFieldDataType#COMPLEX}. It may be a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} though.
  • + *
  • If the field or method is annotated with {@link ComplexField} the {@link SearchFieldDataType} inferred by the + * type of the field or return type of the method must be {@link SearchFieldDataType#COMPLEX}. It may be a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} of {@link SearchFieldDataType#COMPLEX}.
  • + *
  • If the field or method isn't annotated with either {@link BasicField} or {@link ComplexField} it will be + * ignored.
  • + *
+ *

+ * If the type of the field or return type of the method is an array or {@link Iterable} it will be considered a + * {@link SearchFieldDataType#collection(SearchFieldDataType)} type. Nested + * {@link SearchFieldDataType#collection(SearchFieldDataType)} aren't allowed and will throw an exception, ex. + * {@code String[][]}, {@code List>}, {@code List}, {@code List[]}, etc. + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Conversion of Java type to {@link SearchFieldDataType}
Java type{@link SearchFieldDataType}
{@code byte}{@link SearchFieldDataType#SBYTE}
{@link Byte}{@link SearchFieldDataType#SBYTE}
{@code boolean}{@link SearchFieldDataType#BOOLEAN}
{@link Boolean}{@link SearchFieldDataType#BOOLEAN}
{@code short}{@link SearchFieldDataType#INT16}
{@link Short}{@link SearchFieldDataType#INT16}
{@code int}{@link SearchFieldDataType#INT32}
{@link Integer}{@link SearchFieldDataType#INT32}
{@code long}{@link SearchFieldDataType#INT64}
{@link Long}{@link SearchFieldDataType#INT64}
{@code float}{@link SearchFieldDataType#SINGLE}
{@link Float}{@link SearchFieldDataType#SINGLE}
{@code double}{@link SearchFieldDataType#DOUBLE}
{@link Double}{@link SearchFieldDataType#DOUBLE}
{@code char}{@link SearchFieldDataType#STRING}
{@link Character}{@link SearchFieldDataType#STRING}
{@link CharSequence}{@link SearchFieldDataType#STRING}
{@link String}{@link SearchFieldDataType#STRING}
{@link Date}{@link SearchFieldDataType#DATE_TIME_OFFSET}
{@link OffsetDateTime}{@link SearchFieldDataType#DATE_TIME_OFFSET}
{@link GeoPoint}{@link SearchFieldDataType#GEOGRAPHY_POINT}
Any other typeAttempted to be consumed as {@link SearchFieldDataType#COMPLEX}
+ *

+ * {@link SearchFieldDataType#HALF} and {@link SearchFieldDataType#BYTE} aren't supported by {@link Field} given there + * isn't a built-in Java type that represents them. + *

+ * When generating {@link SearchField SearchFields} there is a maximum class depth limit of {@code 1000} before an + * exception will be thrown. + *

+ * This helper method performs a few basic validation on the created {@link SearchField SearchFields}, they are the + * following: + *

    + *
  • If {@link BasicField#isHidden()} and {@link BasicField#isRetrievable()} must have different + * {@link BasicField.BooleanHelper} values or both be set to {@link BasicField.BooleanHelper#NULL}.
  • + *
  • If {@link BasicField#isSearchable()} is true, then the inferred {@link SearchFieldDataType} must be one + * of {@link SearchFieldDataType#STRING}, {@link SearchFieldDataType#collection(SearchFieldDataType)} of + * {@link SearchFieldDataType#STRING}, or {@link SearchFieldDataType#collection(SearchFieldDataType)} + * of {@link SearchFieldDataType#SINGLE}.
  • + *
  • If {@link BasicField#analyzerName()} is set, both {@link BasicField#searchAnalyzerName()} and + * {@link BasicField#indexAnalyzerName()} must be empty.
  • + *
  • If {@link BasicField#searchAnalyzerName()} is set then {@link BasicField#indexAnalyzerName()} must be + * set and vice versa.
  • + *
  • If {@link BasicField#normalizerName()} is set the inferred {@link SearchFieldDataType} must be either + * {@link SearchFieldDataType#STRING} or {@link SearchFieldDataType#collection(SearchFieldDataType)} of + * {@link SearchFieldDataType#STRING} and have one or more of {@link BasicField#isFacetable()} , + * {@link BasicField#isFilterable()}, or {@link BasicField#isSortable()} set to true.
  • + *
  • If one of {@link BasicField#vectorSearchDimensions()} or {@link BasicField#vectorSearchProfileName()} is + * set the other must be set as well.
  • + *
+ * + * @param model The model {@link Class} that will have {@link SearchField SearchFields} generated from its + * structure. + * @return A list {@link SearchField SearchFields} which represent the model {@link Class}. + * @throws IllegalStateException If fields or methods are annotated with an improper {@link BasicField} or + * {@link ComplexField} annotation, the model exceeds the nesting limit, or {@link SearchField} validation fails. */ - public String getEndpoint() { - return this.endpoint; + public static List buildSearchFields(Class model) { + return FieldBuilder.build(model); } /** - * Initializes a new {@link SearchClient} using the given Index name and the same configuration as the - * SearchServiceClient. + * Initializes a new {@link SearchClient} using the given index name and the same configuration as the + * SearchIndexClient. * - * @param indexName the name of the Index for the client - * @return a {@link SearchClient} created from the service client configuration + * @param indexName the name of the index for the client + * @return a {@link SearchClient} created from the SearchIndexClient configuration */ public SearchClient getSearchClient(String indexName) { - return getSearchClientBuilder(indexName, endpoint, serviceVersion, httpPipeline, serializer).buildClient(); + return new SearchClientBuilder().indexName(indexName) + .endpoint(serviceClient.getEndpoint()) + .serviceVersion(serviceClient.getServiceVersion()) + .pipeline(serviceClient.getHttpPipeline()) + .buildClient(); } /** - * Creates a new Azure AI Search index + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Create search index named "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 index definition of the index to create - * @return the created Index. + * @param name 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 SearchIndex createIndex(SearchIndex index) { - return createIndexWithResponse(index, Context.NONE).getValue(); + Response createOrUpdateSynonymMapWithResponse(String name, BinaryData synonymMap, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateSynonymMapWithResponse(name, synonymMap, requestOptions); } /** - * Creates a new Azure AI Search index + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Create search index named "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 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. + * @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 createIndexWithResponse(SearchIndex index, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Objects.requireNonNull(index, "'Index' cannot be null"); - return restClient.getIndexes().createWithResponse(index, null, context); - }, LOGGER); + public Response createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, + RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateSynonymMapWithResponse(synonymMap.getName(), + BinaryData.fromObject(synonymMap), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SynonymMap.class)); } /** - * 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. + * 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 name 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 SearchIndex getIndex(String indexName) { - return getIndexWithResponse(indexName, Context.NONE).getValue(); + public Response deleteSynonymMapWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteSynonymMapWithResponse(name, requestOptions); } /** - * Retrieves an index definition from the Azure AI Search. - * - *

Code Sample

- * - *

Get search index with "searchIndex.

+ * Retrieves a synonym map definition. + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 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. + * @param name 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 getIndexWithResponse(String indexName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().getWithResponse(indexName, null, context), LOGGER); + public Response getSynonymMapWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getSynonymMapWithResponse(name, requestOptions); } /** - * Returns statistics for the given index, including a document count and storage usage. - * - *

Code Sample

+ * Lists all synonym maps available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - *

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());
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             format: String (Required)
+     *             synonyms (Required): [
+     *                 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 indexName the name of the index for which to retrieve statistics - * @return the index statistics result. + * @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 SearchIndexStatistics getIndexStatistics(String indexName) { - return getIndexStatisticsWithResponse(indexName, Context.NONE).getValue(); + Response getSynonymMapsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getSynonymMapsWithResponse(requestOptions); } /** - * Returns statistics for the given index, including a document count and storage usage. + * Creates a new synonym map. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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)
+     * }
+     * }
+     * 
* - *

Get search index "searchIndex" statistics.

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     format: String (Required)
+     *     synonyms (Required): [
+     *         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 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. + * @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 getIndexStatisticsWithResponse(String indexName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().getStatisticsWithResponse(indexName, null, context), LOGGER); + public Response createSynonymMapWithResponse(BinaryData synonymMap, RequestOptions requestOptions) { + return this.serviceClient.createSynonymMapWithResponse(synonymMap, requestOptions); } /** - * Lists all indexes available for an Azure AI Search service. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
* - *

List all search indexes.

+ *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @return the list of indexes. + * @param name 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.COLLECTION) - public PagedIterable listIndexes() { - return listIndexes(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateIndexWithResponse(String name, BinaryData index, RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateIndexWithResponse(name, index, requestOptions); } /** - * Lists all indexes available for an Azure AI Search service. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
* - *

List all search indexes.

+ *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of indexes. + * @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.COLLECTION) - public PagedIterable listIndexes(Context context) { - try { - return new PagedIterable<>(() -> this.listIndexesWithResponse(null, context)); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateIndexWithResponse(SearchIndex index, RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateIndexWithResponse(index.getName(), + BinaryData.fromObject(index), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SearchIndex.class)); } - private PagedResponse listIndexesWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().listSinglePage(select, null, context), LOGGER); + /** + * 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 name 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 deleteIndexWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteIndexWithResponse(name, requestOptions); } /** - * Lists all index names for an Azure AI Search service. + * Retrieves an index definition. + *

Response Body Schema

* - *

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);
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @return the list of index names. + * @param name 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.COLLECTION) - public PagedIterable listIndexNames() { - return listIndexNames(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getIndexWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexWithResponse(name, requestOptions); } /** - * Lists all indexes names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexes names.

+ * Lists all indexes available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - * *
-     * 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);
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of index names. + * @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 listIndexNames(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mapPagedSearchIndexNames(this.listIndexesWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } + public PagedIterable listIndexes(RequestOptions requestOptions) { + return this.serviceClient.listIndexes(requestOptions); } /** - * Creates a new Azure AI Search index or updates an index if it already exists. + * Creates a new search index. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
+     * 
* - *

Create or update search index named "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     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)
+     *             permissionFilter: String(userIds/groupIds/rbacScope) (Optional)
+     *             sensitivityLabel: 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/product) (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)
+     *                     ]
+     *                 }
+     *                 rankingOrder: String(BoostedRerankerScore/RerankerScore) (Optional)
+     *                 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)
+     *                 rescoringOptions (Optional): {
+     *                     enableRescoring: Boolean (Optional)
+     *                     defaultOversampling: Double (Optional)
+     *                     rescoreStorageMethod: String(preserveOriginals/discardOriginals) (Optional)
+     *                 }
+     *                 truncationDimension: Integer (Optional)
+     *             }
+     *         ]
+     *     }
+     *     permissionFilterOption: String(enabled/disabled) (Optional)
+     *     purviewEnabled: Boolean (Optional)
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param index the definition of the index to create or update - * @return the index that was created or updated. + * @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 SearchIndex createOrUpdateIndex(SearchIndex index) { - return createOrUpdateIndexWithResponse(index, false, false, Context.NONE).getValue(); + public Response createIndexWithResponse(BinaryData index, RequestOptions requestOptions) { + return this.serviceClient.createIndexWithResponse(index, requestOptions); } /** - * Creates a new Azure AI Search index or updates an index if it already exists. - * - *

Code Sample

- * - *

Create or update search index named "searchIndex".

+ * Returns statistics for the given index, including a document count and storage usage. + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
      * 
- * * - * @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. + * @param name 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 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); + public Response getIndexStatisticsWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexStatisticsWithResponse(name, requestOptions); } /** - * Deletes an Azure AI Search index and all the documents it contains. + * Shows how an analyzer breaks text into tokens. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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)
+     *     ]
+     * }
+     * }
+     * 
* - *

Delete search index with name "searchIndex".

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEX_CLIENT.deleteIndex("searchIndex");
+     * {@code
+     * {
+     *     tokens (Required): [
+     *          (Required){
+     *             token: String (Required)
+     *             startOffset: int (Required)
+     *             endOffset: int (Required)
+     *             position: int (Required)
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @param indexName the name of the index to delete + * @param name 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 void deleteIndex(String indexName) { - Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexes().deleteWithResponse(indexName, null, null, null, Context.NONE), LOGGER); + public Response analyzeTextWithResponse(String name, BinaryData request, + RequestOptions requestOptions) { + return this.serviceClient.analyzeTextWithResponse(name, request, requestOptions); } /** - * Deletes an Azure AI Search index and all the documents it contains. + * 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 Sample

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

Delete search index with name "searchIndex".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @param name 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 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); + Response createOrUpdateAliasWithResponse(String name, BinaryData alias, RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateAliasWithResponse(name, alias, requestOptions); } /** - * Shows how an analyzer breaks text into tokens. + * 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 Sample

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

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

+ *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @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.COLLECTION) - public PagedIterable analyzeText(String indexName, AnalyzeTextOptions analyzeTextOptions) { - return analyzeText(indexName, analyzeTextOptions, Context.NONE); + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createOrUpdateAliasWithResponse(SearchAlias alias, RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateAliasWithResponse(alias.getName(), + BinaryData.fromObject(alias), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SearchAlias.class)); } /** - * Shows how an analyzer breaks text into tokens. - * - *

Code Sample

- * - *

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

+ * 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 name 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 deleteAliasWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteAliasWithResponse(name, requestOptions); + } + + /** + * Retrieves an alias definition. + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @param name 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.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.mapPagedTokenInfos(restClient.getIndexes() - .analyzeWithResponse(indexName, AnalyzeRequestConverter.map(analyzeTextOptions), null, context)), - LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getAliasWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getAliasWithResponse(name, requestOptions); } /** - * Creates a new Azure AI Search synonym map. - * - *

Code Sample

+ * Lists all aliases available for a search service. + *

Response Body Schema

* - *

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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMap the definition of the synonym map to create - * @return the created {@link SynonymMap}. + * @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.SINGLE) - public SynonymMap createSynonymMap(SynonymMap synonymMap) { - return createSynonymMapWithResponse(synonymMap, Context.NONE).getValue(); + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listAliases(RequestOptions requestOptions) { + return this.serviceClient.listAliases(requestOptions); } /** - * Creates a new Azure AI Search synonym map. + * Creates a new search alias. + *

Request Body Schema

* - *

Code Sample

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

Create synonym map named "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     indexes (Required): [
+     *         String (Required)
+     *     ]
+     *     @odata.etag: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @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 createSynonymMapWithResponse(SynonymMap synonymMap, Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> { - Objects.requireNonNull(synonymMap, "'synonymMap' cannot be null."); - return restClient.getSynonymMaps().createWithResponse(synonymMap, null, context); - }, LOGGER); + public Response createAliasWithResponse(BinaryData alias, RequestOptions requestOptions) { + return this.serviceClient.createAliasWithResponse(alias, requestOptions); } /** - * Retrieves a synonym map definition. + * Creates a new knowledge base or updates a knowledge base 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
* - *

Get synonym map with name "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @param synonymMapName name of the synonym map to retrieve - * @return the {@link SynonymMap} definition + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap getSynonymMap(String synonymMapName) { - return getSynonymMapWithResponse(synonymMapName, Context.NONE).getValue(); + Response createOrUpdateKnowledgeBaseWithResponse(String name, BinaryData knowledgeBase, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateKnowledgeBaseWithResponse(name, knowledgeBase, requestOptions); } /** - * Retrieves a synonym map definition. + * Creates a new knowledge base or updates a knowledge base 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
* - *

Get synonym map with name "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @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. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getSynonymMapWithResponse(String synonymMapName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSynonymMaps().getWithResponse(synonymMapName, null, context), LOGGER); + public Response createOrUpdateKnowledgeBaseWithResponse(KnowledgeBase knowledgeBase, + RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateKnowledgeBaseWithResponse( + knowledgeBase.getName(), BinaryData.fromObject(knowledgeBase), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(KnowledgeBase.class)); } /** - * Lists all synonym maps available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym maps.

+ * Deletes a knowledge base. + *

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 name The name of the knowledge base. + * @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 deleteKnowledgeBaseWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteKnowledgeBaseWithResponse(name, requestOptions); + } + + /** + * Retrieves a knowledge base definition. + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @return the list of synonym maps. + * @param name The name of the knowledge base. + * @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 knowledge base definition along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMaps() { - return listSynonymMaps(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getKnowledgeBaseWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getKnowledgeBaseWithResponse(name, requestOptions); } /** - * Lists all synonym maps available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all synonym maps.

+ * Lists all knowledge bases available for a search service. + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of synonym map names. + * @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 result from listing knowledge bases as paginated response with {@link PagedIterable}. */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMaps(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mapPagedSynonymMaps(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); + public PagedIterable listKnowledgeBases(RequestOptions requestOptions) { + return this.serviceClient.listKnowledgeBases(requestOptions); } /** - * Lists all synonym maps names for an Azure AI Search service. + * Creates a new knowledge base. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
+     * 
* - *

List all synonym map names.

+ *

Response Body Schema

* - * *
-     * PagedIterable<String> synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMapNames();
-     * for (String synonymMap: synonymMaps) {
-     *     System.out.printf("The synonymMap name is %s.%n", synonymMap);
-     * }
+     * {@code
+     * {
+     *     name: String (Required)
+     *     knowledgeSources (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *         }
+     *     ]
+     *     models (Optional): [
+     *          (Optional){
+     *             kind: String(azureOpenAI) (Required)
+     *         }
+     *     ]
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     outputMode: String(extractiveData/answerSynthesis) (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)
+     *         }
+     *     }
+     *     description: String (Optional)
+     *     retrievalInstructions: String (Optional)
+     *     answerInstructions: String (Optional)
+     * }
+     * }
      * 
- * * - * @return the list of synonym maps. + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMapNames() { - return listSynonymMapNames(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createKnowledgeBaseWithResponse(BinaryData knowledgeBase, + RequestOptions requestOptions) { + return this.serviceClient.createKnowledgeBaseWithResponse(knowledgeBase, requestOptions); } /** - * Lists all synonym maps names for an Azure AI Search service. + * Creates a new knowledge source or updates an knowledge source 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 Sample

+ *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
* - *

List all synonym map names.

+ *

Response Body Schema

* - * *
-     * 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);
-     * }
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of synonym map names. + * @param name The name of the knowledge source. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSynonymMapNames(Context context) { - try { - return new PagedIterable<>( - () -> MappingUtils.mapPagedSynonymMapNames(listSynonymMapsWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateKnowledgeSourceWithResponse(String name, BinaryData knowledgeSource, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateKnowledgeSourceWithResponse(name, knowledgeSource, requestOptions); } /** - * Creates a new Azure AI Search synonym map or updates a synonym map if it already exists. + * Creates a new knowledge source or updates an knowledge source 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 Sample

+ *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
* - *

Create or update synonym map named "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @param synonymMap the definition of the synonym map to create or update - * @return the synonym map that was created or updated. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SynonymMap createOrUpdateSynonymMap(SynonymMap synonymMap) { - return createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); + public Response createOrUpdateKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource, + RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateKnowledgeSourceWithResponse( + knowledgeSource.getName(), BinaryData.fromObject(knowledgeSource), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(KnowledgeSource.class)); } /** - * 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".

+ * Deletes an existing knowledge source. + *

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 name The name of the knowledge source. + * @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 deleteKnowledgeSourceWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteKnowledgeSourceWithResponse(name, requestOptions); + } + + /** + * Retrieves a knowledge source definition. + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @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. + * @param name The name of the knowledge source. + * @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 knowledge source definition along with {@link Response}. */ + @Generated @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); + public Response getKnowledgeSourceWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getKnowledgeSourceWithResponse(name, requestOptions); } /** - * Deletes an Azure AI Search synonym map. - * - *

Code Sample

- * - *

Delete synonym map with name "synonymMap".

+ * Lists all knowledge sources available for a search service. + *

Response Body Schema

* - * *
-     * SEARCH_INDEX_CLIENT.deleteSynonymMap("synonymMap");
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @param synonymMapName the name of the synonym map to delete + * @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 result from listing knowledge sources as paginated response with {@link PagedIterable}. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteSynonymMap(String synonymMapName) { - Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSynonymMaps().deleteWithResponse(synonymMapName, null, null, null, Context.NONE), - LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listKnowledgeSources(RequestOptions requestOptions) { + return this.serviceClient.listKnowledgeSources(requestOptions); } /** - * Deletes an Azure AI Search synonym map. + * Creates a new knowledge source. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
+     * 
* - *

Delete synonym map with name "synonymMap".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *     name: String (Required)
+     *     description: String (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)
+     *         }
+     *     }
+     * }
+     * }
      * 
- * * - * @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. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. */ + @Generated @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); + public Response createKnowledgeSourceWithResponse(BinaryData knowledgeSource, + RequestOptions requestOptions) { + return this.serviceClient.createKnowledgeSourceWithResponse(knowledgeSource, requestOptions); } /** - * Returns service level statistics for a search service, including service counters and limits. - * - *

Code Sample

- * - *

Get service statistics.

+ * Retrieves the status of a knowledge source. + *

Response Body Schema

* - * *
-     * SearchServiceStatistics serviceStatistics = SEARCH_INDEX_CLIENT.getServiceStatistics();
-     * System.out.printf("There are %s search indexes in your service.%n",
-     *     serviceStatistics.getCounters().getIndexCounter());
+     * {@code
+     * {
+     *     synchronizationStatus: String(creating/active/deleting) (Required)
+     *     synchronizationInterval: String (Optional)
+     *     currentSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     lastSynchronizationState (Optional): {
+     *         startTime: OffsetDateTime (Required)
+     *         endTime: OffsetDateTime (Required)
+     *         itemsUpdatesProcessed: int (Required)
+     *         itemsUpdatesFailed: int (Required)
+     *         itemsSkipped: int (Required)
+     *     }
+     *     statistics (Optional): {
+     *         totalSynchronization: int (Required)
+     *         averageSynchronizationDuration: String (Required)
+     *         averageItemsProcessedPerSynchronization: int (Required)
+     *     }
+     * }
+     * }
      * 
- * * - * @return the search service statistics result. + * @param name The name of the knowledge source. + * @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 status and synchronization history of a knowledge source along with {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public SearchServiceStatistics getServiceStatistics() { - return getServiceStatisticsWithResponse(Context.NONE).getValue(); + public Response getKnowledgeSourceStatusWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getKnowledgeSourceStatusWithResponse(name, requestOptions); } /** - * Returns service level statistics for a search service, including service counters and limits. - * - *

Code Sample

- * - *

Get service statistics.

+ * Gets service level statistics for a search service. + *

Response Body Schema

* - * *
-     * 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());
+     * {@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)
+     *         maxCumulativeIndexerRuntimeSeconds: Long (Optional)
+     *     }
+     *     indexersRuntime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     * }
+     * }
      * 
- * * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the search service statistics result. + * @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 Response getServiceStatisticsWithResponse(Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getServiceStatisticsWithResponse(null, context), LOGGER); + 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

* - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. - * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. + *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     documentCount: long (Required)
+     *     storageSize: long (Required)
+     *     vectorIndexSize: long (Required)
+     * }
+     * }
+     * 
+ * + * @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 PagedIterable getIndexStatsSummary() { - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getIndexStatsSummary(null), LOGGER); + public PagedIterable listIndexStatsSummary(RequestOptions requestOptions) { + return this.serviceClient.listIndexStatsSummary(requestOptions); } /** - * Retrieves a summary of statistics for all indexes in the search service. + * Creates a new synonym map or updates a synonym map if it already exists. * - * @param context The context to associate with this operation. + * @param name 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 ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 PagedResponse}. + * @return represents a synonym map definition. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getIndexStatsSummary(Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getIndexStatsSummary(null, context), - LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + SynonymMap createOrUpdateSynonymMap(String name, SynonymMap synonymMap, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateSynonymMapWithResponse + 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 createOrUpdateSynonymMapWithResponse(name, BinaryData.fromObject(synonymMap), requestOptions).getValue() + .toObject(SynonymMap.class); } /** - * 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); + * Creates a new synonym map or updates a synonym map if it already exists. + * + * @param name 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) + SynonymMap createOrUpdateSynonymMap(String name, SynonymMap synonymMap) { + // Generated convenience method for createOrUpdateSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateSynonymMapWithResponse(name, BinaryData.fromObject(synonymMap), requestOptions).getValue() + .toObject(SynonymMap.class); } /** - * Creates a new Azure AI Search alias. - * - *

Code Sample

- * - *

Create the search alias named "my-alias".

- * - * - *
-     * SearchAlias searchAlias = SEARCH_INDEX_CLIENT.createAlias(new SearchAlias("my-alias",
-     *     Collections.singletonList("index-to-alias")));
-     * System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(),
-     *     searchAlias.getIndexes().get(0));
-     * 
- * + * Creates a new synonym map or updates a synonym map if it already exists. * - * @param alias definition of the alias to create. - * @return the created alias. + * @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. */ - public SearchAlias createAlias(SearchAlias alias) { - return createAliasWithResponse(alias, Context.NONE).getValue(); + @ServiceMethod(returns = ReturnType.SINGLE) + public SynonymMap createOrUpdateSynonymMap(SynonymMap synonymMap) { + return createOrUpdateSynonymMap(synonymMap.getName(), synonymMap); } /** - * Creates a new Azure AI Search alias. - * - *

Code Sample

- * - *

Create the search alias named "my-alias".

+ * Deletes a synonym map. * - * - *
-     * Response<SearchAlias> response = SEARCH_INDEX_CLIENT.createAliasWithResponse(new SearchAlias("my-alias",
-     *     Collections.singletonList("index-to-alias")), new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.",
-     *     response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0));
-     * 
- * - * - * @param alias definition of the alias to create. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the created alias. + * @param name 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. */ - public Response createAliasWithResponse(SearchAlias alias, Context context) { - try { - return restClient.getAliases().createWithResponse(alias, null, context); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteSynonymMap(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteSynonymMapWithResponse + 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); + } + deleteSynonymMapWithResponse(name, requestOptions).getValue(); } /** - * Creates or updates an Azure AI Search alias. - * - *

Code Sample

- * - *

Create then update the search alias named "my-alias".

- * - * - *
-     * SearchAlias searchAlias = SEARCH_INDEX_CLIENT.createOrUpdateAlias(
-     *     new SearchAlias("my-alias", Collections.singletonList("index-to-alias")));
-     *
-     * System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(),
-     *     searchAlias.getIndexes().get(0));
-     *
-     * searchAlias = SEARCH_INDEX_CLIENT.createOrUpdateAlias(new SearchAlias(searchAlias.getName(),
-     *     Collections.singletonList("new-index-to-alias")));
+     * Deletes a synonym map.
      *
-     * System.out.printf("Updated alias '%s' to aliases index '%s'.", searchAlias.getName(),
-     *     searchAlias.getIndexes().get(0));
-     * 
- * - * - * @param alias definition of the alias to create or update. - * @return the created or updated alias. + * @param name 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. */ - public SearchAlias createOrUpdateAlias(SearchAlias alias) { - return createOrUpdateAliasWithResponse(alias, false, Context.NONE).getValue(); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteSynonymMap(String name) { + // Generated convenience method for deleteSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteSynonymMapWithResponse(name, requestOptions).getValue(); } /** - * Creates or updates an Azure AI Search alias. - * - *

Code Sample

- * - *

Create then update the search alias named "my-alias".

- * - * - *
-     * Response<SearchAlias> response = SEARCH_INDEX_CLIENT.createOrUpdateAliasWithResponse(
-     *     new SearchAlias("my-alias", Collections.singletonList("index-to-alias")), false, new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.",
-     *     response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0));
-     *
-     * response = SEARCH_INDEX_CLIENT.createOrUpdateAliasWithResponse(
-     *     new SearchAlias(response.getValue().getName(), Collections.singletonList("new-index-to-alias"))
-     *         .setETag(response.getValue().getETag()), true, new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("Response status code %d. Updated alias '%s' that aliases index '%s'.",
-     *     response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0));
-     * 
- * + * Retrieves a synonym map definition. * - * @param alias definition of the alias to create or update. - * @param onlyIfUnchanged only update the alias if the eTag matches the alias on the service. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the created or updated alias. + * @param name 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. */ - public Response createOrUpdateAliasWithResponse(SearchAlias alias, boolean onlyIfUnchanged, - Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getAliases() - .createOrUpdateWithResponse(alias.getName(), alias, onlyIfUnchanged ? alias.getETag() : null, null, null, - context), - LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SynonymMap getSynonymMap(String name) { + // Generated convenience method for getSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSynonymMapWithResponse(name, requestOptions).getValue().toObject(SynonymMap.class); } /** - * Gets the Azure AI Search alias. - * - *

Code Sample

- * - *

Get the search alias named "my-alias".

+ * Lists all synonym maps available for a search service. * - * - *
-     * SearchAlias searchAlias = SEARCH_INDEX_CLIENT.getAlias("my-alias");
-     *
-     * System.out.printf("Retrieved alias '%s' that aliases index '%s'.", searchAlias.getName(),
-     *     searchAlias.getIndexes().get(0));
-     * 
- * - * - * @param aliasName name of the alias to get. - * @return the retrieved alias. + * @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. */ - public SearchAlias getAlias(String aliasName) { - return getAliasWithResponse(aliasName, Context.NONE).getValue(); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + ListSynonymMapsResult getSynonymMaps(List select) { + // Generated convenience method for getSynonymMapsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getSynonymMapsWithResponse(requestOptions).getValue().toObject(ListSynonymMapsResult.class); } /** - * Gets the Azure AI Search alias. - * - *

Code Sample

- * - *

Get the search alias named "my-alias".

- * - * - *
-     * Response<SearchAlias> response = SEARCH_INDEX_CLIENT.getAliasWithResponse("my-alias", new Context(KEY_1, VALUE_1));
-     *
-     * System.out.printf("Response status code %d. Retrieved alias '%s' that aliases index '%s'.",
-     *     response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0));
-     * 
- * + * Lists all synonym maps available for a search service. * - * @param aliasName name of the alias to get. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the retrieved alias. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ - public Response getAliasWithResponse(String aliasName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getAliases().getWithResponse(aliasName, null, context), LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + ListSynonymMapsResult getSynonymMaps() { + // Generated convenience method for getSynonymMapsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSynonymMapsWithResponse(requestOptions).getValue().toObject(ListSynonymMapsResult.class); } /** - * Deletes the Azure AI Search alias. - * - *

Code Sample

- * - *

Delete the search alias named "my-alias".

- * - * - *
-     * SEARCH_INDEX_CLIENT.deleteAlias("my-alias");
-     *
-     * System.out.println("Deleted alias 'my-alias'.");
-     * 
- * + * Lists all synonym maps available for a search service. * - * @param aliasName name of the alias to delete. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ - public void deleteAlias(String aliasName) { - deleteAliasWithResponse(aliasName, null, Context.NONE); + @ServiceMethod(returns = ReturnType.SINGLE) + public ListSynonymMapsResult listSynonymMaps() { + return getSynonymMaps(); } /** - * Deletes the Azure AI Search alias. + * Lists the names of all synonym maps available for a search service. * - *

Code Sample

+ * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public List listSynonymMapNames() { + return getSynonymMaps(Collections.singletonList("name")).getSynonymMaps() + .stream() + .map(SynonymMap::getName) + .collect(Collectors.toList()); + } + + /** + * Creates a new synonym map. * - *

Delete the search alias named "my-alias".

+ * @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 createSynonymMap(SynonymMap synonymMap) { + // Generated convenience method for createSynonymMapWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createSynonymMapWithResponse(BinaryData.fromObject(synonymMap), requestOptions).getValue() + .toObject(SynonymMap.class); + } + + /** + * Creates a new search index or updates an index if it already exists. * - * - *
-     * SearchAlias searchAlias = SEARCH_INDEX_CLIENT.getAlias("my-alias");
+     * @param name 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)
+    SearchIndex createOrUpdateIndex(String name, SearchIndex index, Boolean allowIndexDowntime,
+        MatchConditions matchConditions) {
+        // Generated convenience method for createOrUpdateIndexWithResponse
+        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 createOrUpdateIndexWithResponse(name, BinaryData.fromObject(index), requestOptions).getValue()
+            .toObject(SearchIndex.class);
+    }
+
+    /**
+     * Creates a new search index or updates an index if it already exists.
      *
-     * Response<Void> response = SEARCH_INDEX_CLIENT.deleteAliasWithResponse(searchAlias, true,
-     *     new Context(KEY_1, VALUE_1));
+     * @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.
+     */
+    @ServiceMethod(returns = ReturnType.SINGLE)
+    public SearchIndex createOrUpdateIndex(SearchIndex index) {
+        return createOrUpdateIndex(index.getName(), index);
+    }
+
+    /**
+     * Creates a new search index or updates an index if it already exists.
      *
-     * System.out.printf("Response status code %d. Deleted alias 'my-alias'.", response.getStatusCode());
-     * 
- * + * @param name 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) + SearchIndex createOrUpdateIndex(String name, SearchIndex index) { + // Generated convenience method for createOrUpdateIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateIndexWithResponse(name, 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 alias the alias to delete. - * @param onlyIfUnchanged only delete the alias if the eTag matches the alias on the service. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response indicating the alias has been deleted. + * @param name 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. */ - public Response deleteAliasWithResponse(SearchAlias alias, boolean onlyIfUnchanged, Context context) { - return deleteAliasWithResponse(alias.getName(), onlyIfUnchanged ? alias.getETag() : null, context); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteIndex(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteIndexWithResponse + 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); + } + deleteIndexWithResponse(name, requestOptions).getValue(); } - Response deleteAliasWithResponse(String aliasName, String eTag, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getAliases().deleteWithResponse(aliasName, eTag, null, null, context), LOGGER); + /** + * 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 name 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 deleteIndex(String name) { + // Generated convenience method for deleteIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteIndexWithResponse(name, requestOptions).getValue(); } /** - * Lists all aliases in the Azure AI Search service. + * Retrieves an index definition. * - *

Code Sample

+ * @param name 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 getIndex(String name) { + // Generated convenience method for getIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexWithResponse(name, requestOptions).getValue().toObject(SearchIndex.class); + } + + /** + * Lists all indexes available for a search service. * - *

List aliases

+ * @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 listIndexes(List select) { + // Generated convenience method for listIndexes + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return serviceClient.listIndexes(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(SearchIndex.class)); + } + + /** + * Lists all indexes available for a search service. * - * - *
-     * SEARCH_INDEX_CLIENT.listAliases()
-     *     .forEach(searchAlias -> System.out.printf("Listed alias '%s' that aliases index '%s'.",
-     *         searchAlias.getName(), searchAlias.getIndexes().get(0)));
-     * 
- * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 listIndexes() { + // Generated convenience method for listIndexes + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listIndexes(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(SearchIndex.class)); + } + + /** + * Lists the names all indexes available for a search service. * - * @return a list of aliases in the 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}. */ - public PagedIterable listAliases() { - return listAliases(Context.NONE); + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listIndexNames() { + return listIndexes(Collections.singletonList("name")).mapPage(SearchIndex::getName); } /** - * Lists all aliases in the Azure AI Search service. + * Creates a new search index. * - *

Code Sample

+ * @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 createIndex(SearchIndex index) { + // Generated convenience method for createIndexWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createIndexWithResponse(BinaryData.fromObject(index), requestOptions).getValue() + .toObject(SearchIndex.class); + } + + /** + * Returns statistics for the given index, including a document count and storage usage. * - *

List aliases

+ * @param name 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 getIndexStatistics(String name) { + // Generated convenience method for getIndexStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexStatisticsWithResponse(name, requestOptions).getValue().toObject(GetIndexStatisticsResult.class); + } + + /** + * Shows how an analyzer breaks text into tokens. * - * - *
-     * SEARCH_INDEX_CLIENT.listAliases(new Context(KEY_1, VALUE_1))
-     *     .forEach(searchAlias -> System.out.printf("Listed alias '%s' that aliases index '%s'.",
-     *         searchAlias.getName(), searchAlias.getIndexes().get(0)));
-     * 
- * + * @param name 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 analyzeText(String name, AnalyzeTextOptions request) { + // Generated convenience method for analyzeTextWithResponse + RequestOptions requestOptions = new RequestOptions(); + return analyzeTextWithResponse(name, BinaryData.fromObject(request), requestOptions).getValue() + .toObject(AnalyzeResult.class); + } + + /** + * Creates a new search alias or updates an alias if it already exists. * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a list of aliases in the service. + * @param name 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. */ - public PagedIterable listAliases(Context context) { - try { - return new PagedIterable<>(() -> restClient.getAliases().listSinglePage(null, context)); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + SearchAlias createOrUpdateAlias(String name, SearchAlias alias, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateAliasWithResponse + 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 createOrUpdateAliasWithResponse(name, BinaryData.fromObject(alias), requestOptions).getValue() + .toObject(SearchAlias.class); } /** - * Creates a new agent. + * Creates a new search alias or updates an alias if it already exists. * - * @param knowledgeBases The definition of the agent to create. + * @param alias The definition of the alias to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response. + * @return represents an index alias, which describes a mapping from the alias name to an index. */ @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBase createKnowledgeBase(KnowledgeBase knowledgeBases) { - return createKnowledgeBaseWithResponse(knowledgeBases, Context.NONE).getValue(); + public SearchAlias createOrUpdateAlias(SearchAlias alias) { + return createOrUpdateAlias(alias.getName(), alias); } /** - * Creates a new agent. + * Creates a new search alias or updates an alias if it already exists. * - * @param knowledgeBases The definition of the agent to create. - * @param context The context to associate with this operation. + * @param name 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 ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body along with {@link Response}. + * @return represents an index alias, which describes a mapping from the alias name to an index. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response createKnowledgeBaseWithResponse(KnowledgeBase knowledgeBases, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getKnowledgeBases().createWithResponse(knowledgeBases, null, context), LOGGER); + SearchAlias createOrUpdateAlias(String name, SearchAlias alias) { + // Generated convenience method for createOrUpdateAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateAliasWithResponse(name, BinaryData.fromObject(alias), requestOptions).getValue() + .toObject(SearchAlias.class); } /** - * Creates a new agent or updates an agent if it already exists. + * 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 knowledgeBases The definition of the agent to create or update. + * @param name The name of the alias. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 the response. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBase createOrUpdateKnowledgeBase(KnowledgeBase knowledgeBases) { - return createOrUpdateKnowledgeBaseWithResponse(knowledgeBases, null, Context.NONE).getValue(); + public void deleteAlias(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteAliasWithResponse + 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); + } + deleteAliasWithResponse(name, requestOptions).getValue(); } /** - * Creates a new agent or updates an agent if it already exists. + * 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 knowledgeBases The definition of the agent to create or update. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. - * @param context The context to associate with this operation. + * @param name The name of the alias. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 the response body along with {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateKnowledgeBaseWithResponse(KnowledgeBase knowledgeBases, - MatchConditions matchConditions, Context context) { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getKnowledgeBases() - .createOrUpdateWithResponse(knowledgeBases.getName(), knowledgeBases, ifMatch, ifNoneMatch, null, context), - LOGGER); + public void deleteAlias(String name) { + // Generated convenience method for deleteAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteAliasWithResponse(name, requestOptions).getValue(); } /** - * Retrieves an agent definition. + * Retrieves an alias definition. * - * @param knowledgeBaseName The name of the agent to retrieve. + * @param name The name of the alias. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response. + * @return represents an index alias, which describes a mapping from the alias name to an index. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBase getKnowledgeBase(String knowledgeBaseName) { - return getKnowledgeBaseWithResponse(knowledgeBaseName, Context.NONE).getValue(); + public SearchAlias getAlias(String name) { + // Generated convenience method for getAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getAliasWithResponse(name, 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 listAliases() { + // Generated convenience method for listAliases + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listAliases(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(SearchAlias.class)); } /** - * Retrieves an agent definition. + * Creates a new search alias. * - * @param knowledgeBaseName The name of the agent to retrieve. - * @param context The context to associate with this operation. + * @param alias The definition of the alias to create. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 response body along with {@link Response}. + * @return represents an index alias, which describes a mapping from the alias name to an index. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKnowledgeBaseWithResponse(String knowledgeBaseName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getKnowledgeBases().getWithResponse(knowledgeBaseName, null, context), LOGGER); + public SearchAlias createAlias(SearchAlias alias) { + // Generated convenience method for createAliasWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createAliasWithResponse(BinaryData.fromObject(alias), requestOptions).getValue() + .toObject(SearchAlias.class); } /** - * Lists all knowledgebases available for a search service. + * Creates a new knowledge base or updates a knowledge base if it already exists. * + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base to create or update. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 paginated response with {@link PagedIterable}. + * @return represents a knowledge base definition. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listKnowledgeBases() { - return listKnowledgeBases(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + KnowledgeBase createOrUpdateKnowledgeBase(String name, KnowledgeBase knowledgeBase, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateKnowledgeBaseWithResponse + 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 createOrUpdateKnowledgeBaseWithResponse(name, BinaryData.fromObject(knowledgeBase), requestOptions) + .getValue() + .toObject(KnowledgeBase.class); } /** - * Lists all knowledgebases available for a search service. + * Creates a new knowledge base or updates a knowledge base if it already exists. * - * @param context The context to associate with this operation. + * @param name The name of the knowledge base. + * @param knowledgeBase The definition of the knowledge base to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 paginated response with {@link PagedIterable}. + * @return represents a knowledge base definition. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listKnowledgeBases(Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getKnowledgeBases().list(null, context), - LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + KnowledgeBase createOrUpdateKnowledgeBase(String name, KnowledgeBase knowledgeBase) { + // Generated convenience method for createOrUpdateKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateKnowledgeBaseWithResponse(name, BinaryData.fromObject(knowledgeBase), requestOptions) + .getValue() + .toObject(KnowledgeBase.class); } /** - * Deletes an existing agent. + * Creates a new knowledge base or updates a knowledge base if it already exists. * - * @param knowledgeBaseName The name of the agent to delete. + * @param knowledgeBase The definition of the knowledge base to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 knowledge base definition. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteKnowledgeBase(String knowledgeBaseName) { - deleteKnowledgeBaseWithResponse(knowledgeBaseName, null, Context.NONE).getValue(); + public KnowledgeBase createOrUpdateKnowledgeBase(KnowledgeBase knowledgeBase) { + return createOrUpdateKnowledgeBase(knowledgeBase.getName(), knowledgeBase); } /** - * Deletes an existing agent. + * Deletes a knowledge base. * - * @param knowledgeBaseName The name of the agent to delete. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. - * @param context The context to associate with this operation. + * @param name The name of the knowledge base. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 the {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteKnowledgeBaseWithResponse(String knowledgeBaseName, MatchConditions matchConditions, - Context context) { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getKnowledgeBases() - .deleteWithResponse(knowledgeBaseName, ifMatch, ifNoneMatch, null, context), LOGGER); + public void deleteKnowledgeBase(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteKnowledgeBaseWithResponse + 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); + } + deleteKnowledgeBaseWithResponse(name, requestOptions).getValue(); } /** - * Creates a new knowledge source. + * Deletes a knowledge base. * - * @param knowledgeSource The definition of the knowledge source to create. + * @param name The name of the knowledge base. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 The created knowledge source. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeSource createKnowledgeSource(KnowledgeSource knowledgeSource) { - return createKnowledgeSourceWithResponse(knowledgeSource, Context.NONE).getValue(); + public void deleteKnowledgeBase(String name) { + // Generated convenience method for deleteKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteKnowledgeBaseWithResponse(name, requestOptions).getValue(); } /** - * Creates a new knowledge source. + * Retrieves a knowledge base definition. * - * @param knowledgeSource The definition of the knowledge source to create. - * @param context The context to associate with this operation. + * @param name The name of the knowledge base. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 Response} containing the created knowledge source. + * @return represents a knowledge base definition. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response createKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource, - Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getKnowledgeSources().createWithResponse(knowledgeSource, null, context), LOGGER); + public KnowledgeBase getKnowledgeBase(String name) { + // Generated convenience method for getKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getKnowledgeBaseWithResponse(name, requestOptions).getValue().toObject(KnowledgeBase.class); } /** - * Creates or updates a knowledge source. + * Lists all knowledge bases 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 result from listing knowledge bases as paginated response with {@link PagedIterable}. + */ + @Generated + @ServiceMethod(returns = ReturnType.COLLECTION) + public PagedIterable listKnowledgeBases() { + // Generated convenience method for listKnowledgeBases + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listKnowledgeBases(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(KnowledgeBase.class)); + } + + /** + * Creates a new knowledge base. + * + * @param knowledgeBase The definition of the knowledge base 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 knowledge base definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeBase createKnowledgeBase(KnowledgeBase knowledgeBase) { + // Generated convenience method for createKnowledgeBaseWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createKnowledgeBaseWithResponse(BinaryData.fromObject(knowledgeBase), requestOptions).getValue() + .toObject(KnowledgeBase.class); + } + + /** + * Creates a new knowledge source or updates an knowledge source if it already exists. + * + * @param name The name of the knowledge source. + * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + KnowledgeSource createOrUpdateKnowledgeSource(String name, KnowledgeSource knowledgeSource, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateKnowledgeSourceWithResponse + 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 createOrUpdateKnowledgeSourceWithResponse(name, BinaryData.fromObject(knowledgeSource), requestOptions) + .getValue() + .toObject(KnowledgeSource.class); + } + + /** + * Creates a new knowledge source or updates an knowledge source if it already exists. * * @param knowledgeSource The definition of the knowledge source to create or update. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 created or updated knowledge source. + * @return represents a knowledge source definition. */ @ServiceMethod(returns = ReturnType.SINGLE) public KnowledgeSource createOrUpdateKnowledgeSource(KnowledgeSource knowledgeSource) { - return createOrUpdateKnowledgeSourceWithResponse(knowledgeSource, null, Context.NONE).getValue(); + return createOrUpdateKnowledgeSource(knowledgeSource.getName(), knowledgeSource); } /** - * Creates or updates a knowledge source. + * Creates a new knowledge source or updates an knowledge source if it already exists. * + * @param name The name of the knowledge source. * @param knowledgeSource The definition of the knowledge source to create or update. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. - * @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 HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 Response} containing the created or updated knowledge source. + * @return represents a knowledge source definition. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateKnowledgeSourceWithResponse(KnowledgeSource knowledgeSource, - MatchConditions matchConditions, Context context) { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getKnowledgeSources() - .createOrUpdateWithResponse(knowledgeSource.getName(), knowledgeSource, ifMatch, ifNoneMatch, null, - context), - LOGGER); + KnowledgeSource createOrUpdateKnowledgeSource(String name, KnowledgeSource knowledgeSource) { + // Generated convenience method for createOrUpdateKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateKnowledgeSourceWithResponse(name, BinaryData.fromObject(knowledgeSource), requestOptions) + .getValue() + .toObject(KnowledgeSource.class); } /** - * Retrieves a knowledge source definition. + * Deletes an existing knowledge source. * - * @param sourceName The name of the knowledge source to retrieve. + * @param name The name of the knowledge source. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 The retrieved knowledge source. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeSource getKnowledgeSource(String sourceName) { - return getKnowledgeSourceWithResponse(sourceName, Context.NONE).getValue(); + public void deleteKnowledgeSource(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteKnowledgeSourceWithResponse + 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); + } + deleteKnowledgeSourceWithResponse(name, requestOptions).getValue(); + } + /** + * Deletes an existing knowledge source. + * + * @param name The name of the knowledge source. + * @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 deleteKnowledgeSource(String name) { + // Generated convenience method for deleteKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteKnowledgeSourceWithResponse(name, requestOptions).getValue(); } /** * Retrieves a knowledge source definition. * - * @param sourceName The name of the knowledge source to retrieve. - * @param context The context to associate with this operation. + * @param name The name of the knowledge source. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 Response} containing the retrieved knowledge source. + * @return represents a knowledge source definition. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response getKnowledgeSourceWithResponse(String sourceName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getKnowledgeSources().getWithResponse(sourceName, null, context), LOGGER); + public KnowledgeSource getKnowledgeSource(String name) { + // Generated convenience method for getKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getKnowledgeSourceWithResponse(name, requestOptions).getValue().toObject(KnowledgeSource.class); } /** * Lists all knowledge sources available for a search service. * - * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 PagedIterable} of knowledge sources. + * @return result from listing knowledge sources as paginated response with {@link PagedIterable}. */ + @Generated @ServiceMethod(returns = ReturnType.COLLECTION) public PagedIterable listKnowledgeSources() { - return listKnowledgeSources(Context.NONE); + // Generated convenience method for listKnowledgeSources + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listKnowledgeSources(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(KnowledgeSource.class)); } /** - * Lists all knowledge sources available for a search service. + * Creates a new knowledge source. * - * @param context The context to associate with this operation. + * @param knowledgeSource The definition of the knowledge source to create. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 PagedIterable} of knowledge sources. + * @return represents a knowledge source definition. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listKnowledgeSources(Context context) { - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getKnowledgeSources().list(null, context), - LOGGER); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeSource createKnowledgeSource(KnowledgeSource knowledgeSource) { + // Generated convenience method for createKnowledgeSourceWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createKnowledgeSourceWithResponse(BinaryData.fromObject(knowledgeSource), requestOptions).getValue() + .toObject(KnowledgeSource.class); } /** - * Deletes an existing knowledge agent. + * Retrieves the status of a knowledge source. * - * @param sourceName The name of the knowledge source to delete. + * @param name The name of the knowledge source. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 status and synchronization history of a knowledge source. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public void deleteKnowledgeSource(String sourceName) { - deleteKnowledgeSourceWithResponse(sourceName, null, Context.NONE).getValue(); + public KnowledgeSourceStatus getKnowledgeSourceStatus(String name) { + // Generated convenience method for getKnowledgeSourceStatusWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getKnowledgeSourceStatusWithResponse(name, requestOptions).getValue() + .toObject(KnowledgeSourceStatus.class); } /** - * Deletes an existing knowledge source. + * Gets service level statistics for a search service. * - * @param sourceName The name of the knowledge source to delete. - * @param matchConditions Defining {@code If-Match} and {@code If-None-Match} conditions. If null is passed, no - * conditions will be applied. - * @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 HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 Response} indicating deletion completed. + * @return service level statistics for a search service. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response deleteKnowledgeSourceWithResponse(String sourceName, MatchConditions matchConditions, - Context context) { - String ifMatch = matchConditions != null ? matchConditions.getIfMatch() : null; - String ifNoneMatch = matchConditions != null ? matchConditions.getIfNoneMatch() : null; - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getKnowledgeSources().deleteWithResponse(sourceName, ifMatch, ifNoneMatch, null, context), - LOGGER); + public SearchServiceStatistics getServiceStatistics() { + // Generated convenience method for getServiceStatisticsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getServiceStatisticsWithResponse(requestOptions).getValue().toObject(SearchServiceStatistics.class); + } + + /** + * 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 PagedIterable listIndexStatsSummary() { + // Generated convenience method for listIndexStatsSummary + RequestOptions requestOptions = new RequestOptions(); + return serviceClient.listIndexStatsSummary(requestOptions) + .mapPage(bodyItemValue -> bodyItemValue.toObject(IndexStatisticsSummary.class)); } } 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 index 48a1ddeab62c..21b304f7c187 100644 --- 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 @@ -1,531 +1,377 @@ // 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.indexes; +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.HttpClientOptions; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.builder.ClientBuilderUtil; import com.azure.core.util.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.models.SearchAudience; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.search.documents.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 com.azure.search.documents.implementation.SearchIndexClientImpl; import java.util.ArrayList; import java.util.List; +import java.util.Map; 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 + * A builder for creating a new instance of the SearchIndexClient type. */ @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); +public final class SearchIndexClientBuilder implements HttpTrait, + ConfigurationTrait, TokenCredentialTrait, + KeyCredentialTrait, EndpointTrait { - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); + @Generated + private static final String SDK_NAME = "name"; - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; + @Generated + private static final String SDK_VERSION = "version"; - 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; + @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 SearchIndexClient SearchIndexClients} - * and {@link SearchIndexAsyncClient SearchIndexAsyncClients}. + * Create an instance of the SearchIndexClientBuilder. */ + @Generated public SearchIndexClientBuilder() { + this.pipelinePolicies = new ArrayList<>(); } - /** - * 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. + /* + * The HTTP client used to send the request. */ - 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); - } + @Generated + private HttpClient httpClient; /** - * 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. + * {@inheritDoc}. */ - 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); + @Generated + @Override + public SearchIndexClientBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; } + /* + * The HTTP pipeline to send requests through. + */ + @Generated + private HttpPipeline pipeline; + /** - * 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. + * {@inheritDoc}. */ + @Generated @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)); + public SearchIndexClientBuilder pipeline(HttpPipeline pipeline) { + if (this.pipeline != null && pipeline == null) { + LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured."); } - this.endpoint = endpoint; + this.pipeline = pipeline; return this; } + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; + /** - * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. - * - * @param credential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated SearchIndexClientBuilder object. + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexClientBuilder credential(AzureKeyCredential credential) { - this.azureKeyCredential = credential; + public SearchIndexClientBuilder 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 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. + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexClientBuilder credential(TokenCredential credential) { - this.tokenCredential = credential; + public SearchIndexClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; return this; } + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + /** - * 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. + * {@inheritDoc}. */ - public SearchIndexClientBuilder audience(SearchAudience audience) { - this.audience = audience; + @Generated + @Override + public SearchIndexClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; 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. + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; + public SearchIndexClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { + Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); + pipelinePolicies.add(customPolicy); return this; } - /** - * Gets the default Azure Search headers and query parameters allow list. - * - * @return The default {@link HttpLogOptions} allow list. + /* + * The configuration store that is used during construction of the service client. */ - public static HttpLogOptions getDefaultLogOptions() { - return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); - } + @Generated + private Configuration configuration; /** - * 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 + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; + public SearchIndexClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; return this; } + /* + * The TokenCredential used for authentication. + */ + @Generated + private TokenCredential tokenCredential; + /** - * 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}. + * {@inheritDoc}. */ + @Generated @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); - } - + public SearchIndexClientBuilder credential(TokenCredential tokenCredential) { + this.tokenCredential = tokenCredential; return this; } + /* + * The KeyCredential used for authentication. + */ + @Generated + private KeyCredential keyCredential; + /** - * 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. + * {@inheritDoc}. */ - public SearchIndexClientBuilder serializer(JsonSerializer jsonSerializer) { - this.jsonSerializer = jsonSerializer; + @Generated + @Override + public SearchIndexClientBuilder credential(KeyCredential keyCredential) { + this.keyCredential = keyCredential; return this; } + /* + * The service endpoint + */ + @Generated + private String endpoint; + /** - * 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. + * {@inheritDoc}. */ + @Generated @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; + public SearchIndexClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; return this; } + /* + * Service version + */ + @Generated + private SearchServiceVersion serviceVersion; + /** - * 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}. + * Sets Service version. * - * @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses. - * @return The updated SearchIndexClientBuilder object. + * @param serviceVersion the serviceVersion value. + * @return the SearchIndexClientBuilder. */ - @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; + @Generated + public SearchIndexClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; return this; } + /* + * The retry policy that will attempt to retry failed requests, if applicable. + */ + @Generated + private RetryPolicy retryPolicy; + /** - * 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. + * Sets The retry policy that will attempt to retry failed requests, if applicable. * - * @param configuration The configuration store that will be used. - * @return The updated SearchIndexClientBuilder object. + * @param retryPolicy the retryPolicy value. + * @return the SearchIndexClientBuilder. */ - @Override - public SearchIndexClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; + @Generated + public SearchIndexClientBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; 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. + * Sets the Audience to use for authentication with Microsoft Entra ID. *

- * Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}. + * If {@code audience} is null the public cloud audience will be assumed. * - * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. + * @param audience The Audience to use for authentication with Microsoft Entra ID. * @return The updated SearchIndexClientBuilder object. */ - public SearchIndexClientBuilder retryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; + public SearchIndexClientBuilder audience(SearchAudience audience) { + if (audience == null) { + this.scopes = DEFAULT_SCOPES; + } else { + this.scopes = new String[] { audience.getValue() + "/.default" }; + } return this; } /** - * Sets the {@link RetryOptions} for all the requests made through the client. + * Builds an instance of SearchIndexClientImpl with the provided parameters. * - *

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)}. + * @return an instance of SearchIndexClientImpl. + */ + @Generated + private SearchIndexClientImpl buildInnerClient() { + this.validateClient(); + HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); + SearchServiceVersion localServiceVersion + = (serviceVersion != null) ? serviceVersion : SearchServiceVersion.getLatest(); + SearchIndexClientImpl client = new SearchIndexClientImpl(localPipeline, + JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); + return client; + } + + @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, 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; + } + + /** + * Builds an instance of SearchIndexAsyncClient class. * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. - * @return The updated SearchIndexClientBuilder object. + * @return an instance of SearchIndexAsyncClient. */ - @Override - public SearchIndexClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; + @Generated + public SearchIndexAsyncClient buildAsyncClient() { + return new SearchIndexAsyncClient(buildInnerClient()); } /** - * 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. + * Builds an instance of SearchIndexClient class. * - * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchIndexClientBuilder object. + * @return an instance of SearchIndexClient. */ - public SearchIndexClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - return this; + @Generated + public SearchIndexClient buildClient() { + return new SearchIndexClient(buildInnerClient()); } + + private static final ClientLogger LOGGER = new ClientLogger(SearchIndexClientBuilder.class); + + @Generated + private String[] scopes = DEFAULT_SCOPES; } 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 index 6a287165dae9..406d713b5755 100644 --- 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 @@ -1,2005 +1,3713 @@ // 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.indexes; +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.HttpPipeline; -import com.azure.core.http.rest.PagedFlux; +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.Context; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; 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.DocumentKeysOrIds; -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.ListIndexersResult; -import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; -import com.azure.search.documents.indexes.implementation.models.SkillNames; -import com.azure.search.documents.indexes.models.CreateOrUpdateDataSourceConnectionOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateIndexerOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateSkillsetOptions; +import com.azure.search.documents.implementation.SearchIndexerClientImpl; +import com.azure.search.documents.indexes.models.DocumentKeysOrIds; import com.azure.search.documents.indexes.models.IndexerResyncBody; +import com.azure.search.documents.indexes.models.ListDataSourcesResult; +import com.azure.search.documents.indexes.models.ListIndexersResult; +import com.azure.search.documents.indexes.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 com.azure.search.documents.indexes.models.SkillNames; +import java.util.Collections; import java.util.List; -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; +import java.util.Objects; +import java.util.stream.Collectors; +import reactor.core.publisher.Mono; /** - * 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 + * Initializes a new instance of the asynchronous SearchIndexerClient type. */ @ServiceClient(builder = SearchIndexerClientBuilder.class, isAsync = true) -public class SearchIndexerAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexerAsyncClient.class); +public final class SearchIndexerAsyncClient { - /** - * Search REST API Version - */ - private final SearchServiceVersion serviceVersion; + @Generated + private final SearchIndexerClientImpl serviceClient; /** - * 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. + * Initializes an instance of SearchIndexerAsyncClient class. + * + * @param serviceClient the service client implementation. */ - 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()); + @Generated + SearchIndexerAsyncClient(SearchIndexerClientImpl serviceClient) { + this.serviceClient = serviceClient; } /** - * Gets the {@link HttpPipeline} powering this client. + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. * * @return the pipeline. */ HttpPipeline getHttpPipeline() { - return this.httpPipeline; + return serviceClient.getHttpPipeline(); } /** - * Gets the endpoint for the Azure AI Search service. + * Gets the endpoint used to communicate with the Azure AI Search service. * - * @return the endpoint value. + * @return The endpoint. */ public String getEndpoint() { - return this.endpoint; + return serviceClient.getEndpoint(); } /** - * 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());
-     * 
- * + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. * - * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create or update. - * @return the data source that was created or updated. + * @return The service version. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono - createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection dataSource) { - return createOrUpdateDataSourceConnectionWithResponse(dataSource, false).map(Response::getValue); + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); } /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

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

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 {@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. + * @param name 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> createOrUpdateDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged) { - return withContext( - context -> createOrUpdateDataSourceConnectionWithResponse(dataSource, onlyIfUnchanged, null, context)); + Mono> createOrUpdateDataSourceConnectionWithResponse(String name, BinaryData dataSource, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateDataSourceConnectionWithResponseAsync(name, dataSource, requestOptions); } /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

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

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource")
-     *     .flatMap(dataSource -> {
-     *         dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer"));
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateDataSourceConnectionWithResponse(
-     *             new CreateOrUpdateDataSourceConnectionOptions(dataSource)
-     *                 .setOnlyIfUnchanged(true)
-     *                 .setCacheResetRequirementsIgnored(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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 options The options used to create or update the - * {@link SearchIndexerDataSourceConnection data source connection}. - * @return a data source response. - * @throws NullPointerException If {@code options} is null. + * @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> - createOrUpdateDataSourceConnectionWithResponse(CreateOrUpdateDataSourceConnectionOptions options) { - if (options == null) { - return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); + public Mono> createOrUpdateDataSourceConnectionWithResponse( + SearchIndexerDataSourceConnection dataSource, RequestOptions requestOptions) { + try { + return this.serviceClient + .createOrUpdateDataSourceConnectionWithResponseAsync(dataSource.getName(), + BinaryData.fromObject(dataSource), requestOptions) + .map(response -> new SimpleResponse<>(response, + response.getValue().toObject(SearchIndexerDataSourceConnection.class))); + } catch (Exception ex) { + return Mono.error(ex); } - - return withContext(context -> createOrUpdateDataSourceConnectionWithResponse(options.getDataSourceConnection(), - options.isOnlyIfUnchanged(), options.isCacheResetRequirementsIgnored(), 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); - } + /** + * 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 name 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> deleteDataSourceConnectionWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteDataSourceConnectionWithResponseAsync(name, requestOptions); } /** - * Creates a new Azure AI Search data source + * Retrieves a datasource definition. + *

Response Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

Create search indexer data source connection named "dataSource".

+ * @param name 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> getDataSourceConnectionWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getDataSourceConnectionWithResponseAsync(name, requestOptions); + } + + /** + * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *             subType: String (Optional)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             indexerPermissionOptions (Optional): [
+     *                 String(userIds/groupIds/rbacScope) (Optional)
+     *             ]
+     *             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. - * @return a Mono which performs the network request upon subscription. + * @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 - createDataSourceConnection(SearchIndexerDataSourceConnection dataSource) { - return createDataSourceConnectionWithResponse(dataSource).map(Response::getValue); + Mono> getDataSourceConnectionsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getDataSourceConnectionsWithResponseAsync(requestOptions); } /** - * Creates a new Azure AI Search data source + * Creates a new datasource. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

Create search indexer data source connection named "dataSource".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 {@link SearchIndexerDataSourceConnection} to create. - * @return a Mono which performs the network request upon subscription. + * @param dataSourceConnection 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> - createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSource) { - return withContext(context -> this.createDataSourceConnectionWithResponse(dataSource, context)); + public Mono> createDataSourceConnectionWithResponse(BinaryData dataSourceConnection, + RequestOptions requestOptions) { + return this.serviceClient.createDataSourceConnectionWithResponseAsync(dataSourceConnection, requestOptions); } - Mono> - createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSource, Context context) { - try { - return restClient.getDataSources() - .createWithResponseAsync(dataSource, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * Resets the change tracking state associated with an indexer. + * + * @param name 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> resetIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.resetIndexerWithResponseAsync(name, requestOptions); } /** - * Retrieves a DataSource from an Azure AI Search service. + * Resync selective options from the datasource to be re-ingested by the indexer.". + *

Request Body Schema

* - *

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()));
+     * {@code
+     * {
+     *     options (Optional): [
+     *         String(permissions) (Optional)
+     *     ]
+     * }
+     * }
      * 
- * * - * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} to retrieve. - * @return the DataSource. + * @param name The name of the indexer. + * @param indexerResync The definition of the indexer resync options. + * @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 getDataSourceConnection(String dataSourceName) { - return getDataSourceConnectionWithResponse(dataSourceName).map(Response::getValue); + public Mono> resyncWithResponse(String name, BinaryData indexerResync, + RequestOptions requestOptions) { + return this.serviceClient.resyncWithResponseAsync(name, indexerResync, requestOptions); } /** - * Retrieves a DataSource from an Azure AI Search service. - * - *

Code Sample

- * - *

Get search indexer data source connection named "dataSource".

+ * 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

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     documentKeys (Optional): [
+     *         String (Optional)
+     *     ]
+     *     datasourceDocumentIds (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
      * 
- * * - * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} to retrieve. - * @return a response containing the DataSource. + * @param name 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> - getDataSourceConnectionWithResponse(String dataSourceName) { - return withContext(context -> getDataSourceConnectionWithResponse(dataSourceName, context)); + public Mono> resetDocumentsWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.resetDocumentsWithResponseAsync(name, requestOptions); } - Mono> getDataSourceConnectionWithResponse(String dataSourceName, - Context context) { - try { - return restClient.getDataSources() - .getWithResponseAsync(dataSourceName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * Runs an indexer on-demand. + * + * @param name 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> runIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.runIndexerWithResponseAsync(name, requestOptions); } /** - * List all DataSources from an Azure AI Search service. + * 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 Sample

+ *
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
* - *

List all search indexer data source connections.

+ *

Response Body Schema

* - * *
-     * 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())
-     *     );
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @return a list of DataSources + * @param name 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.COLLECTION) - public PagedFlux listDataSourceConnections() { - try { - return new PagedFlux<>( - () -> withContext(context -> this.listDataSourceConnectionsWithResponse(null, context)) - .map(MappingUtils::mapPagedDataSources)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> createOrUpdateIndexerWithResponse(String name, BinaryData indexer, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateIndexerWithResponseAsync(name, indexer, requestOptions); } /** - * List all DataSource names from an Azure AI Search service. + * 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 Sample

+ *
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
* - *

List all search indexer data source connection names.

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listDataSourceConnectionNames()
-     *     .subscribe(dataSourceName -> System.out.printf("The dataSource name is %s.%n", dataSourceName));
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @return a list of DataSource names + * @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.COLLECTION) - public PagedFlux listDataSourceConnectionNames() { + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createOrUpdateIndexerWithResponse(SearchIndexer indexer, + RequestOptions requestOptions) { try { - return new PagedFlux<>( - () -> withContext(context -> this.listDataSourceConnectionsWithResponse("name", context)) - .map(MappingUtils::mapPagedDataSourceNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); + return this.serviceClient + .createOrUpdateIndexerWithResponseAsync(indexer.getName(), BinaryData.fromObject(indexer), + requestOptions) + .map(response -> new SimpleResponse<>(response, response.getValue().toObject(SearchIndexer.class))); + } catch (Exception ex) { + return Mono.error(ex); } } - private Mono> listDataSourceConnectionsWithResponse(String select, - Context context) { - return restClient.getDataSources() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); + /** + * 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 name 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> deleteIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteIndexerWithResponseAsync(name, requestOptions); } /** - * Delete a DataSource - * - *

Code Sample

- * - *

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

+ * Retrieves an indexer definition. + *

Response Body Schema

* - * *
-     * SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnection("dataSource")
-     *     .subscribe();
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} for deletion - * @return a void Mono + * @param name 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 deleteDataSourceConnection(String dataSourceName) { - return withContext( - context -> deleteDataSourceConnectionWithResponse(dataSourceName, null, context).flatMap(FluxUtil::toMono)); + public Mono> getIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexerWithResponseAsync(name, requestOptions); } /** - * Deletes an Azure AI Search data source. + * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - *

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()));
+     * {@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: Object (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: Object (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): {
+     *                 id: String (Optional)
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (Optional)
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @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 + * @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> 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); - } + Mono> getIndexersWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getIndexersWithResponseAsync(requestOptions); } /** - * Creates a new Azure AI Search indexer. - * - *

Code Sample

+ * Lists all indexers available for a search service. * - *

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. + * @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. + * @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 Mono createIndexer(SearchIndexer indexer) { - return createIndexerWithResponse(indexer).map(Response::getValue); + public Mono> listIndexersWithResponse(RequestOptions requestOptions) { + return getIndexersWithResponse(requestOptions) + .map(response -> new SimpleResponse<>(response, response.getValue().toObject(ListIndexersResult.class))); } /** - * Creates a new Azure AI Search indexer. + * Creates a new indexer. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
* - *

Create search indexer named "searchIndexer".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @param indexer definition of the indexer to create - * @return a response containing the created Indexer. + * @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> 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); - } + public Mono> createIndexerWithResponse(BinaryData indexer, RequestOptions requestOptions) { + return this.serviceClient.createIndexerWithResponseAsync(indexer, requestOptions); } /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer named "searchIndexer".

+ * Returns the current status and execution history of an indexer. + *

Response Body Schema

* - * *
-     * 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()));
+     * {@code
+     * {
+     *     name: String (Required)
+     *     status: String(unknown/error/running) (Required)
+     *     runtime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs/resync) (Optional)
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (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)
+     *     }
+     *     currentState (Optional): {
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (Optional)
+     *         allDocsInitialTrackingState: String (Optional)
+     *         allDocsFinalTrackingState: String (Optional)
+     *         resetDocsInitialTrackingState: String (Optional)
+     *         resetDocsFinalTrackingState: String (Optional)
+     *         resyncInitialTrackingState: String (Optional)
+     *         resyncFinalTrackingState: String (Optional)
+     *         resetDocumentKeys (Optional): [
+     *             String (Optional)
+     *         ]
+     *         resetDatasourceDocumentIds (Optional): [
+     *             String (Optional)
+     *         ]
+     *     }
+     * }
+     * }
      * 
- * * - * @param indexer The definition of the indexer to create or update. - * @return a response containing the created Indexer. + * @param name 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 createOrUpdateIndexer(SearchIndexer indexer) { - return createOrUpdateIndexerWithResponse(indexer, false).map(Response::getValue); + public Mono> getIndexerStatusWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexerStatusWithResponseAsync(name, requestOptions); } /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. + * 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 Sample

+ *
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
+     * 
* - *

Create or update search indexer named "searchIndexer".

+ *

Response Body Schema

* - * *
-     * 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()));
+     * {@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 (Required)
+     *                         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: Object (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: Object (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 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. + * @param name 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> createOrUpdateIndexerWithResponse(SearchIndexer indexer, - boolean onlyIfUnchanged) { - return withContext(context -> createOrUpdateIndexerWithResponse(indexer, onlyIfUnchanged, null, null, context)); + Mono> createOrUpdateSkillsetWithResponse(String name, BinaryData skillset, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateSkillsetWithResponseAsync(name, skillset, requestOptions); } /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. + * 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 Sample

+ *
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
+     * 
* - *

Create or update search indexer named "searchIndexer".

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer")
-     *     .flatMap(searchIndexerFromService -> {
-     *         searchIndexerFromService.setFieldMappings(Collections.singletonList(
-     *             new FieldMapping("hotelName").setTargetFieldName("HotelName")));
-     *         return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexerWithResponse(
-     *             new CreateOrUpdateIndexerOptions(searchIndexerFromService)
-     *                 .setOnlyIfUnchanged(true)
-     *                 .setCacheReprocessingChangeDetectionDisabled(false)
-     *                 .setCacheResetRequirementsIgnored(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()));
+     * {@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 (Required)
+     *                         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: Object (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: Object (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 options The options used to create or update the {@link SearchIndexer indexer}. - * @return a response containing the created Indexer. - * @throws NullPointerException If {@code options} is null. + * @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> createOrUpdateIndexerWithResponse(CreateOrUpdateIndexerOptions options) { - if (options == null) { - return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); - } - - return withContext(context -> createOrUpdateIndexerWithResponse(options.getIndexer(), - options.isOnlyIfUnchanged(), options.isCacheReprocessingChangeDetectionDisabled(), - options.isCacheResetRequirementsIgnored(), 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; + public Mono> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, + RequestOptions requestOptions) { try { - return restClient.getIndexers() - .createOrUpdateWithResponseAsync(indexer.getName(), indexer, ifMatch, null, ignoreResetRequirements, - disableCacheReprocessingChangeDetection, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return this.serviceClient + .createOrUpdateSkillsetWithResponseAsync(skillset.getName(), BinaryData.fromObject(skillset), + requestOptions) + .map(response -> new SimpleResponse<>(response, + response.getValue().toObject(SearchIndexerSkillset.class))); + } catch (Exception ex) { + return Mono.error(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. + * 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 name 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 getIndexer(String indexerName) { - return getIndexerWithResponse(indexerName).map(Response::getValue); + public Mono> deleteSkillsetWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteSkillsetWithResponseAsync(name, requestOptions); } /** - * Retrieves an indexer definition. - * - *

Code Sample

- * - *

Get search indexer with name "searchIndexer".

+ * Retrieves a skillset in a search service. + *

Response Body Schema

* - * *
-     * 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()));
+     * {@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 (Required)
+     *                         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: Object (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: Object (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 indexerName the name of the indexer to retrieve - * @return a response containing the indexer. + * @param name 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> 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); - } + public Mono> getSkillsetWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getSkillsetWithResponseAsync(name, requestOptions); } /** - * Lists all indexers available for an Azure AI Search service. + * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - *

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()));
+     * {@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 (Required)
+     *                                 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: Object (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: Object (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)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @return a response containing all Indexers from the 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 response from a list skillset request along with {@link Response} on successful completion of + * {@link Mono}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listIndexers() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexersWithResponse(null, context)) - .map(MappingUtils::mapPagedSearchIndexers)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono> getSkillsetsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getSkillsetsWithResponseAsync(requestOptions); } /** - * Lists all indexers available for an Azure AI Search service. + * Creates a new skillset in a search service. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
+     * 
* - *

List all search indexer names.

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listIndexerNames()
-     *     .subscribe(indexerName -> System.out.printf("The indexer name is %s.%n", indexerName));
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
      * 
- * * - * @return a response containing all Indexers from the Search service. + * @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.COLLECTION) - public PagedFlux listIndexerNames() { - try { - return new PagedFlux<>(() -> withContext(context -> this.listIndexersWithResponse("name", context)) - .map(MappingUtils::mapPagedSearchIndexerNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } - } - - private Mono> listIndexersWithResponse(String select, Context context) { - return restClient.getIndexers() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> createSkillsetWithResponse(BinaryData skillset, RequestOptions requestOptions) { + return this.serviceClient.createSkillsetWithResponseAsync(skillset, requestOptions); } /** - * Deletes an Azure AI Search indexer. - * - *

Code Sample

+ * Reset an existing skillset in a search service. + *

Request Body Schema

* - *

Delete search indexer named "searchIndexer".

- * - * *
-     * SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexer("searchIndexer")
-     *     .subscribe();
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
      * 
- * * - * @param indexerName the name of the indexer to delete - * @return a response signalling completion. + * @param name 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 deleteIndexer(String indexerName) { - return withContext(context -> deleteIndexerWithResponse(indexerName, null, context).flatMap(FluxUtil::toMono)); + public Mono> resetSkillsWithResponse(String name, BinaryData skillNames, + RequestOptions requestOptions) { + return this.serviceClient.resetSkillsWithResponseAsync(name, skillNames, requestOptions); } /** - * Deletes an Azure AI Search indexer. + * Creates a new datasource or updates a datasource if it already exists. * - *

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. + * @param name 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> deleteIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged) { - if (indexer == null) { - return monoError(LOGGER, new NullPointerException("'indexer' cannot be null.")); + Mono createOrUpdateDataSourceConnection(String name, + SearchIndexerDataSourceConnection dataSource, Boolean skipIndexerResetRequirementForCache, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateDataSourceConnectionWithResponse + 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); } - String eTag = onlyIfUnchanged ? indexer.getETag() : null; - return withContext(context -> deleteIndexerWithResponse(indexer.getName(), eTag, context)); + if (ifMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_MATCH, ifMatch); + } + if (ifNoneMatch != null) { + requestOptions.setHeader(HttpHeaderName.IF_NONE_MATCH, ifNoneMatch); + } + return createOrUpdateDataSourceConnectionWithResponse(name, BinaryData.fromObject(dataSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSourceConnection.class)); } /** - * Deletes an Azure AI Search indexer. + * Creates a new datasource or updates a datasource if it already exists. * - * @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. + * @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}. */ - Mono> deleteIndexerWithResponse(String indexerName, String eTag, Context context) { + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono + createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection dataSource) { try { - return restClient.getIndexers() - .deleteWithResponseAsync(indexerName, eTag, null, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + return createOrUpdateDataSourceConnection(dataSource.getName(), dataSource); + } catch (Exception ex) { + return Mono.error(ex); } } /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

+ * Creates a new datasource or updates a datasource if it already exists. * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.resetIndexer("searchIndexer")
-     *     .subscribe();
-     * 
- * - * - * @param indexerName the name of the indexer to reset - * @return a response signalling completion. + * @param name 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 resetIndexer(String indexerName) { - return resetIndexerWithResponse(indexerName).flatMap(FluxUtil::toMono); + Mono createOrUpdateDataSourceConnection(String name, + SearchIndexerDataSourceConnection dataSource) { + // Generated convenience method for createOrUpdateDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateDataSourceConnectionWithResponse(name, BinaryData.fromObject(dataSource), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSourceConnection.class)); } /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

+ * Deletes a datasource. * - * - *
-     * 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. + * @param name 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> 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); + public Mono deleteDataSourceConnection(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteDataSourceConnectionWithResponse + 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 deleteDataSourceConnectionWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Runs an indexer on-demand. - * - *

Code Sample

- * - *

Run search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.runIndexer("searchIndexer")
-     *     .subscribe();
-     * 
- * + * Deletes a datasource. * - * @param indexerName the name of the indexer to run - * @return a response signalling completion. + * @param name 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 runIndexer(String indexerName) { - return runIndexerWithResponse(indexerName).flatMap(FluxUtil::toMono); + public Mono deleteDataSourceConnection(String name) { + // Generated convenience method for deleteDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteDataSourceConnectionWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Runs an indexer on-demand. - * - *

Code Sample

+ * Retrieves a datasource definition. * - *

Run search indexer named "searchIndexer".

+ * @param name 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 getDataSourceConnection(String name) { + // Generated convenience method for getDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDataSourceConnectionWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSourceConnection.class)); + } + + /** + * Lists all datasources available for a search service. * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.runIndexerWithResponse("searchIndexer")
-     *     .subscribe(response ->
-     *         System.out.println("The status code of the response is " + response.getStatusCode()));
-     * 
- * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono listDataSourceConnections() { + return getDataSourceConnections(); + } + + /** + * Lists the names of all datasources available for a search service. * - * @param indexerName the name of the indexer to run - * @return a response signalling completion. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> runIndexerWithResponse(String indexerName) { - return withContext(context -> runIndexerWithResponse(indexerName, context)); + public Mono> listDataSourceConnectionNames() { + return getDataSourceConnections(Collections.singletonList("name")).map(result -> result.getDataSources() + .stream() + .map(SearchIndexerDataSourceConnection::getName) + .collect(Collectors.toList())); } - 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); + /** + * 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) + Mono getDataSourceConnections(List select) { + // Generated convenience method for getDataSourceConnectionsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); } + return getDataSourceConnectionsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListDataSourcesResult.class)); } /** - * 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()));
-     * 
- * + * Lists all datasources available for a search service. * - * @param indexerName the name of the indexer for which to retrieve status - * @return the indexer execution info. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 getIndexerStatus(String indexerName) { - return getIndexerStatusWithResponse(indexerName).map(Response::getValue); + Mono getDataSourceConnections() { + // Generated convenience method for getDataSourceConnectionsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDataSourceConnectionsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListDataSourcesResult.class)); } /** - * Returns the current status and execution history of an indexer. - * - *

Code Sample

- * - *

Get search indexer status.

+ * Creates a new datasource. * - * - *
-     * 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. + * @param dataSourceConnection 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> getIndexerStatusWithResponse(String indexerName) { - return withContext(context -> getIndexerStatusWithResponse(indexerName, context)); + public Mono + createDataSourceConnection(SearchIndexerDataSourceConnection dataSourceConnection) { + // Generated convenience method for createDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createDataSourceConnectionWithResponse(BinaryData.fromObject(dataSourceConnection), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerDataSourceConnection.class)); } - Mono> getIndexerStatusWithResponse(String indexerName, Context context) { - try { - return restClient.getIndexers() - .getStatusWithResponseAsync(indexerName, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); - } + /** + * Resets the change tracking state associated with an indexer. + * + * @param name 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 resetIndexer(String name) { + // Generated convenience method for resetIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resetIndexerWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. + * Resync selective options from the datasource to be re-ingested by the indexer.". * - * - *
-     * // Reset the documents with keys 1234 and 4321.
-     * SEARCH_INDEXER_ASYNC_CLIENT.resetDocuments("searchIndexer", false, Arrays.asList("1234", "4321"), null)
-     *     // Clear the previous documents to be reset and replace them with documents 1235 and 5231.
-     *     .then(SEARCH_INDEXER_ASYNC_CLIENT.resetDocuments("searchIndexer", true, Arrays.asList("1235", "5321"), null))
-     *     .subscribe();
-     * 
- * - * - * @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 documentKeys Document keys to be reset. - * @param datasourceDocumentIds Datasource document identifiers to be reset. - * @return A response signalling completion. + * @param name The name of the indexer. + * @param indexerResync The definition of the indexer resync options. + * @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 resetDocuments(String indexerName, Boolean overwrite, List documentKeys, - List datasourceDocumentIds) { - return withContext( - context -> resetDocumentsWithResponse(indexerName, overwrite, documentKeys, datasourceDocumentIds, context)) - .map(Response::getValue); + public Mono resync(String name, IndexerResyncBody indexerResync) { + // Generated convenience method for resyncWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resyncWithResponse(name, BinaryData.fromObject(indexerResync), requestOptions).flatMap(FluxUtil::toMono); } /** * Resets specific documents in the datasource to be selectively re-ingested by the indexer. * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer")
-     *     .flatMap(searchIndexer -> SEARCH_INDEXER_ASYNC_CLIENT.resetDocumentsWithResponse(searchIndexer, false,
-     *         Arrays.asList("1234", "4321"), null)
-     *         .flatMap(resetDocsResult -> {
-     *             System.out.printf("Requesting documents to be reset completed with status code %d.%n",
-     *                 resetDocsResult.getStatusCode());
-     *
-     *             // Clear the previous documents to be reset and replace them with documents 1235 and 5231.
-     *             return SEARCH_INDEXER_ASYNC_CLIENT.resetDocumentsWithResponse(searchIndexer, true,
-     *                 Arrays.asList("1235", "5321"), null);
-     *         }))
-     *     .subscribe(resetDocsResult ->
-     *         System.out.printf("Overwriting the documents to be reset completed with status code %d.%n",
-     *             resetDocsResult.getStatusCode()));
-     * 
- * - * - * @param indexer 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 + * @param name 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 documentKeys Document keys to be reset. - * @param datasourceDocumentIds Datasource document identifiers to be reset. - * @return A response signalling completion. - * @throws NullPointerException If {@code indexer} is null. + * @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> resetDocumentsWithResponse(SearchIndexer indexer, Boolean overwrite, - List documentKeys, List datasourceDocumentIds) { - if (indexer == null) { - return monoError(LOGGER, new NullPointerException("'indexer' cannot be null.")); + public Mono resetDocuments(String name, Boolean overwrite, DocumentKeysOrIds keysOrIds) { + // Generated convenience method for resetDocumentsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (overwrite != null) { + requestOptions.addQueryParam("overwrite", String.valueOf(overwrite), false); } - - return withContext(context -> resetDocumentsWithResponse(indexer.getName(), overwrite, documentKeys, - datasourceDocumentIds, context)); - } - - Mono> resetDocumentsWithResponse(String indexerName, Boolean overwrite, List documentKeys, - List datasourceDocumentIds, Context context) { - try { - DocumentKeysOrIds documentKeysOrIds - = new DocumentKeysOrIds().setDocumentKeys(documentKeys).setDatasourceDocumentIds(datasourceDocumentIds); - - return restClient.getIndexers() - .resetDocsWithResponseAsync(indexerName, overwrite, documentKeysOrIds, null, context); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + if (keysOrIds != null) { + requestOptions.setBody(BinaryData.fromObject(keysOrIds)); } + return resetDocumentsWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * 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()));
-     * 
- * + * Resets specific documents in the datasource to be selectively re-ingested by the indexer. * - * @param skillset definition of the skillset containing one or more cognitive skills - * @return the created Skillset. + * @param name 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 createSkillset(SearchIndexerSkillset skillset) { - return createSkillsetWithResponse(skillset).map(Response::getValue); + public Mono resetDocuments(String name) { + // Generated convenience method for resetDocumentsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resetDocumentsWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * 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()));
-     * 
- * + * Runs an indexer on-demand. * - * @param skillset definition of the skillset containing one or more cognitive skills - * @return a response containing the created Skillset. + * @param name 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> createSkillsetWithResponse(SearchIndexerSkillset skillset) { - return withContext(context -> createSkillsetWithResponse(skillset, context)); + public Mono runIndexer(String name) { + // Generated convenience method for runIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return runIndexerWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } - Mono> createSkillsetWithResponse(SearchIndexerSkillset skillset, Context context) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); + /** + * Creates a new indexer or updates an indexer if it already exists. + * + * @param name 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) + Mono createOrUpdateIndexer(String name, SearchIndexer indexer, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateIndexerWithResponse + 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); } - try { - return restClient.getSkillsets() - .createWithResponseAsync(skillset, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + 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 createOrUpdateIndexerWithResponse(name, BinaryData.fromObject(indexer), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); } /** - * Retrieves a skillset definition. - * - *

Code Sample

+ * Creates a new indexer or updates an indexer if it already exists. * - *

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. + * @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}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getSkillset(String skillsetName) { - return getSkillsetWithResponse(skillsetName).map(Response::getValue); + public Mono createOrUpdateIndexer(SearchIndexer indexer) { + try { + return createOrUpdateIndexer(indexer.getName(), indexer); + } catch (Exception ex) { + return Mono.error(ex); + } } /** - * Retrieves a skillset definition. - * - *

Code Sample

- * - *

Get search indexer skillset "searchIndexerSkillset".

+ * Creates a new indexer or updates an indexer if it already exists. * - * - *
-     * 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. + * @param name 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> getSkillsetWithResponse(String skillsetName) { - return withContext(context -> getSkillsetWithResponse(skillsetName, context)); + Mono createOrUpdateIndexer(String name, SearchIndexer indexer) { + // Generated convenience method for createOrUpdateIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateIndexerWithResponse(name, BinaryData.fromObject(indexer), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); } - 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); + /** + * Deletes an indexer. + * + * @param name 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 deleteIndexer(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteIndexerWithResponse + 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 deleteIndexerWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Lists all skillsets available for an Azure AI Search service. + * Deletes an indexer. * - *

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. + * @param name 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. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSkillsets() { - try { - return new PagedFlux<>(() -> withContext(context -> listSkillsetsWithResponse(null, context)) - .map(MappingUtils::mapPagedSkillsets)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); - } + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono deleteIndexer(String name) { + // Generated convenience method for deleteIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteIndexerWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Lists all skillset names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer skillset names.

+ * Retrieves an indexer definition. * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.listSkillsetNames()
-     *     .subscribe(skillsetName -> System.out.printf("The indexer skillset name is %s.%n", skillsetName));
-     * 
- * + * @param name 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 getIndexer(String name) { + // Generated convenience method for getIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexerWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); + } + + /** + * Lists all indexers available for a search service. * - * @return a reactive response emitting the list of skillset names. + * @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}. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listSkillsetNames() { - try { - return new PagedFlux<>(() -> withContext(context -> listSkillsetsWithResponse("name", context)) - .map(MappingUtils::mapPagedSkillsetNames)); - } catch (RuntimeException ex) { - return pagedFluxError(LOGGER, ex); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Mono getIndexers(List select) { + // Generated convenience method for getIndexersWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); } + return getIndexersWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListIndexersResult.class)); } - private Mono> listSkillsetsWithResponse(String select, Context context) { - return this.restClient.getSkillsets() - .listWithResponseAsync(select, null, context) - .onErrorMap(MappingUtils::exceptionMapper); + /** + * 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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono listIndexers() { + return getIndexers(); } /** - * Creates a new Azure AI Search skillset or updates a skillset if it already exists. - * - *

Code Sample

+ * Lists all indexer names available for a search service. * - *

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. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateSkillset(SearchIndexerSkillset skillset) { - return createOrUpdateSkillsetWithResponse(skillset, false).map(Response::getValue); + public Mono> listIndexerNames() { + return getIndexers(Collections.singletonList("name")) + .map(result -> result.getIndexers().stream().map(SearchIndexer::getName).collect(Collectors.toList())); } /** - * 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()));
-     * 
- * + * Lists all indexers available for a search service. * - * @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. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged) { - return withContext( - context -> createOrUpdateSkillsetWithResponse(skillset, onlyIfUnchanged, null, null, context)); + Mono getIndexers() { + // Generated convenience method for getIndexersWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexersWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListIndexersResult.class)); } /** - * 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(
-     *             new CreateOrUpdateSkillsetOptions(indexerSkillset)
-     *                 .setOnlyIfUnchanged(true)
-     *                 .setCacheReprocessingChangeDetectionDisabled(false)
-     *                 .setCacheResetRequirementsIgnored(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()));
-     * 
- * + * Creates a new indexer. * - * @param options The options used to create or update the {@link SearchIndexerSkillset skillset}. - * @return a response containing the skillset that was created or updated. - * @throws NullPointerException If {@code options} is null. + * @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> - createOrUpdateSkillsetWithResponse(CreateOrUpdateSkillsetOptions options) { - if (options == null) { - return monoError(LOGGER, new NullPointerException("'options' cannot be null.")); - } + public Mono createIndexer(SearchIndexer indexer) { + // Generated convenience method for createIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createIndexerWithResponse(BinaryData.fromObject(indexer), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexer.class)); + } - return withContext(context -> createOrUpdateSkillsetWithResponse(options.getSkillset(), - options.isOnlyIfUnchanged(), options.isCacheReprocessingChangeDetectionDisabled(), - options.isCacheResetRequirementsIgnored(), context)); + /** + * Returns the current status and execution history of an indexer. + * + * @param name 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 getIndexerStatus(String name) { + // Generated convenience method for getIndexerStatusWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexerStatusWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerStatus.class)); } - Mono> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged, Boolean disableCacheReprocessingChangeDetection, Boolean ignoreResetRequirements, - Context context) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); + /** + * Creates a new skillset in a search service or updates the skillset if it already exists. + * + * @param name 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) + Mono createOrUpdateSkillset(String name, SearchIndexerSkillset skillset, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateSkillsetWithResponse + 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); } - 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); + 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 createOrUpdateSkillsetWithResponse(name, BinaryData.fromObject(skillset), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); } /** - * Deletes a cognitive skillset in an Azure AI Search service. + * Creates a new skillset in a search service or updates the skillset if it already exists. * - *

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. + * @param name 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 deleteSkillset(String skillsetName) { - return withContext( - context -> deleteSkillsetWithResponse(skillsetName, null, context).flatMap(FluxUtil::toMono)); + Mono createOrUpdateSkillset(String name, SearchIndexerSkillset skillset) { + // Generated convenience method for createOrUpdateSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateSkillsetWithResponse(name, BinaryData.fromObject(skillset), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); } /** - * Deletes a cognitive skillset in an Azure AI Search service. + * Creates a new skillset in a search service or updates the skillset if it already exists. * - *

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. + * @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}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> deleteSkillsetWithResponse(SearchIndexerSkillset skillset, boolean onlyIfUnchanged) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); + public Mono createOrUpdateSkillset(SearchIndexerSkillset skillset) { + try { + return createOrUpdateSkillset(skillset.getName(), skillset); + } catch (Exception ex) { + return Mono.error(ex); } - 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); + /** + * Deletes a skillset in a search service. + * + * @param name 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 deleteSkillset(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteSkillsetWithResponse + 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 deleteSkillsetWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Resync selective options from the datasource to be re-ingested by the indexer. + * Deletes a skillset in a search service. * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync parameter. + * @param name The name of the skillset. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 resync(String indexerName, IndexerResyncBody indexerResync) { - return resyncWithResponse(indexerName, indexerResync).flatMap(FluxUtil::toMono); + public Mono deleteSkillset(String name) { + // Generated convenience method for deleteSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return deleteSkillsetWithResponse(name, requestOptions).flatMap(FluxUtil::toMono); } /** - * Resync selective options from the datasource to be re-ingested by the indexer. + * Retrieves a skillset in a search service. * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync parameter. + * @param name The name of the skillset. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 {@link Response} on successful completion of {@link Mono}. + * @return a list of skills on successful completion of {@link Mono}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resyncWithResponse(String indexerName, IndexerResyncBody indexerResync) { - return withContext(context -> resyncWithResponseAsync(indexerName, indexerResync, context)); + public Mono getSkillset(String name) { + // Generated convenience method for getSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSkillsetWithResponse(name, requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); } - Mono> resyncWithResponseAsync(String indexerName, IndexerResyncBody indexerResync, Context context) { - try { - return restClient.getIndexers() - .resyncWithResponseAsync(indexerName, indexerResync, null, context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * 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) + Mono getSkillsets(List select) { + // Generated convenience method for getSkillsetsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); } + return getSkillsetsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSkillsetsResult.class)); } /** - * Resets skills in an existing skillset in an Azure AI Search service. - * - * - *
-     * // Reset the "myOcr" and "myText" skills.
-     * SEARCH_INDEXER_ASYNC_CLIENT.resetSkills("searchIndexerSkillset", Arrays.asList("myOcr", "myText"))
-     *     .subscribe();
-     * 
- * + * List all skillsets in a search service. * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The skills to reset. - * @return A response signalling completion. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 resetSkills(String skillsetName, List skillNames) { - return withContext( - context -> resetSkillsWithResponse(skillsetName, skillNames, context).flatMap(FluxUtil::toMono)); + Mono getSkillsets() { + // Generated convenience method for getSkillsetsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSkillsetsWithResponse(requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(ListSkillsetsResult.class)); } /** - * Resets skills in an existing skillset in an Azure AI Search service. - * - * - *
-     * SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset")
-     *     .flatMap(searchIndexerSkillset -> SEARCH_INDEXER_ASYNC_CLIENT.resetSkillsWithResponse(searchIndexerSkillset,
-     *         Arrays.asList("myOcr", "myText")))
-     *     .subscribe(resetSkillsResponse -> System.out.printf("Resetting skills completed with status code %d.%n",
-     *         resetSkillsResponse.getStatusCode()));
-     * 
- * + * List all skillsets in a search service. * - * @param skillset The skillset to reset. - * @param skillNames The skills to reset. - * @return A response signalling completion. - * @throws NullPointerException If {@code skillset} is null. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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}. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> resetSkillsWithResponse(SearchIndexerSkillset skillset, List skillNames) { - if (skillset == null) { - return monoError(LOGGER, new NullPointerException("'skillset' cannot be null.")); - } + public Mono listSkillsets() { + return getSkillsets(); + } - return withContext(context -> resetSkillsWithResponse(skillset.getName(), skillNames, context)); + /** + * List the names of 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}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> listSkillsetNames() { + return getSkillsets(Collections.singletonList("name")).map( + result -> result.getSkillsets().stream().map(SearchIndexerSkillset::getName).collect(Collectors.toList())); } - Mono> resetSkillsWithResponse(String skillsetName, List skillNames, Context context) { - try { - return restClient.getSkillsets() - .resetSkillsWithResponseAsync(skillsetName, new SkillNames().setSkillNames(skillNames), null, context); - } catch (RuntimeException ex) { - return monoError(LOGGER, ex); + /** + * 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 createSkillset(SearchIndexerSkillset skillset) { + // Generated convenience method for createSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createSkillsetWithResponse(BinaryData.fromObject(skillset), requestOptions).flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(SearchIndexerSkillset.class)); + } - } + /** + * Reset an existing skillset in a search service. + * + * @param name 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 name, SkillNames skillNames) { + // Generated convenience method for resetSkillsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return resetSkillsWithResponse(name, BinaryData.fromObject(skillNames), requestOptions) + .flatMap(FluxUtil::toMono); } } 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 index 6902704d7cfd..48cb07d9ea24 100644 --- 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 @@ -1,1882 +1,3630 @@ // 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.indexes; +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.HttpPipeline; -import com.azure.core.http.rest.PagedIterable; +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.Context; -import com.azure.core.util.logging.ClientLogger; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.BinaryData; 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.DocumentKeysOrIds; -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.ListIndexersResult; -import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; -import com.azure.search.documents.indexes.implementation.models.SkillNames; -import com.azure.search.documents.indexes.models.CreateOrUpdateDataSourceConnectionOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateIndexerOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateSkillsetOptions; +import com.azure.search.documents.implementation.SearchIndexerClientImpl; +import com.azure.search.documents.indexes.models.DocumentKeysOrIds; import com.azure.search.documents.indexes.models.IndexerResyncBody; +import com.azure.search.documents.indexes.models.ListDataSourcesResult; +import com.azure.search.documents.indexes.models.ListIndexersResult; +import com.azure.search.documents.indexes.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 com.azure.search.documents.indexes.models.SkillNames; +import java.util.Collections; import java.util.List; import java.util.Objects; +import java.util.stream.Collectors; /** - * 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 + * Initializes a new instance of the synchronous SearchIndexerClient type. */ @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; +public final class SearchIndexerClient { - /** - * The underlying AutoRest client used to interact with the Search service - */ - private final SearchServiceClientImpl restClient; + @Generated + private final SearchIndexerClientImpl serviceClient; /** - * The pipeline that powers this client. + * Initializes an instance of SearchIndexerClient class. + * + * @param serviceClient the service client implementation. */ - 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()); + @Generated + SearchIndexerClient(SearchIndexerClientImpl serviceClient) { + this.serviceClient = serviceClient; } /** - * Gets the {@link HttpPipeline} powering this client. + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. * * @return the pipeline. */ HttpPipeline getHttpPipeline() { - return this.httpPipeline; + return serviceClient.getHttpPipeline(); } /** - * Gets the endpoint for the Azure AI Search service. + * Gets the endpoint used to communicate with the Azure AI Search service. * - * @return the endpoint value. + * @return The endpoint. */ public String getEndpoint() { - return this.endpoint; + return serviceClient.getEndpoint(); } /** - * 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".

+ * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. * - * - *
-     * 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. + * @return The service version. */ - @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerDataSourceConnection - createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection dataSourceConnection) { - return createOrUpdateDataSourceConnectionWithResponse(dataSourceConnection, false, Context.NONE).getValue(); + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); } /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

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

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 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. + * @param name 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 createOrUpdateDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSourceConnection, boolean onlyIfUnchanged, Context context) { - return createOrUpdateDataSourceConnectionWithResponse(dataSourceConnection, onlyIfUnchanged, null, context); + Response createOrUpdateDataSourceConnectionWithResponse(String name, BinaryData dataSource, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateDataSourceConnectionWithResponse(name, dataSource, requestOptions); } /** - * Creates a new Azure AI Search data source or updates a data source if it already exists. + * 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 Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

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

+ *

Response Body Schema

* - * *
-     * SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource");
-     * dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer"));
-     * CreateOrUpdateDataSourceConnectionOptions options = new CreateOrUpdateDataSourceConnectionOptions(dataSource)
-     *     .setOnlyIfUnchanged(true)
-     *     .setCacheResetRequirementsIgnored(true);
-     *
-     * Response<SearchIndexerDataSourceConnection> updateDataSource = SEARCH_INDEXER_CLIENT
-     *     .createOrUpdateDataSourceConnectionWithResponse(options, 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 options The options used to create or update the {@link SearchIndexerDataSourceConnection data source - * connection}. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a data source response. - * @throws NullPointerException If {@code options} is null. + * @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 createOrUpdateDataSourceConnectionWithResponse( - CreateOrUpdateDataSourceConnectionOptions options, Context context) { - Objects.requireNonNull(options, "'options' cannot be null."); - - return createOrUpdateDataSourceConnectionWithResponse(options.getDataSourceConnection(), - options.isOnlyIfUnchanged(), options.isCacheResetRequirementsIgnored(), context); + SearchIndexerDataSourceConnection dataSource, RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateDataSourceConnectionWithResponse( + dataSource.getName(), BinaryData.fromObject(dataSource), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SearchIndexerDataSourceConnection.class)); } - 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); + /** + * 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 name 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 deleteDataSourceConnectionWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteDataSourceConnectionWithResponse(name, requestOptions); } /** - * Creates a new Azure AI Search data source - * - *

Code Sample

- * - *

Create search indexer data source connection named "dataSource".

+ * Retrieves a datasource definition. + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 dataSourceConnection The definition of the data source to create - * @return the data source that was created. + * @param name 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 SearchIndexerDataSourceConnection - createDataSourceConnection(SearchIndexerDataSourceConnection dataSourceConnection) { - return createDataSourceConnectionWithResponse(dataSourceConnection, Context.NONE).getValue(); + public Response getDataSourceConnectionWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getDataSourceConnectionWithResponse(name, requestOptions); } /** - * Creates a new Azure AI Search data source - * - *

Code Sample

- * - *

Create search indexer data source connection named "dataSource".

+ * Lists all datasources available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     value (Required): [
+     *          (Required){
+     *             name: String (Required)
+     *             description: String (Optional)
+     *             type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *             subType: String (Optional)
+     *             credentials (Required): {
+     *                 connectionString: String (Optional)
+     *             }
+     *             container (Required): {
+     *                 name: String (Required)
+     *                 query: String (Optional)
+     *             }
+     *             identity (Optional): {
+     *                 @odata.type: String (Required)
+     *             }
+     *             indexerPermissionOptions (Optional): [
+     *                 String(userIds/groupIds/rbacScope) (Optional)
+     *             ]
+     *             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 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. + * @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 createDataSourceConnectionWithResponse( - SearchIndexerDataSourceConnection dataSourceConnection, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDataSources().createWithResponse(dataSourceConnection, null, context), LOGGER); + Response getDataSourceConnectionsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getDataSourceConnectionsWithResponse(requestOptions); } /** - * Retrieves a DataSource from an Azure AI Search service. + * Creates a new datasource. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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)
+     *     }
+     * }
+     * }
+     * 
* - *

Get search indexer data source connection named "dataSource".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     description: String (Optional)
+     *     type: String(azuresql/cosmosdb/azureblob/azuretable/mysql/adlsgen2/onelake/sharepoint) (Required)
+     *     subType: String (Optional)
+     *     credentials (Required): {
+     *         connectionString: String (Optional)
+     *     }
+     *     container (Required): {
+     *         name: String (Required)
+     *         query: String (Optional)
+     *     }
+     *     identity (Optional): {
+     *         @odata.type: String (Required)
+     *     }
+     *     indexerPermissionOptions (Optional): [
+     *         String(userIds/groupIds/rbacScope) (Optional)
+     *     ]
+     *     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 dataSourceConnectionName the name of the data source to retrieve - * @return the DataSource. + * @param dataSourceConnection 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 SearchIndexerDataSourceConnection getDataSourceConnection(String dataSourceConnectionName) { - return getDataSourceConnectionWithResponse(dataSourceConnectionName, Context.NONE).getValue(); + public Response createDataSourceConnectionWithResponse(BinaryData dataSourceConnection, + RequestOptions requestOptions) { + return this.serviceClient.createDataSourceConnectionWithResponse(dataSourceConnection, requestOptions); } /** - * 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());
-     * 
- * + * Resets the change tracking state associated with an indexer. * - * @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. + * @param name 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 - getDataSourceConnectionWithResponse(String dataSourceConnectionName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDataSources().getWithResponse(dataSourceConnectionName, null, context), LOGGER); + public Response resetIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.resetIndexerWithResponse(name, requestOptions); } /** - * List all DataSources from an Azure AI Search service. + * Resync selective options from the datasource to be re-ingested by the indexer.". + *

Request Body Schema

* - *

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());
-     * }
+     * {@code
+     * {
+     *     options (Optional): [
+     *         String(permissions) (Optional)
+     *     ]
+     * }
+     * }
      * 
- * * - * @return a list of DataSources + * @param name The name of the indexer. + * @param indexerResync The definition of the indexer resync options. + * @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.COLLECTION) - public PagedIterable listDataSourceConnections() { - return listDataSourceConnections(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response resyncWithResponse(String name, BinaryData indexerResync, RequestOptions requestOptions) { + return this.serviceClient.resyncWithResponse(name, indexerResync, requestOptions); } /** - * List all DataSources from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connections.

+ * 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

* - * *
-     * 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());
-     * }
+     * {@code
+     * {
+     *     documentKeys (Optional): [
+     *         String (Optional)
+     *     ]
+     *     datasourceDocumentIds (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
      * 
- * - * - * @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.mapPagedDataSources(listDataSourceConnectionsWithResponse(null, context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } + * + * @param name 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 resetDocumentsWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.resetDocumentsWithResponse(name, requestOptions); } - private Response listDataSourceConnectionsWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getDataSources().listWithResponse(select, null, context), LOGGER); + /** + * Runs an indexer on-demand. + * + * @param name 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 runIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.runIndexerWithResponse(name, requestOptions); } /** - * List all DataSource names from an Azure AI Search service. + * 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 Sample

+ *
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
* - *

List all search indexer data source connection names.

+ *

Response Body Schema

* - * *
-     * PagedIterable<String> dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnectionNames();
-     * for (String dataSourceName: dataSources) {
-     *     System.out.printf("The dataSource name is %s.%n", dataSourceName);
-     * }
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @return a list of DataSources names + * @param name 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.COLLECTION) - public PagedIterable listDataSourceConnectionNames() { - return listDataSourceConnectionNames(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + Response createOrUpdateIndexerWithResponse(String name, BinaryData indexer, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateIndexerWithResponse(name, indexer, requestOptions); } /** - * List all DataSources names from an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer data source connection names.

+ * 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

* - * *
-     * 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);
-     * }
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * - * - * @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 - .mapPagedDataSourceNames(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".

+ *

Response Body Schema

* - * *
-     * SEARCH_INDEXER_CLIENT.deleteDataSourceConnection("dataSource");
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @param dataSourceConnectionName the name of the data source to be deleted + * @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 void deleteDataSourceConnection(String dataSourceConnectionName) { - deleteDataSourceConnectionWithResponse(new SearchIndexerDataSourceConnection(dataSourceConnectionName), false, - Context.NONE); + public Response createOrUpdateIndexerWithResponse(SearchIndexer indexer, + RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateIndexerWithResponse(indexer.getName(), + BinaryData.fromObject(indexer), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SearchIndexer.class)); } /** - * Delete a DataSource with Response - * - *

Code Sample

- * - *

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

+ * 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 name 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 deleteIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteIndexerWithResponse(name, requestOptions); + } + + /** + * Retrieves an indexer definition. + *

Response Body Schema

* - * *
-     * 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());
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @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 + * @param name 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 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); + public Response getIndexerWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexerWithResponse(name, requestOptions); } /** - * Creates a new Azure AI Search indexer. - * - *

Code Sample

+ * Lists all indexers available for a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - *

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());
+     * {@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: Object (Required)
+     *                     }
+     *                 }
+     *             }
+     *             fieldMappings (Optional): [
+     *                  (Optional){
+     *                     sourceFieldName: String (Required)
+     *                     targetFieldName: String (Optional)
+     *                     mappingFunction (Optional): {
+     *                         name: String (Required)
+     *                         parameters (Optional): {
+     *                             String: Object (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): {
+     *                 id: String (Optional)
+     *                 storageConnectionString: String (Optional)
+     *                 enableReprocessing: Boolean (Optional)
+     *                 identity (Optional): (recursive schema, see identity above)
+     *             }
+     *         }
+     *     ]
+     * }
+     * }
      * 
- * * - * @param indexer definition of the indexer to create. - * @return the created 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 response from a List Indexers request along with {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexer createIndexer(SearchIndexer indexer) { - return createIndexerWithResponse(indexer, Context.NONE).getValue(); + Response getIndexersWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getIndexersWithResponse(requestOptions); } /** - * Creates a new Azure AI Search indexer. + * Creates a new indexer. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
+     * 
* - *

Create search indexer named "searchIndexer".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@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: Object (Required)
+     *             }
+     *         }
+     *     }
+     *     fieldMappings (Optional): [
+     *          (Optional){
+     *             sourceFieldName: String (Required)
+     *             targetFieldName: String (Optional)
+     *             mappingFunction (Optional): {
+     *                 name: String (Required)
+     *                 parameters (Optional): {
+     *                     String: Object (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): {
+     *         id: String (Optional)
+     *         storageConnectionString: String (Optional)
+     *         enableReprocessing: Boolean (Optional)
+     *         identity (Optional): (recursive schema, see identity above)
+     *     }
+     * }
+     * }
      * 
- * * - * @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. + * @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 createIndexerWithResponse(SearchIndexer indexer, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().createWithResponse(indexer, null, context), LOGGER); + public Response createIndexerWithResponse(BinaryData indexer, RequestOptions requestOptions) { + return this.serviceClient.createIndexerWithResponse(indexer, requestOptions); } /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. - * - *

Code Sample

- * - *

Create or update search indexer named "searchIndexer".

+ * Returns the current status and execution history of an indexer. + *

Response Body Schema

* - * *
-     * 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());
+     * {@code
+     * {
+     *     name: String (Required)
+     *     status: String(unknown/error/running) (Required)
+     *     runtime (Required): {
+     *         usedSeconds: long (Required)
+     *         remainingSeconds: Long (Optional)
+     *         beginningTime: OffsetDateTime (Required)
+     *         endingTime: OffsetDateTime (Required)
+     *     }
+     *     lastResult (Optional): {
+     *         status: String(transientFailure/success/inProgress/reset) (Required)
+     *         statusDetail: String(resetDocs/resync) (Optional)
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (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)
+     *     }
+     *     currentState (Optional): {
+     *         mode: String(indexingAllDocs/indexingResetDocs/indexingResync) (Optional)
+     *         allDocsInitialTrackingState: String (Optional)
+     *         allDocsFinalTrackingState: String (Optional)
+     *         resetDocsInitialTrackingState: String (Optional)
+     *         resetDocsFinalTrackingState: String (Optional)
+     *         resyncInitialTrackingState: String (Optional)
+     *         resyncFinalTrackingState: String (Optional)
+     *         resetDocumentKeys (Optional): [
+     *             String (Optional)
+     *         ]
+     *         resetDatasourceDocumentIds (Optional): [
+     *             String (Optional)
+     *         ]
+     *     }
+     * }
+     * }
      * 
- * * - * @param indexer The definition of the indexer to create or update. - * @return a response containing the created Indexer. + * @param name 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 SearchIndexer createOrUpdateIndexer(SearchIndexer indexer) { - return createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); + public Response getIndexerStatusWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getIndexerStatusWithResponse(name, requestOptions); } /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. + * 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 Sample

+ *
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
+     * 
* - *

Create or update search indexer named "searchIndexer".

+ *

Response Body Schema

* - * *
-     * 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());
+     * {@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 (Required)
+     *                         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: Object (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: Object (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 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. + * @param name 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 createOrUpdateIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged, - Context context) { - return createOrUpdateIndexerWithResponse(indexer, onlyIfUnchanged, null, null, context); + Response createOrUpdateSkillsetWithResponse(String name, BinaryData skillset, + RequestOptions requestOptions) { + return this.serviceClient.createOrUpdateSkillsetWithResponse(name, skillset, requestOptions); } /** - * Creates a new Azure AI Search indexer or updates an indexer if it already exists. + * 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 Sample

+ *
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
+     * 
* - *

Create or update search indexer named "searchIndexer".

+ *

Response Body Schema

* - * *
-     * SearchIndexer searchIndexerFromService = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer");
-     * searchIndexerFromService.setFieldMappings(Collections.singletonList(
-     *     new FieldMapping("hotelName").setTargetFieldName("HotelName")));
-     * CreateOrUpdateIndexerOptions options = new CreateOrUpdateIndexerOptions(searchIndexerFromService)
-     *     .setOnlyIfUnchanged(true)
-     *     .setCacheReprocessingChangeDetectionDisabled(false)
-     *     .setCacheResetRequirementsIgnored(true);
-     * Response<SearchIndexer> indexerFromService = SEARCH_INDEXER_CLIENT.createOrUpdateIndexerWithResponse(
-     *     options, 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());
+     * {@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 (Required)
+     *                         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: Object (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: Object (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 options The options used to create or update the {@link SearchIndexer indexer}. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return A response object containing the Indexer. - * @throws NullPointerException If {@code options} is null. + * @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 createOrUpdateIndexerWithResponse(CreateOrUpdateIndexerOptions options, - Context context) { - Objects.requireNonNull(options, "'options' cannot be null."); - return createOrUpdateIndexerWithResponse(options.getIndexer(), options.isOnlyIfUnchanged(), - options.isCacheReprocessingChangeDetectionDisabled(), options.isCacheResetRequirementsIgnored(), context); + public Response createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, + RequestOptions requestOptions) { + Response response = this.serviceClient.createOrUpdateSkillsetWithResponse(skillset.getName(), + BinaryData.fromObject(skillset), requestOptions); + return new SimpleResponse<>(response, response.getValue().toObject(SearchIndexerSkillset.class)); } - 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); - + /** + * 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 name 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 deleteSkillsetWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.deleteSkillsetWithResponse(name, requestOptions); } /** - * Lists all indexers available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexers.

+ * Retrieves a skillset in a search service. + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
      * 
- * * - * @return all Indexers from the Search service. + * @param name 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.COLLECTION) - public PagedIterable listIndexers() { - return listIndexers(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response getSkillsetWithResponse(String name, RequestOptions requestOptions) { + return this.serviceClient.getSkillsetWithResponse(name, requestOptions); } /** - * Lists all indexers available for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexers.

+ * List all skillsets in a search service. + *

Query Parameters

+ * + * + * + * + *
Query Parameters
NameTypeRequiredDescription
$selectList<String>NoSelects 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. In the form of "," separated string.
+ * You can add these to a request with {@link RequestOptions#addQueryParam} + *

Response Body Schema

* - * *
-     * 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());
-     * }
+     * {@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 (Required)
+     *                                 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: Object (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: Object (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 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.mapPagedSearchIndexers(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); + * + * @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) + Response getSkillsetsWithResponse(RequestOptions requestOptions) { + return this.serviceClient.getSkillsetsWithResponse(requestOptions); } /** - * Lists all indexers names for an Azure AI Search service. + * Creates a new skillset in a search service. + *

Request Body Schema

* - *

Code Sample

+ *
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
+     * 
* - *

List all search indexer names.

+ *

Response Body Schema

* - * *
-     * PagedIterable<String> indexers = SEARCH_INDEXER_CLIENT.listIndexerNames();
-     * for (String indexerName: indexers) {
-     *     System.out.printf("The indexer name is %s.%n", indexerName);
-     * }
+     * {@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 (Required)
+     *                         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: Object (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: Object (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)
+     *     }
+     * }
+     * }
      * 
- * * - * @return all Indexer names from the Search service . + * @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.COLLECTION) - public PagedIterable listIndexerNames() { - return listIndexerNames(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response createSkillsetWithResponse(BinaryData skillset, RequestOptions requestOptions) { + return this.serviceClient.createSkillsetWithResponse(skillset, requestOptions); } /** - * Lists all indexers names for an Azure AI Search service. - * - *

Code Sample

- * - *

List all search indexer names.

+ * Reset an existing skillset in a search service. + *

Request Body Schema

* - * *
-     * 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);
-     * }
+     * {@code
+     * {
+     *     skillNames (Optional): [
+     *         String (Optional)
+     *     ]
+     * }
+     * }
      * 
- * - * - * @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.mapPagedSearchIndexerNames(this.listIndexersWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); - } + * + * @param name 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 name, BinaryData skillNames, RequestOptions requestOptions) { + return this.serviceClient.resetSkillsWithResponse(name, skillNames, requestOptions); } /** - * 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());
-     * 
- * + * Creates a new datasource or updates a datasource if it already exists. * - * @param indexerName the name of the indexer to retrieve - * @return the indexer. + * @param name 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 SearchIndexer getIndexer(String indexerName) { - return getIndexerWithResponse(indexerName, Context.NONE).getValue(); + SearchIndexerDataSourceConnection createOrUpdateDataSourceConnection(String name, + SearchIndexerDataSourceConnection dataSource, Boolean skipIndexerResetRequirementForCache, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateDataSourceConnectionWithResponse + 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 createOrUpdateDataSourceConnectionWithResponse(name, BinaryData.fromObject(dataSource), requestOptions) + .getValue() + .toObject(SearchIndexerDataSourceConnection.class); } /** - * 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());
-     * 
- * + * Creates a new datasource or updates a datasource if it already exists. * - * @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. + * @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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response getIndexerWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().getWithResponse(indexerName, null, context), LOGGER); + public SearchIndexerDataSourceConnection + createOrUpdateDataSourceConnection(SearchIndexerDataSourceConnection dataSource) { + return createOrUpdateDataSourceConnection(dataSource.getName(), dataSource); } /** - * Deletes an Azure AI Search indexer. - * - *

Code Sample

+ * Creates a new datasource or updates a datasource if it already exists. * - *

Delete search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.deleteIndexer("searchIndexer");
-     * 
- * - * - * @param indexerName the name of the indexer to delete + * @param name 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 void deleteIndexer(String indexerName) { - deleteIndexerWithResponse(new SearchIndexer(indexerName), false, Context.NONE); + SearchIndexerDataSourceConnection createOrUpdateDataSourceConnection(String name, + SearchIndexerDataSourceConnection dataSource) { + // Generated convenience method for createOrUpdateDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateDataSourceConnectionWithResponse(name, BinaryData.fromObject(dataSource), requestOptions) + .getValue() + .toObject(SearchIndexerDataSourceConnection.class); } /** - * Deletes an Azure AI Search indexer. + * Deletes a datasource. * - *

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. + * @param name 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 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); + public void deleteDataSourceConnection(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteDataSourceConnectionWithResponse + 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); + } + deleteDataSourceConnectionWithResponse(name, requestOptions).getValue(); } /** - * Resets the change tracking state associated with an indexer. + * Deletes a datasource. * - *

Code Sample

- * - *

Reset search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.resetIndexer("searchIndexer");
-     * 
- * - * - * @param indexerName the name of the indexer to reset + * @param name 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 resetIndexer(String indexerName) { - resetIndexerWithResponse(indexerName, Context.NONE); + public void deleteDataSourceConnection(String name) { + // Generated convenience method for deleteDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteDataSourceConnectionWithResponse(name, requestOptions).getValue(); } /** - * Resets the change tracking state associated with an indexer. - * - *

Code Sample

+ * Retrieves a datasource definition. * - *

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. + * @param name 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 Response resetIndexerWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().resetWithResponse(indexerName, null, context), LOGGER); + public SearchIndexerDataSourceConnection getDataSourceConnection(String name) { + // Generated convenience method for getDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDataSourceConnectionWithResponse(name, requestOptions).getValue() + .toObject(SearchIndexerDataSourceConnection.class); } /** - * Runs an indexer on-demand. - * - *

Code Sample

+ * Lists all datasources available for a search service. * - *

Run search indexer named "searchIndexer".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.runIndexer("searchIndexer");
-     * 
- * - * - * @param indexerName the name of the indexer to run + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void runIndexer(String indexerName) { - runIndexerWithResponse(indexerName, Context.NONE); + public ListDataSourcesResult listDataSourceConnections() { + return getDataSourceConnections(); } /** - * Runs an indexer on-demand. - * - *

Code Sample

+ * Lists the names of all datasources available for a search service. * - *

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. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response runIndexerWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().runWithResponse(indexerName, null, context), LOGGER); + public List listDataSourceConnectionNames() { + return getDataSourceConnections(Collections.singletonList("name")).getDataSources() + .stream() + .map(SearchIndexerDataSourceConnection::getName) + .collect(Collectors.toList()); } /** - * 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());
-     * 
- * + * Lists all datasources available for a search service. * - * @param indexerName the name of the indexer for which to retrieve status - * @return a response with the indexer execution info. + * @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 SearchIndexerStatus getIndexerStatus(String indexerName) { - return getIndexerStatusWithResponse(indexerName, Context.NONE).getValue(); + ListDataSourcesResult getDataSourceConnections(List select) { + // Generated convenience method for getDataSourceConnectionsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getDataSourceConnectionsWithResponse(requestOptions).getValue().toObject(ListDataSourcesResult.class); } /** - * Returns the current status and execution history of an indexer. - * - *

Code Sample

+ * Lists all datasources available for a search service. * - *

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. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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 Response getIndexerStatusWithResponse(String indexerName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().getStatusWithResponse(indexerName, null, context), LOGGER); + ListDataSourcesResult getDataSourceConnections() { + // Generated convenience method for getDataSourceConnectionsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getDataSourceConnectionsWithResponse(requestOptions).getValue().toObject(ListDataSourcesResult.class); } /** - * Creates a new skillset in an Azure AI Search service. - * - *

Code Sample

+ * Creates a new datasource. * - *

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. + * @param dataSourceConnection 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 SearchIndexerSkillset createSkillset(SearchIndexerSkillset skillset) { - return createSkillsetWithResponse(skillset, Context.NONE).getValue(); + public SearchIndexerDataSourceConnection + createDataSourceConnection(SearchIndexerDataSourceConnection dataSourceConnection) { + // Generated convenience method for createDataSourceConnectionWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createDataSourceConnectionWithResponse(BinaryData.fromObject(dataSourceConnection), requestOptions) + .getValue() + .toObject(SearchIndexerDataSourceConnection.class); } /** - * Creates a new skillset in an Azure AI Search service. - * - *

Code Sample

+ * Resets the change tracking state associated with an indexer. * - *

Create search indexer skillset "searchIndexerSkillset".

+ * @param name 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 resetIndexer(String name) { + // Generated convenience method for resetIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + resetIndexerWithResponse(name, requestOptions).getValue(); + } + + /** + * Resync selective options from the datasource to be re-ingested by the indexer.". * - * - *
-     * 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 name The name of the indexer. + * @param indexerResync The definition of the indexer resync options. + * @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 resync(String name, IndexerResyncBody indexerResync) { + // Generated convenience method for resyncWithResponse + RequestOptions requestOptions = new RequestOptions(); + resyncWithResponse(name, BinaryData.fromObject(indexerResync), requestOptions).getValue(); + } + + /** + * Resets specific documents in the datasource to be selectively re-ingested by the indexer. * - * @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. + * @param name 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 Response createSkillsetWithResponse(SearchIndexerSkillset skillset, Context context) { - if (skillset == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'skillset' cannot be null.")); + public void resetDocuments(String name, Boolean overwrite, DocumentKeysOrIds keysOrIds) { + // Generated convenience method for resetDocumentsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (overwrite != null) { + requestOptions.addQueryParam("overwrite", String.valueOf(overwrite), false); } - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSkillsets().createWithResponse(skillset, null, context), LOGGER); + if (keysOrIds != null) { + requestOptions.setBody(BinaryData.fromObject(keysOrIds)); + } + resetDocumentsWithResponse(name, requestOptions).getValue(); } /** - * 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());
-     * 
- * + * Resets specific documents in the datasource to be selectively re-ingested by the indexer. * - * @param skillsetName the name of the skillset to retrieve - * @return the SearchIndexerSkillset. + * @param name 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 SearchIndexerSkillset getSkillset(String skillsetName) { - return getSkillsetWithResponse(skillsetName, Context.NONE).getValue(); + public void resetDocuments(String name) { + // Generated convenience method for resetDocumentsWithResponse + RequestOptions requestOptions = new RequestOptions(); + resetDocumentsWithResponse(name, requestOptions).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());
-     * 
- * + * Runs an indexer on-demand. * - * @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. + * @param name 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 Response getSkillsetWithResponse(String skillsetName, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSkillsets().getWithResponse(skillsetName, null, context), LOGGER); + public void runIndexer(String name) { + // Generated convenience method for runIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + runIndexerWithResponse(name, requestOptions).getValue(); } /** - * 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());
-     * }
-     * 
- * + * Creates a new indexer or updates an indexer if it already exists. * - * @return the list of skillsets. + * @param name 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. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsets() { - return listSkillsets(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + SearchIndexer createOrUpdateIndexer(String name, SearchIndexer indexer, Boolean skipIndexerResetRequirementForCache, + Boolean disableCacheReprocessingChangeDetection, MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateIndexerWithResponse + 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 createOrUpdateIndexerWithResponse(name, BinaryData.fromObject(indexer), requestOptions).getValue() + .toObject(SearchIndexer.class); } /** - * Lists all skillsets available for an Azure AI Search service. - * - *

Code Sample

+ * Creates a new indexer or updates an indexer if it already exists. * - *

List all search indexer skillsets.

+ * @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. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexer createOrUpdateIndexer(SearchIndexer indexer) { + return createOrUpdateIndexer(indexer.getName(), indexer); + } + + /** + * Creates a new indexer or updates an indexer if it already exists. * - * - *
-     * 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 name 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) + SearchIndexer createOrUpdateIndexer(String name, SearchIndexer indexer) { + // Generated convenience method for createOrUpdateIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateIndexerWithResponse(name, BinaryData.fromObject(indexer), requestOptions).getValue() + .toObject(SearchIndexer.class); + } + + /** + * Deletes an indexer. * - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of skillsets. + * @param name 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. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsets(Context context) { - try { - return new PagedIterable<>(() -> MappingUtils.mapPagedSkillsets(listSkillsetsWithResponse(null, context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public void deleteIndexer(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteIndexerWithResponse + 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); + } + deleteIndexerWithResponse(name, requestOptions).getValue(); } - private Response listSkillsetsWithResponse(String select, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> this.restClient.getSkillsets().listWithResponse(select, null, context), LOGGER); + /** + * Deletes an indexer. + * + * @param name 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 deleteIndexer(String name) { + // Generated convenience method for deleteIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteIndexerWithResponse(name, requestOptions).getValue(); } /** - * 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);
-     * }
-     * 
- * + * Retrieves an indexer definition. * - * @return the list of skillset names. + * @param name 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. */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable listSkillsetNames() { - return listSkillsetNames(Context.NONE); + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public SearchIndexer getIndexer(String name) { + // Generated convenience method for getIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexerWithResponse(name, requestOptions).getValue().toObject(SearchIndexer.class); } /** - * Lists all skillset names for an Azure AI Search service. + * Lists all indexers available for a 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.mapPagedSkillsetNames(listSkillsetsWithResponse("name", context))); - } catch (RuntimeException ex) { - throw LOGGER.logExceptionAsError(ex); + * @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) + ListIndexersResult getIndexers(List select) { + // Generated convenience method for getIndexersWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); } + return getIndexersWithResponse(requestOptions).getValue().toObject(ListIndexersResult.class); } /** - * 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());
-     * 
- * + * Lists all indexers available for a search service. * - * @param skillset the {@link SearchIndexerSkillset} to create or update. - * @return the skillset that was created or updated. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public SearchIndexerSkillset createOrUpdateSkillset(SearchIndexerSkillset skillset) { - return createOrUpdateSkillsetWithResponse(skillset, false, Context.NONE).getValue(); + public ListIndexersResult listIndexers() { + return getIndexers(); } /** - * 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());
-     * 
- * + * Lists all indexer names available for a search service. * - * @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. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged, Context context) { - return createOrUpdateSkillsetWithResponse(skillset, onlyIfUnchanged, null, null, context); + public List listIndexerNames() { + return getIndexers(Collections.singletonList("name")).getIndexers() + .stream() + .map(SearchIndexer::getName) + .collect(Collectors.toList()); } /** - * Creates a new Azure AI Search skillset or updates a skillset if it already exists. + * Lists all indexers available for a search service. * - *

Code Sample

- * - *

Create or update search indexer skillset "searchIndexerSkillset".

+ * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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) + ListIndexersResult getIndexers() { + // Generated convenience method for getIndexersWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexersWithResponse(requestOptions).getValue().toObject(ListIndexersResult.class); + } + + /** + * Creates a new indexer. * - * - *
-     * SearchIndexerSkillset indexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset");
-     * indexerSkillset.setDescription("This is new description!");
-     * CreateOrUpdateSkillsetOptions options = new CreateOrUpdateSkillsetOptions(indexerSkillset)
-     *     .setOnlyIfUnchanged(true)
-     *     .setCacheReprocessingChangeDetectionDisabled(false)
-     *     .setCacheResetRequirementsIgnored(true);
-     * Response<SearchIndexerSkillset> updateSkillsetResponse = SEARCH_INDEXER_CLIENT.createOrUpdateSkillsetWithResponse(
-     *     options, 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 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 createIndexer(SearchIndexer indexer) { + // Generated convenience method for createIndexerWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createIndexerWithResponse(BinaryData.fromObject(indexer), requestOptions).getValue() + .toObject(SearchIndexer.class); + } + + /** + * Returns the current status and execution history of an indexer. * - * @param options The options used to create or update the {@link SearchIndexerSkillset skillset}. - * @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. - * @throws NullPointerException If {@code options} is null. + * @param name 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 Response createOrUpdateSkillsetWithResponse(CreateOrUpdateSkillsetOptions options, - Context context) { - Objects.requireNonNull(options, "'options' cannot be null."); - return createOrUpdateSkillsetWithResponse(options.getSkillset(), options.isOnlyIfUnchanged(), - options.isCacheReprocessingChangeDetectionDisabled(), options.isCacheResetRequirementsIgnored(), context); + public SearchIndexerStatus getIndexerStatus(String name) { + // Generated convenience method for getIndexerStatusWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getIndexerStatusWithResponse(name, requestOptions).getValue().toObject(SearchIndexerStatus.class); } - Response createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, - boolean onlyIfUnchanged, Boolean disableCacheReprocessingChangeDetection, Boolean ignoreResetRequirements, - Context context) { - if (skillset == null) { - throw LOGGER.logExceptionAsError(new NullPointerException("'skillset' cannot be null.")); + /** + * Creates a new skillset in a search service or updates the skillset if it already exists. + * + * @param name 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) + SearchIndexerSkillset createOrUpdateSkillset(String name, SearchIndexerSkillset skillset, + Boolean skipIndexerResetRequirementForCache, Boolean disableCacheReprocessingChangeDetection, + MatchConditions matchConditions) { + // Generated convenience method for createOrUpdateSkillsetWithResponse + 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); } - String ifMatch = onlyIfUnchanged ? skillset.getETag() : null; - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getSkillsets() - .createOrUpdateWithResponse(skillset.getName(), skillset, ifMatch, null, ignoreResetRequirements, - disableCacheReprocessingChangeDetection, null, context), - LOGGER); + return createOrUpdateSkillsetWithResponse(name, BinaryData.fromObject(skillset), requestOptions).getValue() + .toObject(SearchIndexerSkillset.class); } /** - * Deletes a cognitive skillset in an Azure AI Search service. + * Creates a new skillset in a search service or updates the skillset if it already exists. * - *

Code Sample

- * - *

Delete search indexer skillset "searchIndexerSkillset".

- * - * - *
-     * SEARCH_INDEXER_CLIENT.deleteSkillset("searchIndexerSkillset");
-     * 
- * - * - * @param skillsetName the name of the skillset to delete + * @param name 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 void deleteSkillset(String skillsetName) { - deleteSkillsetWithResponse(new SearchIndexerSkillset(skillsetName), false, Context.NONE); + SearchIndexerSkillset createOrUpdateSkillset(String name, SearchIndexerSkillset skillset) { + // Generated convenience method for createOrUpdateSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createOrUpdateSkillsetWithResponse(name, BinaryData.fromObject(skillset), requestOptions).getValue() + .toObject(SearchIndexerSkillset.class); } /** - * Deletes a cognitive skillset in an Azure AI Search service. - * - *

Code Sample

- * - *

Delete search indexer skillset "searchIndexerSkillset".

+ * Creates a new skillset in a search service or updates the skillset if it already exists. * - * - *
-     * 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. + * @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. */ @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); + public SearchIndexerSkillset createOrUpdateSkillset(SearchIndexerSkillset skillset) { + return createOrUpdateSkillset(skillset.getName(), skillset); } /** - * Resync selective options from the datasource to be re-ingested by the indexer. + * Deletes a skillset in a search service. * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync parameter. + * @param name The name of the skillset. + * @param matchConditions Specifies HTTP options for conditional requests. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 resync(String indexerName, IndexerResyncBody indexerResync) { - resyncWithResponse(indexerName, indexerResync, Context.NONE).getValue(); + public void deleteSkillset(String name, MatchConditions matchConditions) { + // Generated convenience method for deleteSkillsetWithResponse + 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); + } + deleteSkillsetWithResponse(name, requestOptions).getValue(); } /** - * Resync selective options from the datasource to be re-ingested by the indexer. + * Deletes a skillset in a search service. * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync parameter. - * @param context The context to associate with this operation. + * @param name The name of the skillset. * @throws IllegalArgumentException thrown if parameters fail the validation. - * @throws ErrorResponseException thrown if the request is rejected by server. + * @throws 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 the {@link Response}. */ + @Generated @ServiceMethod(returns = ReturnType.SINGLE) - public Response resyncWithResponse(String indexerName, IndexerResyncBody indexerResync, Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getIndexers().resyncWithResponse(indexerName, indexerResync, null, context), LOGGER); + public void deleteSkillset(String name) { + // Generated convenience method for deleteSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + deleteSkillsetWithResponse(name, requestOptions).getValue(); } /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * - *
-     * // Reset the documents with keys 1234 and 4321.
-     * SEARCH_INDEXER_CLIENT.resetDocuments("searchIndexer", false, Arrays.asList("1234", "4321"), null);
-     *
-     * // Clear the previous documents to be reset and replace them with documents 1235 and 5231.
-     * SEARCH_INDEXER_CLIENT.resetDocuments("searchIndexer", true, Arrays.asList("1235", "5321"), null);
-     * 
- * + * Retrieves a skillset in a search service. * - * @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 documentKeys Document keys to be reset. - * @param datasourceDocumentIds Datasource document identifiers to be reset. + * @param name 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 void resetDocuments(String indexerName, Boolean overwrite, List documentKeys, - List datasourceDocumentIds) { - resetDocumentsWithResponse(new SearchIndexer(indexerName), overwrite, documentKeys, datasourceDocumentIds, - Context.NONE); + public SearchIndexerSkillset getSkillset(String name) { + // Generated convenience method for getSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSkillsetWithResponse(name, requestOptions).getValue().toObject(SearchIndexerSkillset.class); } /** - * Resets specific documents in the datasource to be selectively re-ingested by the indexer. - * - * - *
-     * SearchIndexer searchIndexer = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer");
-     *
-     * // Reset the documents with keys 1234 and 4321.
-     * Response<Void> resetDocsResult = SEARCH_INDEXER_CLIENT.resetDocumentsWithResponse(searchIndexer, false,
-     *     Arrays.asList("1234", "4321"), null, new Context(KEY_1, VALUE_1));
-     * System.out.printf("Requesting documents to be reset completed with status code %d.%n",
-     *     resetDocsResult.getStatusCode());
-     *
-     * // Clear the previous documents to be reset and replace them with documents 1235 and 5231.
-     * resetDocsResult = SEARCH_INDEXER_CLIENT.resetDocumentsWithResponse(searchIndexer, true,
-     *     Arrays.asList("1235", "5321"), null, new Context(KEY_1, VALUE_1));
-     * System.out.printf("Overwriting the documents to be reset completed with status code %d.%n",
-     *     resetDocsResult.getStatusCode());
-     * 
- * + * List all skillsets in a search service. * - * @param indexer 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 documentKeys Document keys to be reset. - * @param datasourceDocumentIds Datasource document identifiers to be reset. - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return A response signalling completion. - * @throws NullPointerException If {@code indexer} is null. + * @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 Response resetDocumentsWithResponse(SearchIndexer indexer, Boolean overwrite, - List documentKeys, List datasourceDocumentIds, Context context) { - DocumentKeysOrIds documentKeysOrIds - = new DocumentKeysOrIds().setDocumentKeys(documentKeys).setDatasourceDocumentIds(datasourceDocumentIds); - - return Utility.executeRestCallWithExceptionHandling(() -> restClient.getIndexers() - .resetDocsWithResponse(indexer.getName(), overwrite, documentKeysOrIds, null, context), LOGGER); + ListSkillsetsResult getSkillsets(List select) { + // Generated convenience method for getSkillsetsWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (select != null) { + requestOptions.addQueryParam("$select", + select.stream() + .map(paramItemValue -> Objects.toString(paramItemValue, "")) + .collect(Collectors.joining(",")), + false); + } + return getSkillsetsWithResponse(requestOptions).getValue().toObject(ListSkillsetsResult.class); } /** - * Resets skills in an existing skillset in an Azure AI Search service. + * List all skillsets in a search service. * - * - *
-     * // Reset the "myOcr" and "myText" skills.
-     * SEARCH_INDEXER_CLIENT.resetSkills("searchIndexerSkillset", Arrays.asList("myOcr", "myText"));
-     * 
- * + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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) + ListSkillsetsResult getSkillsets() { + // Generated convenience method for getSkillsetsWithResponse + RequestOptions requestOptions = new RequestOptions(); + return getSkillsetsWithResponse(requestOptions).getValue().toObject(ListSkillsetsResult.class); + } + + /** + * List all skillsets in a search service. * - * @param skillsetName The name of the skillset to reset. - * @param skillNames The skills to reset. + * @throws HttpResponseException thrown if the request is rejected by server. + * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. + * @throws ResourceNotFoundException thrown if 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. */ @ServiceMethod(returns = ReturnType.SINGLE) - public void resetSkills(String skillsetName, List skillNames) { - resetSkillsWithResponse(new SearchIndexerSkillset(skillsetName), skillNames, Context.NONE); + public ListSkillsetsResult listSkillsets() { + return getSkillsets(); } /** - * Resets skills in an existing skillset in an Azure AI Search service. + * List the names of all skillsets in a search service. * - * - *
-     * SearchIndexerSkillset searchIndexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset");
+     * @throws HttpResponseException thrown if the request is rejected by server.
+     * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401.
+     * @throws ResourceNotFoundException thrown if 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.
+     */
+    @ServiceMethod(returns = ReturnType.SINGLE)
+    public List listSkillsetNames() {
+        return getSkillsets(Collections.singletonList("name")).getSkillsets()
+            .stream()
+            .map(SearchIndexerSkillset::getName)
+            .collect(Collectors.toList());
+    }
+
+    /**
+     * Creates a new skillset in a search service.
      *
-     * // Reset the "myOcr" and "myText" skills.
-     * Response<Void> resetSkillsResponse = SEARCH_INDEXER_CLIENT.resetSkillsWithResponse(searchIndexerSkillset,
-     *     Arrays.asList("myOcr", "myText"), new Context(KEY_1, VALUE_1));
-     * System.out.printf("Resetting skills completed with status code %d.%n", resetSkillsResponse.getStatusCode());
-     * 
- * + * @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 createSkillset(SearchIndexerSkillset skillset) { + // Generated convenience method for createSkillsetWithResponse + RequestOptions requestOptions = new RequestOptions(); + return createSkillsetWithResponse(BinaryData.fromObject(skillset), requestOptions).getValue() + .toObject(SearchIndexerSkillset.class); + } + + /** + * Reset an existing skillset in a search service. * - * @param skillset The skillset to reset. - * @param skillNames The skills to reset. - * @param context Additional context that is passed through the HTTP pipeline during the service call. - * @return A response signalling completion. - * @throws NullPointerException If {@code skillset} is null. + * @param name 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 Response resetSkillsWithResponse(SearchIndexerSkillset skillset, List skillNames, - Context context) { - return Utility.executeRestCallWithExceptionHandling( - () -> restClient.getSkillsets() - .resetSkillsWithResponse(skillset.getName(), new SkillNames().setSkillNames(skillNames), null, context), - LOGGER); + public void resetSkills(String name, SkillNames skillNames) { + // Generated convenience method for resetSkillsWithResponse + RequestOptions requestOptions = new RequestOptions(); + resetSkillsWithResponse(name, BinaryData.fromObject(skillNames), requestOptions).getValue(); } } 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 index de6cfec11a34..0e56fde46edd 100644 --- 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 @@ -1,517 +1,377 @@ // 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.indexes; +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.HttpClientOptions; +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.models.SearchAudience; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.search.documents.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 com.azure.search.documents.implementation.SearchIndexerClientImpl; import java.util.ArrayList; import java.util.List; +import java.util.Map; 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 + * A builder for creating a new instance of the SearchIndexerClient type. */ @ServiceClientBuilder(serviceClients = { SearchIndexerClient.class, SearchIndexerAsyncClient.class }) -public class SearchIndexerClientBuilder implements AzureKeyCredentialTrait, - ConfigurationTrait, EndpointTrait, - HttpTrait, TokenCredentialTrait { - private static final ClientLogger LOGGER = new ClientLogger(SearchIndexerClientBuilder.class); +public final class SearchIndexerClientBuilder implements HttpTrait, + ConfigurationTrait, TokenCredentialTrait, + KeyCredentialTrait, EndpointTrait { - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); + @Generated + private static final String SDK_NAME = "name"; - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; + @Generated + private static final String SDK_VERSION = "version"; - 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; + @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 SearchIndexerClient - * SearchIndexerClients} and {@link SearchIndexerAsyncClient SearchIndexerAsyncClients}. + * Create an instance of the SearchIndexerClientBuilder. */ + @Generated public SearchIndexerClientBuilder() { + this.pipelinePolicies = new ArrayList<>(); } - /** - * 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. + /* + * The HTTP client used to send the request. */ - 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); - } + @Generated + private HttpClient httpClient; /** - * 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. + * {@inheritDoc}. */ - 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); + @Generated + @Override + public SearchIndexerClientBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; } + /* + * The HTTP pipeline to send requests through. + */ + @Generated + private HttpPipeline 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. + * {@inheritDoc}. */ + @Generated @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)); + public SearchIndexerClientBuilder pipeline(HttpPipeline pipeline) { + if (this.pipeline != null && pipeline == null) { + LOGGER.atInfo().log("HttpPipeline is being set to 'null' when it was previously configured."); } - this.endpoint = endpoint; + this.pipeline = pipeline; return this; } + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; + /** - * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. - * - * @param credential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated SearchIndexerClientBuilder object. + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexerClientBuilder credential(AzureKeyCredential credential) { - this.azureKeyCredential = credential; + public SearchIndexerClientBuilder 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 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. + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexerClientBuilder credential(TokenCredential credential) { - this.tokenCredential = credential; + public SearchIndexerClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; return this; } + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + /** - * 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. + * {@inheritDoc}. */ - public SearchIndexerClientBuilder audience(SearchAudience audience) { - this.audience = audience; + @Generated + @Override + public SearchIndexerClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; 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. + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexerClientBuilder httpLogOptions(HttpLogOptions logOptions) { - httpLogOptions = logOptions; + public SearchIndexerClientBuilder addPolicy(HttpPipelinePolicy customPolicy) { + Objects.requireNonNull(customPolicy, "'customPolicy' cannot be null."); + pipelinePolicies.add(customPolicy); return this; } - /** - * Gets the default Azure Search headers and query parameters allow list. - * - * @return The default {@link HttpLogOptions} allow list. + /* + * The configuration store that is used during construction of the service client. */ - public static HttpLogOptions getDefaultLogOptions() { - return Constants.DEFAULT_LOG_OPTIONS_SUPPLIER.get(); - } + @Generated + private Configuration configuration; /** - * 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 + * {@inheritDoc}. */ + @Generated @Override - public SearchIndexerClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; + public SearchIndexerClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; return this; } + /* + * The TokenCredential used for authentication. + */ + @Generated + private TokenCredential tokenCredential; + /** - * 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}. + * {@inheritDoc}. */ + @Generated @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); - } - + public SearchIndexerClientBuilder credential(TokenCredential tokenCredential) { + this.tokenCredential = tokenCredential; return this; } + /* + * The KeyCredential used for authentication. + */ + @Generated + private KeyCredential keyCredential; + /** - * 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. + * {@inheritDoc}. */ + @Generated @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; + public SearchIndexerClientBuilder credential(KeyCredential keyCredential) { + this.keyCredential = keyCredential; return this; } + /* + * The service endpoint + */ + @Generated + private String endpoint; + /** - * 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. + * {@inheritDoc}. */ + @Generated @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; + public SearchIndexerClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; return this; } + /* + * Service version + */ + @Generated + private SearchServiceVersion serviceVersion; + /** - * 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. + * Sets Service version. * - * @param configuration The configuration store that will be used. - * @return The updated SearchIndexerClientBuilder object. + * @param serviceVersion the serviceVersion value. + * @return the SearchIndexerClientBuilder. */ - @Override - public SearchIndexerClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; + @Generated + public SearchIndexerClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; return this; } + /* + * The retry policy that will attempt to retry failed requests, if applicable. + */ + @Generated + private RetryPolicy retryPolicy; + /** - * 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)}. + * Sets The retry policy that will attempt to retry failed requests, if applicable. * - * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. - * @return The updated SearchIndexerClientBuilder object. + * @param retryPolicy the retryPolicy value. + * @return the SearchIndexerClientBuilder. */ + @Generated 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.

+ * Sets the Audience to use for authentication with Microsoft Entra ID. *

- * Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}. + * If {@code audience} is null the public cloud audience will be assumed. * - * @param retryOptions The {@link RetryOptions} to use for all the requests made through the client. + * @param audience The Audience to use for authentication with Microsoft Entra ID. * @return The updated SearchIndexerClientBuilder object. */ - @Override - public SearchIndexerClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; + public SearchIndexerClientBuilder audience(SearchAudience audience) { + if (audience == null) { + this.scopes = DEFAULT_SCOPES; + } else { + this.scopes = new String[] { audience.getValue() + "/.default" }; + } 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. + * Builds an instance of SearchIndexerClientImpl with the provided parameters. * - * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchIndexerClientBuilder object. + * @return an instance of SearchIndexerClientImpl. */ - public SearchIndexerClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { - this.serviceVersion = serviceVersion; - return this; + @Generated + private SearchIndexerClientImpl buildInnerClient() { + this.validateClient(); + HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); + SearchServiceVersion localServiceVersion + = (serviceVersion != null) ? serviceVersion : SearchServiceVersion.getLatest(); + SearchIndexerClientImpl client = new SearchIndexerClientImpl(localPipeline, + JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); + return client; + } + + @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, 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; + } + + /** + * Builds an instance of SearchIndexerAsyncClient class. + * + * @return an instance of SearchIndexerAsyncClient. + */ + @Generated + public SearchIndexerAsyncClient buildAsyncClient() { + return new SearchIndexerAsyncClient(buildInnerClient()); + } + + /** + * Builds an instance of SearchIndexerClient class. + * + * @return an instance of SearchIndexerClient. + */ + @Generated + public SearchIndexerClient buildClient() { + return new SearchIndexerClient(buildInnerClient()); + } + + private static final ClientLogger LOGGER = new ClientLogger(SearchIndexerClientBuilder.class); + + @Generated + private String[] scopes = DEFAULT_SCOPES; } 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/SimpleField.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java deleted file mode 100644 index 39276c8e11c6..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SimpleField.java +++ /dev/null @@ -1,79 +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.LexicalNormalizerName; -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; - - /** - * A {@link LexicalNormalizerName} to associate as the normalizer for the {@link SearchField field}. - * - * @return The {@link LexicalNormalizerName} that will be associated as the normalizer for the - * {@link SearchField field}. - */ - String normalizerName() default ""; - - /** - * A value indicating whether the field should be used as a permission filter. - * - * @return A flag indicating if the field or method should generate as a permission filter {@link SearchField field}. - */ - String permissionFilter() default ""; - - /** - * Indicates if the field or method should be used for sensitivity label filtering. This enables document-level - * filtering based on Microsoft Purview sensitivity labels. - * - * @return A flag indicating if the field or method should generate as a sensitivity label {@link SearchField field}. - */ - boolean isSensitivityLabel() 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 ee20c7e80e34..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 = "SearchServiceClientAliases") - 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)); - } - - /** - * 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/DataSourcesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/DataSourcesImpl.java deleted file mode 100644 index 045ce6da4694..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 = "SearchServiceClientDataSources") - 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 719f9d1f291c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/IndexersImpl.java +++ /dev/null @@ -1,1465 +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.IndexerResyncBody; -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 = "SearchServiceClientIndexers") - 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.resync") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> resync(@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, - @BodyParam("application/json") IndexerResyncBody indexerResync, Context context); - - @Post("/indexers('{indexerName}')/search.resync") - @ExpectedResponses({ 204 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response resyncSync(@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, - @BodyParam("application/json") IndexerResyncBody indexerResync, 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); - } - - /** - * Resync selective options from the datasource to be re-ingested by the indexer. - * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync 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> resyncWithResponseAsync(String indexerName, IndexerResyncBody indexerResync, - RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> resyncWithResponseAsync(indexerName, indexerResync, requestOptions, context)); - } - - /** - * Resync selective options from the datasource to be re-ingested by the indexer. - * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync 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> resyncWithResponseAsync(String indexerName, IndexerResyncBody indexerResync, - 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.resync(this.client.getEndpoint(), indexerName, xMsClientRequestId, this.client.getApiVersion(), - accept, indexerResync, context); - } - - /** - * Resync selective options from the datasource to be re-ingested by the indexer. - * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync 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 resyncAsync(String indexerName, IndexerResyncBody indexerResync, RequestOptions requestOptions) { - return resyncWithResponseAsync(indexerName, indexerResync, requestOptions).flatMap(ignored -> Mono.empty()); - } - - /** - * Resync selective options from the datasource to be re-ingested by the indexer. - * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync 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 resyncAsync(String indexerName, IndexerResyncBody indexerResync, RequestOptions requestOptions, - Context context) { - return resyncWithResponseAsync(indexerName, indexerResync, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Resync selective options from the datasource to be re-ingested by the indexer. - * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync 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 resyncWithResponse(String indexerName, IndexerResyncBody indexerResync, - 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.resyncSync(this.client.getEndpoint(), indexerName, xMsClientRequestId, - this.client.getApiVersion(), accept, indexerResync, context); - } - - /** - * Resync selective options from the datasource to be re-ingested by the indexer. - * - * @param indexerName The name of the indexer to resync for. - * @param indexerResync The indexerResync 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 resync(String indexerName, IndexerResyncBody indexerResync, RequestOptions requestOptions) { - resyncWithResponse(indexerName, indexerResync, 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 5e6162a5621b..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 = "SearchServiceClientIndexes") - 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)); - } - - /** - * 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/KnowledgeBasesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeBasesImpl.java deleted file mode 100644 index f171f4fc1d89..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeBasesImpl.java +++ /dev/null @@ -1,817 +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.ListKnowledgeBasesResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.KnowledgeBase; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in KnowledgeBases. - */ -public final class KnowledgeBasesImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KnowledgeBasesService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of KnowledgeBasesImpl. - * - * @param client the instance of the service client containing this operation class. - */ - KnowledgeBasesImpl(SearchServiceClientImpl client) { - this.service - = RestProxy.create(KnowledgeBasesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientKnowledgeBases to be used by the proxy service to - * perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientKnowledgeBases") - public interface KnowledgeBasesService { - @Put("/knowledgebases('{knowledgeBaseName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("knowledgeBaseName") String knowledgeBaseName, - @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") KnowledgeBase knowledgeBase, Context context); - - @Put("/knowledgebases('{knowledgeBaseName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("knowledgeBaseName") String knowledgeBaseName, - @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") KnowledgeBase knowledgeBase, Context context); - - @Delete("/knowledgebases('{knowledgeBaseName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, - @PathParam("knowledgeBaseName") String knowledgeBaseName, - @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("/knowledgebases('{knowledgeBaseName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, - @PathParam("knowledgeBaseName") String knowledgeBaseName, - @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("/knowledgebases('{knowledgeBaseName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("knowledgeBaseName") String knowledgeBaseName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/knowledgebases('{knowledgeBaseName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, - @PathParam("knowledgeBaseName") String knowledgeBaseName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/knowledgebases") - @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("/knowledgebases") - @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); - - @Post("/knowledgebases") - @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") KnowledgeBase knowledgeBase, Context context); - - @Post("/knowledgebases") - @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") KnowledgeBase knowledgeBase, Context context); - } - - /** - * Creates a new knowledge base or updates an knowledge base if it already exists. - * - * @param knowledgeBaseName The name of the knowledge base to create or update. - * @param knowledgeBase The definition of the knowledge base 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 the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String knowledgeBaseName, - KnowledgeBase knowledgeBase, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(knowledgeBaseName, knowledgeBase, - ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Creates a new knowledge base or updates an knowledge base if it already exists. - * - * @param knowledgeBaseName The name of the knowledge base to create or update. - * @param knowledgeBase The definition of the knowledge base 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 the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String knowledgeBaseName, - KnowledgeBase knowledgeBase, 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(), knowledgeBaseName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), accept, knowledgeBase, context); - } - - /** - * Creates a new knowledge base or updates an knowledge base if it already exists. - * - * @param knowledgeBaseName The name of the knowledge base to create or update. - * @param knowledgeBase The definition of the knowledge base 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 the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String knowledgeBaseName, KnowledgeBase knowledgeBase, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(knowledgeBaseName, knowledgeBase, ifMatch, ifNoneMatch, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge base or updates an knowledge base if it already exists. - * - * @param knowledgeBaseName The name of the knowledge base to create or update. - * @param knowledgeBase The definition of the knowledge base 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 the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String knowledgeBaseName, KnowledgeBase knowledgeBase, - String ifMatch, String ifNoneMatch, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(knowledgeBaseName, knowledgeBase, ifMatch, ifNoneMatch, requestOptions, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge base or updates an knowledge base if it already exists. - * - * @param knowledgeBaseName The name of the knowledge base to create or update. - * @param knowledgeBase The definition of the knowledge base 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 the response body along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String knowledgeBaseName, KnowledgeBase knowledgeBase, - 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(), knowledgeBaseName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), accept, knowledgeBase, context); - } - - /** - * Creates a new knowledge base or updates an knowledge base if it already exists. - * - * @param knowledgeBaseName The name of the knowledge base to create or update. - * @param knowledgeBase The definition of the knowledge base 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 the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBase createOrUpdate(String knowledgeBaseName, KnowledgeBase knowledgeBase, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponse(knowledgeBaseName, knowledgeBase, ifMatch, ifNoneMatch, requestOptions, - Context.NONE).getValue(); - } - - /** - * Deletes an existing knowledge base. - * - * @param knowledgeBaseName The name of the knowledge base 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 knowledgeBaseName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil.withContext( - context -> deleteWithResponseAsync(knowledgeBaseName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Deletes an existing knowledge base. - * - * @param knowledgeBaseName The name of the knowledge base 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 knowledgeBaseName, 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(), knowledgeBaseName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes an existing knowledge base. - * - * @param knowledgeBaseName The name of the knowledge base 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 knowledgeBaseName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return deleteWithResponseAsync(knowledgeBaseName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes an existing knowledge base. - * - * @param knowledgeBaseName The name of the knowledge base 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 knowledgeBaseName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions, Context context) { - return deleteWithResponseAsync(knowledgeBaseName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes an existing knowledge base. - * - * @param knowledgeBaseName The name of the knowledge base 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 knowledgeBaseName, 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(), knowledgeBaseName, xMsClientRequestId, ifMatch, - ifNoneMatch, this.client.getApiVersion(), accept, context); - } - - /** - * Deletes an existing knowledge base. - * - * @param knowledgeBaseName The name of the knowledge base 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 knowledgeBaseName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(knowledgeBaseName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves an knowledge base definition. - * - * @param knowledgeBaseName The name of the knowledge base 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 the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String knowledgeBaseName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(knowledgeBaseName, requestOptions, context)); - } - - /** - * Retrieves an knowledge base definition. - * - * @param knowledgeBaseName The name of the knowledge base 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 the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String knowledgeBaseName, 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(), knowledgeBaseName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Retrieves an knowledge base definition. - * - * @param knowledgeBaseName The name of the knowledge base 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 the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String knowledgeBaseName, RequestOptions requestOptions) { - return getWithResponseAsync(knowledgeBaseName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an knowledge base definition. - * - * @param knowledgeBaseName The name of the knowledge base 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 the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String knowledgeBaseName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(knowledgeBaseName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves an knowledge base definition. - * - * @param knowledgeBaseName The name of the knowledge base 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 the response body along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String knowledgeBaseName, 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(), knowledgeBaseName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Retrieves an knowledge base definition. - * - * @param knowledgeBaseName The name of the knowledge base 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 the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBase get(String knowledgeBaseName, RequestOptions requestOptions) { - return getWithResponse(knowledgeBaseName, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all knowledge bases 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 the response body 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().getKnowledgeBases(), null, null)); - } - - /** - * Lists all knowledge bases 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 the response body 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().getKnowledgeBases(), null, null)); - } - - /** - * Lists all knowledge bases 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 the paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(RequestOptions requestOptions) { - return new PagedFlux<>(() -> listSinglePageAsync(requestOptions)); - } - - /** - * Lists all knowledge bases 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 the paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(RequestOptions requestOptions, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(requestOptions, context)); - } - - /** - * Lists all knowledge bases 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 the response body 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().getKnowledgeBases(), null, null); - } - - /** - * Lists all knowledge bases 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 the response body 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().getKnowledgeBases(), null, null); - } - - /** - * Lists all knowledge bases 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 the paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(RequestOptions requestOptions) { - return new PagedIterable<>(() -> listSinglePage(requestOptions)); - } - - /** - * Lists all knowledge bases 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 the 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 knowledge base. - * - * @param knowledgeBase The definition of the knowledge base 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 the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(KnowledgeBase knowledgeBase, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(knowledgeBase, requestOptions, context)); - } - - /** - * Creates a new knowledge base. - * - * @param knowledgeBase The definition of the knowledge base 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 the response body along with {@link Response} on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(KnowledgeBase knowledgeBase, - 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, - knowledgeBase, context); - } - - /** - * Creates a new knowledge base. - * - * @param knowledgeBase The definition of the knowledge base 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 the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(KnowledgeBase knowledgeBase, RequestOptions requestOptions) { - return createWithResponseAsync(knowledgeBase, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge base. - * - * @param knowledgeBase The definition of the knowledge base 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 the response body on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(KnowledgeBase knowledgeBase, RequestOptions requestOptions, - Context context) { - return createWithResponseAsync(knowledgeBase, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge base. - * - * @param knowledgeBase The definition of the knowledge base 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 the response body along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(KnowledgeBase knowledgeBase, 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, - knowledgeBase, context); - } - - /** - * Creates a new knowledge base. - * - * @param knowledgeBase The definition of the knowledge base 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 the response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBase create(KnowledgeBase knowledgeBase, RequestOptions requestOptions) { - return createWithResponse(knowledgeBase, requestOptions, Context.NONE).getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeSourcesImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeSourcesImpl.java deleted file mode 100644 index 1d3cfcf226a8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/KnowledgeSourcesImpl.java +++ /dev/null @@ -1,951 +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.ListKnowledgeSourcesResult; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.KnowledgeSource; -import com.azure.search.documents.indexes.models.KnowledgeSourceStatus; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in KnowledgeSources. - */ -public final class KnowledgeSourcesImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KnowledgeSourcesService service; - - /** - * The service client containing this operation class. - */ - private final SearchServiceClientImpl client; - - /** - * Initializes an instance of KnowledgeSourcesImpl. - * - * @param client the instance of the service client containing this operation class. - */ - KnowledgeSourcesImpl(SearchServiceClientImpl client) { - this.service - = RestProxy.create(KnowledgeSourcesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for SearchServiceClientKnowledgeSources to be used by the proxy service - * to perform REST calls. - */ - @Host("{endpoint}") - @ServiceInterface(name = "SearchServiceClientKnowledgeSources") - public interface KnowledgeSourcesService { - @Put("/knowledgesources('{sourceName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> createOrUpdate(@HostParam("endpoint") String endpoint, - @PathParam("sourceName") String sourceName, @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") KnowledgeSource knowledgeSource, - Context context); - - @Put("/knowledgesources('{sourceName}')") - @ExpectedResponses({ 200, 201 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response createOrUpdateSync(@HostParam("endpoint") String endpoint, - @PathParam("sourceName") String sourceName, @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") KnowledgeSource knowledgeSource, - Context context); - - @Delete("/knowledgesources('{sourceName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> delete(@HostParam("endpoint") String endpoint, @PathParam("sourceName") String sourceName, - @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("/knowledgesources('{sourceName}')") - @ExpectedResponses({ 204, 404 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response deleteSync(@HostParam("endpoint") String endpoint, @PathParam("sourceName") String sourceName, - @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("/knowledgesources('{sourceName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> get(@HostParam("endpoint") String endpoint, - @PathParam("sourceName") String sourceName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/knowledgesources('{sourceName}')") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getSync(@HostParam("endpoint") String endpoint, - @PathParam("sourceName") String sourceName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/knowledgesources") - @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("/knowledgesources") - @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); - - @Post("/knowledgesources") - @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") KnowledgeSource knowledgeSource, Context context); - - @Post("/knowledgesources") - @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") KnowledgeSource knowledgeSource, Context context); - - @Get("/knowledgesources('{sourceName}')/status") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> getStatus(@HostParam("endpoint") String endpoint, - @PathParam("sourceName") String sourceName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/knowledgesources('{sourceName}')/status") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getStatusSync(@HostParam("endpoint") String endpoint, - @PathParam("sourceName") String sourceName, @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - } - - /** - * Creates a new knowledge source or updates an knowledge source if it already exists. - * - * @param sourceName The name of the knowledge source to create or update. - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String sourceName, - KnowledgeSource knowledgeSource, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createOrUpdateWithResponseAsync(sourceName, knowledgeSource, ifMatch, - ifNoneMatch, requestOptions, context)); - } - - /** - * Creates a new knowledge source or updates an knowledge source if it already exists. - * - * @param sourceName The name of the knowledge source to create or update. - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createOrUpdateWithResponseAsync(String sourceName, - KnowledgeSource knowledgeSource, 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(), sourceName, xMsClientRequestId, ifMatch, ifNoneMatch, - prefer, this.client.getApiVersion(), accept, knowledgeSource, context); - } - - /** - * Creates a new knowledge source or updates an knowledge source if it already exists. - * - * @param sourceName The name of the knowledge source to create or update. - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String sourceName, KnowledgeSource knowledgeSource, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponseAsync(sourceName, knowledgeSource, ifMatch, ifNoneMatch, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge source or updates an knowledge source if it already exists. - * - * @param sourceName The name of the knowledge source to create or update. - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createOrUpdateAsync(String sourceName, KnowledgeSource knowledgeSource, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions, Context context) { - return createOrUpdateWithResponseAsync(sourceName, knowledgeSource, ifMatch, ifNoneMatch, requestOptions, - context).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge source or updates an knowledge source if it already exists. - * - * @param sourceName The name of the knowledge source to create or update. - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createOrUpdateWithResponse(String sourceName, KnowledgeSource knowledgeSource, - 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(), sourceName, xMsClientRequestId, ifMatch, - ifNoneMatch, prefer, this.client.getApiVersion(), accept, knowledgeSource, context); - } - - /** - * Creates a new knowledge source or updates an knowledge source if it already exists. - * - * @param sourceName The name of the knowledge source to create or update. - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeSource createOrUpdate(String sourceName, KnowledgeSource knowledgeSource, String ifMatch, - String ifNoneMatch, RequestOptions requestOptions) { - return createOrUpdateWithResponse(sourceName, knowledgeSource, ifMatch, ifNoneMatch, requestOptions, - Context.NONE).getValue(); - } - - /** - * Deletes an existing knowledge source. - * - * @param sourceName The name of the knowledge source 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 sourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return FluxUtil - .withContext(context -> deleteWithResponseAsync(sourceName, ifMatch, ifNoneMatch, requestOptions, context)); - } - - /** - * Deletes an existing knowledge source. - * - * @param sourceName The name of the knowledge source 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 sourceName, 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(), sourceName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes an existing knowledge source. - * - * @param sourceName The name of the knowledge source 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 sourceName, String ifMatch, String ifNoneMatch, - RequestOptions requestOptions) { - return deleteWithResponseAsync(sourceName, ifMatch, ifNoneMatch, requestOptions) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes an existing knowledge source. - * - * @param sourceName The name of the knowledge source 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 sourceName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions, - Context context) { - return deleteWithResponseAsync(sourceName, ifMatch, ifNoneMatch, requestOptions, context) - .flatMap(ignored -> Mono.empty()); - } - - /** - * Deletes an existing knowledge source. - * - * @param sourceName The name of the knowledge source 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 sourceName, 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(), sourceName, xMsClientRequestId, ifMatch, ifNoneMatch, - this.client.getApiVersion(), accept, context); - } - - /** - * Deletes an existing knowledge source. - * - * @param sourceName The name of the knowledge source 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 sourceName, String ifMatch, String ifNoneMatch, RequestOptions requestOptions) { - deleteWithResponse(sourceName, ifMatch, ifNoneMatch, requestOptions, Context.NONE); - } - - /** - * Retrieves a knowledge source definition. - * - * @param sourceName The name of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String sourceName, RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getWithResponseAsync(sourceName, requestOptions, context)); - } - - /** - * Retrieves a knowledge source definition. - * - * @param sourceName The name of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getWithResponseAsync(String sourceName, 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(), sourceName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves a knowledge source definition. - * - * @param sourceName The name of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String sourceName, RequestOptions requestOptions) { - return getWithResponseAsync(sourceName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a knowledge source definition. - * - * @param sourceName The name of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getAsync(String sourceName, RequestOptions requestOptions, Context context) { - return getWithResponseAsync(sourceName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Retrieves a knowledge source definition. - * - * @param sourceName The name of the knowledge source 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 knowledge source definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getWithResponse(String sourceName, 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(), sourceName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Retrieves a knowledge source definition. - * - * @param sourceName The name of the knowledge source 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 knowledge source definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeSource get(String sourceName, RequestOptions requestOptions) { - return getWithResponse(sourceName, requestOptions, Context.NONE).getValue(); - } - - /** - * Lists all knowledge sources 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 the response body 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().getKnowledgeSources(), null, null)); - } - - /** - * Lists all knowledge sources 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 the response body 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().getKnowledgeSources(), null, null)); - } - - /** - * Lists all knowledge sources 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 the paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(RequestOptions requestOptions) { - return new PagedFlux<>(() -> listSinglePageAsync(requestOptions)); - } - - /** - * Lists all knowledge sources 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 the paginated response with {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux listAsync(RequestOptions requestOptions, Context context) { - return new PagedFlux<>(() -> listSinglePageAsync(requestOptions, context)); - } - - /** - * Lists all knowledge sources 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 the response body 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().getKnowledgeSources(), null, null); - } - - /** - * Lists all knowledge sources 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 the response body 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().getKnowledgeSources(), null, null); - } - - /** - * Lists all knowledge sources 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 the paginated response with {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable list(RequestOptions requestOptions) { - return new PagedIterable<>(() -> listSinglePage(requestOptions)); - } - - /** - * Lists all knowledge sources 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 the 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 knowledge source. - * - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(KnowledgeSource knowledgeSource, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> createWithResponseAsync(knowledgeSource, requestOptions, context)); - } - - /** - * Creates a new knowledge source. - * - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> createWithResponseAsync(KnowledgeSource knowledgeSource, - 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, - knowledgeSource, context); - } - - /** - * Creates a new knowledge source. - * - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(KnowledgeSource knowledgeSource, RequestOptions requestOptions) { - return createWithResponseAsync(knowledgeSource, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge source. - * - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono createAsync(KnowledgeSource knowledgeSource, RequestOptions requestOptions, - Context context) { - return createWithResponseAsync(knowledgeSource, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Creates a new knowledge source. - * - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response createWithResponse(KnowledgeSource knowledgeSource, 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, - knowledgeSource, context); - } - - /** - * Creates a new knowledge source. - * - * @param knowledgeSource The definition of the knowledge source 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 knowledge source definition. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeSource create(KnowledgeSource knowledgeSource, RequestOptions requestOptions) { - return createWithResponse(knowledgeSource, requestOptions, Context.NONE).getValue(); - } - - /** - * Returns the current status and synchronization history of a knowledge source. - * - * @param sourceName The name of the knowledge source 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 status and synchronization history of a knowledge source along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getStatusWithResponseAsync(String sourceName, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> getStatusWithResponseAsync(sourceName, requestOptions, context)); - } - - /** - * Returns the current status and synchronization history of a knowledge source. - * - * @param sourceName The name of the knowledge source 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 status and synchronization history of a knowledge source along with {@link Response} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> getStatusWithResponseAsync(String sourceName, - 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(), sourceName, xMsClientRequestId, this.client.getApiVersion(), - accept, context); - } - - /** - * Returns the current status and synchronization history of a knowledge source. - * - * @param sourceName The name of the knowledge source 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 status and synchronization history of a knowledge source on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getStatusAsync(String sourceName, RequestOptions requestOptions) { - return getStatusWithResponseAsync(sourceName, requestOptions).flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the current status and synchronization history of a knowledge source. - * - * @param sourceName The name of the knowledge source 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 status and synchronization history of a knowledge source on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono getStatusAsync(String sourceName, RequestOptions requestOptions, - Context context) { - return getStatusWithResponseAsync(sourceName, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * Returns the current status and synchronization history of a knowledge source. - * - * @param sourceName The name of the knowledge source 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 status and synchronization history of a knowledge source along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response getStatusWithResponse(String sourceName, 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(), sourceName, xMsClientRequestId, - this.client.getApiVersion(), accept, context); - } - - /** - * Returns the current status and synchronization history of a knowledge source. - * - * @param sourceName The name of the knowledge source 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 status and synchronization history of a knowledge source. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeSourceStatus getStatus(String sourceName, RequestOptions requestOptions) { - return getStatusWithResponse(sourceName, 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 a89899518735..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/SearchServiceClientImpl.java +++ /dev/null @@ -1,570 +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.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.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.ListIndexStatsSummary; -import com.azure.search.documents.indexes.implementation.models.RequestOptions; -import com.azure.search.documents.indexes.models.IndexStatisticsSummary; -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 KnowledgeBasesImpl object to access its operations. - */ - private final KnowledgeBasesImpl knowledgeBases; - - /** - * Gets the KnowledgeBasesImpl object to access its operations. - * - * @return the KnowledgeBasesImpl object. - */ - public KnowledgeBasesImpl getKnowledgeBases() { - return this.knowledgeBases; - } - - /** - * The KnowledgeSourcesImpl object to access its operations. - */ - private final KnowledgeSourcesImpl knowledgeSources; - - /** - * Gets the KnowledgeSourcesImpl object to access its operations. - * - * @return the KnowledgeSourcesImpl object. - */ - public KnowledgeSourcesImpl getKnowledgeSources() { - return this.knowledgeSources; - } - - /** - * 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.knowledgeBases = new KnowledgeBasesImpl(this); - this.knowledgeSources = new KnowledgeSourcesImpl(this); - 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); - - @Get("/indexstats") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> getIndexStatsSummary(@HostParam("endpoint") String endpoint, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, @HeaderParam("Accept") String accept, Context context); - - @Get("/indexstats") - @ExpectedResponses({ 200 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response getIndexStatsSummarySync(@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(); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 request to retrieve stats summary of all indexes along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - getIndexStatsSummarySinglePageAsync(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.getIndexStatsSummary(this.getEndpoint(), xMsClientRequestId, - this.getApiVersion(), accept, context)) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexesStatistics(), null, null)); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 request to retrieve stats summary of all indexes along with {@link PagedResponse} on - * successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - getIndexStatsSummarySinglePageAsync(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 - .getIndexStatsSummary(this.getEndpoint(), xMsClientRequestId, this.getApiVersion(), accept, context) - .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexesStatistics(), null, null)); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 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. - * - * @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 request to retrieve stats summary of all indexes as paginated response with - * {@link PagedFlux}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedFlux getIndexStatsSummaryAsync(RequestOptions requestOptions, Context context) { - return new PagedFlux<>(() -> getIndexStatsSummarySinglePageAsync(requestOptions, context)); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 request to retrieve stats summary of all indexes along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getIndexStatsSummarySinglePage(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.getIndexStatsSummarySync(this.getEndpoint(), xMsClientRequestId, - this.getApiVersion(), accept, Context.NONE); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexesStatistics(), null, null); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 request to retrieve stats summary of all indexes along with {@link PagedResponse}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public PagedResponse getIndexStatsSummarySinglePage(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.getIndexStatsSummarySync(this.getEndpoint(), xMsClientRequestId, - this.getApiVersion(), accept, context); - return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), - res.getValue().getIndexesStatistics(), null, null); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 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)); - } - - /** - * Retrieves a summary of statistics for all indexes in the 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 request to retrieve stats summary of all indexes as paginated response with - * {@link PagedIterable}. - */ - @ServiceMethod(returns = ReturnType.COLLECTION) - public PagedIterable getIndexStatsSummary(RequestOptions requestOptions, Context context) { - return new PagedIterable<>(() -> getIndexStatsSummarySinglePage(requestOptions, context)); - } -} 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 25382361a202..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 = "SearchServiceClientSkillsets") - 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 b0e0e6a0cd9a..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 = "SearchServiceClientSynonymMaps") - 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/AnalyzeRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeRequest.java deleted file mode 100644 index fb5f358876e4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/AnalyzeRequest.java +++ /dev/null @@ -1,277 +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.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; - -/** - * Specifies some text and analysis components used to break that text into tokens. - */ -@Fluent -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. - */ - @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. - */ - @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. - */ - @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. - */ - @Generated - private List charFilters; - - /** - * Creates an instance of AnalyzeRequest class. - * - * @param text the text value to set. - */ - @Generated - public AnalyzeRequest(String text) { - this.text = text; - } - - /** - * Get the text property: The text to break into tokens. - * - * @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. - * - * @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. - * - * @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. - * - * @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. - * - * @param tokenizer the tokenizer value to set. - * @return the AnalyzeRequest object itself. - */ - @Generated - public AnalyzeRequest setTokenizer(LexicalTokenizerName tokenizer) { - this.tokenizer = tokenizer; - return this; - } - - /** - * Get the normalizer property: The name of the normalizer to use to normalize the given text. - * - * @return the normalizer value. - */ - @Generated - public LexicalNormalizerName getNormalizer() { - return this.normalizer; - } - - /** - * Set the normalizer property: The name of the normalizer to use to normalize the given text. - * - * @param normalizer the normalizer value to set. - * @return the AnalyzeRequest object itself. - */ - @Generated - public AnalyzeRequest setNormalizer(LexicalNormalizerName normalizer) { - this.normalizer = normalizer; - return this; - } - - /** - * Get the tokenFilters property: An optional list of token filters to use when breaking the given text. This - * parameter can only be set when using the tokenizer parameter. - * - * @return the tokenFilters value. - */ - @Generated - public List getTokenFilters() { - return this.tokenFilters; - } - - /** - * Set the tokenFilters property: An optional list of token filters to use when breaking the given text. This - * parameter can only be set when using the tokenizer parameter. - * - * @param tokenFilters the tokenFilters value to set. - * @return the AnalyzeRequest object itself. - */ - @Generated - public AnalyzeRequest setTokenFilters(List tokenFilters) { - this.tokenFilters = tokenFilters; - return this; - } - - /** - * Get the charFilters property: An optional list of character filters to use when breaking the given text. This - * parameter can only be set when using the tokenizer parameter. - * - * @return the charFilters value. - */ - @Generated - public List getCharFilters() { - return this.charFilters; - } - - /** - * Set the charFilters property: An optional list of character filters to use when breaking the given text. This - * parameter can only be set when using the tokenizer parameter. - * - * @param charFilters the charFilters value to set. - * @return the AnalyzeRequest object itself. - */ - @Generated - public AnalyzeRequest setCharFilters(List charFilters) { - this.charFilters = charFilters; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("text", this.text); - jsonWriter.writeStringField("analyzer", this.analyzer == null ? null : this.analyzer.toString()); - jsonWriter.writeStringField("tokenizer", this.tokenizer == null ? null : this.tokenizer.toString()); - jsonWriter.writeStringField("normalizer", this.normalizer == null ? null : this.normalizer.toString()); - jsonWriter.writeArrayField("tokenFilters", this.tokenFilters, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeArrayField("charFilters", this.charFilters, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of AnalyzeRequest from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of AnalyzeRequest 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 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; - LexicalNormalizerName normalizer = null; - List tokenFilters = null; - List charFilters = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("text".equals(fieldName)) { - text = reader.getString(); - textFound = true; - } else if ("analyzer".equals(fieldName)) { - analyzer = LexicalAnalyzerName.fromString(reader.getString()); - } else if ("tokenizer".equals(fieldName)) { - tokenizer = LexicalTokenizerName.fromString(reader.getString()); - } else if ("normalizer".equals(fieldName)) { - normalizer = LexicalNormalizerName.fromString(reader.getString()); - } else if ("tokenFilters".equals(fieldName)) { - tokenFilters = reader.readArray(reader1 -> TokenFilterName.fromString(reader1.getString())); - } else if ("charFilters".equals(fieldName)) { - charFilters = reader.readArray(reader1 -> CharFilterName.fromString(reader1.getString())); - } else { - reader.skipChildren(); - } - } - if (textFound) { - 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"); - }); - } -} 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 dd06eb25ffe9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EdgeNGramTokenFilterV1.java +++ /dev/null @@ -1,199 +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.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. - */ -@Fluent -public final class EdgeNGramTokenFilterV1 extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. - */ - @Generated - private String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenFilter"; - - /* - * The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - */ - @Generated - private Integer minGram; - - /* - * The maximum n-gram length. Default is 2. - */ - @Generated - private Integer maxGram; - - /* - * Specifies which side of the input the n-gram should be generated from. Default is "front". - */ - @Generated - private EdgeNGramTokenFilterSide side; - - /** - * Creates an instance of EdgeNGramTokenFilterV1 class. - * - * @param name the name value to set. - */ - @Generated - public EdgeNGramTokenFilterV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * - * @return the odataType value. - */ - @Generated - @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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @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". - * - * @param side the side value to set. - * @return the EdgeNGramTokenFilterV1 object itself. - */ - @Generated - public EdgeNGramTokenFilterV1 setSide(EdgeNGramTokenFilterSide side) { - this.side = side; - 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("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. - */ - @Generated - 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/EntityRecognitionSkillV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV1.java deleted file mode 100644 index b267bec326ed..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/EntityRecognitionSkillV1.java +++ /dev/null @@ -1,311 +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.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 { - /* - * A URI fragment specifying the type of skill. - */ - @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. - */ - @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. - */ - @Generated - private Double minimumPrecision; - - /** - * Creates an instance of EntityRecognitionSkillV1 class. - * - * @param inputs the inputs value to set. - * @param outputs the outputs value to set. - */ - @Generated - public EntityRecognitionSkillV1(List inputs, List outputs) { - super(inputs, outputs); - } - - /** - * Get the odataType property: A URI fragment specifying the type of skill. - * - * @return the odataType value. - */ - @Generated - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the categories property: A list of entity categories that should be extracted. - * - * @return the categories value. - */ - @Generated - public List getCategories() { - return this.categories; - } - - /** - * 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. - */ - @Generated - public EntityRecognitionSkillV1 setCategories(List categories) { - this.categories = categories; - return this; - } - - /** - * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * - * @return the defaultLanguageCode value. - */ - @Generated - public EntityRecognitionSkillLanguage 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 EntityRecognitionSkillV1 object itself. - */ - @Generated - public EntityRecognitionSkillV1 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. - * - * @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. - * - * @param includeTypelessEntities the includeTypelessEntities value to set. - * @return the EntityRecognitionSkillV1 object itself. - */ - @Generated - public EntityRecognitionSkillV1 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. - * - * @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. - * - * @param minimumPrecision the minimumPrecision value to set. - * @return the EntityRecognitionSkillV1 object itself. - */ - @Generated - public EntityRecognitionSkillV1 setMinimumPrecision(Double minimumPrecision) { - this.minimumPrecision = minimumPrecision; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public EntityRecognitionSkillV1 setName(String name) { - super.setName(name); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public EntityRecognitionSkillV1 setDescription(String description) { - super.setDescription(description); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public EntityRecognitionSkillV1 setContext(String context) { - super.setContext(context); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("outputs", getOutputs(), (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("name", getName()); - jsonWriter.writeStringField("description", getDescription()); - jsonWriter.writeStringField("context", getContext()); - jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeArrayField("categories", this.categories, - (writer, element) -> writer.writeString(element == null ? null : element.toString())); - jsonWriter.writeStringField("defaultLanguageCode", - this.defaultLanguageCode == null ? null : this.defaultLanguageCode.toString()); - jsonWriter.writeBooleanField("includeTypelessEntities", this.includeTypelessEntities); - jsonWriter.writeNumberField("minimumPrecision", this.minimumPrecision); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of EntityRecognitionSkillV1 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. - * @throws IllegalStateException If the deserialized JSON object was missing any required properties. - * @throws IOException If an error occurs while reading the EntityRecognitionSkillV1. - */ - @Generated - public static EntityRecognitionSkillV1 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.EntityRecognitionSkill"; - List categories = null; - EntityRecognitionSkillLanguage defaultLanguageCode = null; - Boolean includeTypelessEntities = null; - Double minimumPrecision = 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)) { - description = reader.getString(); - } else if ("context".equals(fieldName)) { - context = reader.getString(); - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); - } else if ("categories".equals(fieldName)) { - categories = reader.readArray(reader1 -> EntityCategory.fromString(reader1.getString())); - } else if ("defaultLanguageCode".equals(fieldName)) { - defaultLanguageCode = EntityRecognitionSkillLanguage.fromString(reader.getString()); - } else if ("includeTypelessEntities".equals(fieldName)) { - includeTypelessEntities = reader.getNullable(JsonReader::getBoolean); - } else if ("minimumPrecision".equals(fieldName)) { - minimumPrecision = reader.getNullable(JsonReader::getDouble); - } else { - 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; - - 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)); - }); - } -} 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 48e780a4d40a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorAdditionalInfo.java +++ /dev/null @@ -1,99 +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.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; - -/** - * The resource management error additional info. - */ -@Immutable -public final class ErrorAdditionalInfo implements JsonSerializable { - /* - * The additional info type. - */ - @Generated - private String type; - - /* - * The additional info. - */ - @Generated - private Object info; - - /** - * Creates an instance of ErrorAdditionalInfo class. - */ - @Generated - public ErrorAdditionalInfo() { - } - - /** - * Get the type property: The additional info type. - * - * @return the type value. - */ - @Generated - public String getType() { - return this.type; - } - - /** - * Get the info property: The additional info. - * - * @return the info value. - */ - @Generated - public Object getInfo() { - return this.info; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 8f07be547010..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorDetail.java +++ /dev/null @@ -1,157 +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.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.List; - -/** - * The error detail. - */ -@Immutable -public final class ErrorDetail implements JsonSerializable { - /* - * The error code. - */ - @Generated - private String code; - - /* - * The error message. - */ - @Generated - private String message; - - /* - * The error target. - */ - @Generated - private String target; - - /* - * The error details. - */ - @Generated - private List details; - - /* - * The error additional info. - */ - @Generated - private List additionalInfo; - - /** - * Creates an instance of ErrorDetail class. - */ - @Generated - public ErrorDetail() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - @Generated - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - @Generated - public String getMessage() { - return this.message; - } - - /** - * Get the target property: The error target. - * - * @return the target value. - */ - @Generated - public String getTarget() { - return this.target; - } - - /** - * Get the details property: The error details. - * - * @return the details value. - */ - @Generated - public List getDetails() { - return this.details; - } - - /** - * Get the additionalInfo property: The error additional info. - * - * @return the additionalInfo value. - */ - @Generated - public List getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 ff995927bb73..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ErrorResponse.java +++ /dev/null @@ -1,97 +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.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; - -/** - * 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. - */ - @Generated - private ErrorDetail error; - - /** - * Creates an instance of ErrorResponse class. - */ - @Generated - public ErrorResponse() { - } - - /** - * Get the error property: The error object. - * - * @return the error value. - */ - @Generated - 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. - */ - @Generated - public ErrorResponse setError(ErrorDetail error) { - this.error = error; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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 3f0939aa3e09..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/KeywordTokenizerV1.java +++ /dev/null @@ -1,131 +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.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. - */ -@Fluent -public final class KeywordTokenizerV1 extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. - */ - @Generated - private String odataType = "#Microsoft.Azure.Search.KeywordTokenizer"; - - /* - * The read buffer size in bytes. Default is 256. - */ - @Generated - private Integer bufferSize; - - /** - * Creates an instance of KeywordTokenizerV1 class. - * - * @param name the name value to set. - */ - @Generated - public KeywordTokenizerV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * - * @return the odataType value. - */ - @Generated - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the bufferSize property: The read buffer size in bytes. Default is 256. - * - * @return the bufferSize value. - */ - @Generated - 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. - */ - @Generated - public KeywordTokenizerV1 setBufferSize(Integer bufferSize) { - this.bufferSize = bufferSize; - 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("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. - */ - @Generated - 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 433cefa150c9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListAliasesResult.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.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.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. - */ - @Generated - private final List aliases; - - /** - * Creates an instance of ListAliasesResult class. - * - * @param aliases the aliases value to set. - */ - @Generated - public ListAliasesResult(List aliases) { - this.aliases = aliases; - } - - /** - * Get the aliases property: The aliases in the Search service. - * - * @return the aliases value. - */ - @Generated - public List getAliases() { - return this.aliases; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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/ListIndexStatsSummary.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexStatsSummary.java deleted file mode 100644 index 51c1697ea380..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexStatsSummary.java +++ /dev/null @@ -1,92 +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.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.IndexStatisticsSummary; -import java.io.IOException; -import java.util.List; - -/** - * Response from a request to retrieve stats summary of all indexes. If successful, it includes the stats of each index - * in the service. - */ -@Immutable -public final class ListIndexStatsSummary implements JsonSerializable { - /* - * The Statistics summary of all indexes in the Search service. - */ - @Generated - private final List indexesStatistics; - - /** - * Creates an instance of ListIndexStatsSummary class. - * - * @param indexesStatistics the indexesStatistics value to set. - */ - @Generated - public ListIndexStatsSummary(List indexesStatistics) { - this.indexesStatistics = indexesStatistics; - } - - /** - * Get the indexesStatistics property: The Statistics summary of all indexes in the Search service. - * - * @return the indexesStatistics value. - */ - @Generated - public List getIndexesStatistics() { - return this.indexesStatistics; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ListIndexStatsSummary from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ListIndexStatsSummary 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 ListIndexStatsSummary. - */ - @Generated - public static ListIndexStatsSummary fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean indexesStatisticsFound = false; - List indexesStatistics = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - indexesStatistics = reader.readArray(reader1 -> IndexStatisticsSummary.fromJson(reader1)); - indexesStatisticsFound = true; - } else { - reader.skipChildren(); - } - } - if (indexesStatisticsFound) { - return new ListIndexStatsSummary(indexesStatistics); - } - 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 f2ab5c4dd1e6..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListIndexesResult.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.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.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. - */ - @Generated - private final List indexes; - - /** - * Creates an instance of ListIndexesResult class. - * - * @param indexes the indexes value to set. - */ - @Generated - public ListIndexesResult(List indexes) { - this.indexes = indexes; - } - - /** - * Get the indexes property: The indexes in the Search service. - * - * @return the indexes value. - */ - @Generated - public List getIndexes() { - return this.indexes; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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/ListKnowledgeBasesResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListKnowledgeBasesResult.java deleted file mode 100644 index 69f18c3127af..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListKnowledgeBasesResult.java +++ /dev/null @@ -1,92 +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.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.KnowledgeBase; -import java.io.IOException; -import java.util.List; - -/** - * The ListKnowledgeBasesResult model. - */ -@Immutable -public final class ListKnowledgeBasesResult implements JsonSerializable { - /* - * The value property. - */ - @Generated - private final List knowledgeBases; - - /** - * Creates an instance of ListKnowledgeBasesResult class. - * - * @param knowledgeBases the knowledgeBases value to set. - */ - @Generated - public ListKnowledgeBasesResult(List knowledgeBases) { - this.knowledgeBases = knowledgeBases; - } - - /** - * Get the knowledgeBases property: The value property. - * - * @return the knowledgeBases value. - */ - @Generated - public List getKnowledgeBases() { - return this.knowledgeBases; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.knowledgeBases, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ListKnowledgeBasesResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ListKnowledgeBasesResult 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 ListKnowledgeBasesResult. - */ - @Generated - public static ListKnowledgeBasesResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean knowledgeBasesFound = false; - List knowledgeBases = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - knowledgeBases = reader.readArray(reader1 -> KnowledgeBase.fromJson(reader1)); - knowledgeBasesFound = true; - } else { - reader.skipChildren(); - } - } - if (knowledgeBasesFound) { - return new ListKnowledgeBasesResult(knowledgeBases); - } - 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/ListKnowledgeSourcesResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListKnowledgeSourcesResult.java deleted file mode 100644 index 83a17d1cf434..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/ListKnowledgeSourcesResult.java +++ /dev/null @@ -1,92 +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.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.KnowledgeSource; -import java.io.IOException; -import java.util.List; - -/** - * The ListKnowledgeSourcesResult model. - */ -@Immutable -public final class ListKnowledgeSourcesResult implements JsonSerializable { - /* - * The value property. - */ - @Generated - private final List knowledgeSources; - - /** - * Creates an instance of ListKnowledgeSourcesResult class. - * - * @param knowledgeSources the knowledgeSources value to set. - */ - @Generated - public ListKnowledgeSourcesResult(List knowledgeSources) { - this.knowledgeSources = knowledgeSources; - } - - /** - * Get the knowledgeSources property: The value property. - * - * @return the knowledgeSources value. - */ - @Generated - public List getKnowledgeSources() { - return this.knowledgeSources; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("value", this.knowledgeSources, (writer, element) -> writer.writeJson(element)); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of ListKnowledgeSourcesResult from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of ListKnowledgeSourcesResult 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 ListKnowledgeSourcesResult. - */ - @Generated - public static ListKnowledgeSourcesResult fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean knowledgeSourcesFound = false; - List knowledgeSources = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("value".equals(fieldName)) { - knowledgeSources = reader.readArray(reader1 -> KnowledgeSource.fromJson(reader1)); - knowledgeSourcesFound = true; - } else { - reader.skipChildren(); - } - } - if (knowledgeSourcesFound) { - return new ListKnowledgeSourcesResult(knowledgeSources); - } - 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 6266caba966a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/LuceneStandardTokenizerV1.java +++ /dev/null @@ -1,133 +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.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. - */ -@Fluent -public final class LuceneStandardTokenizerV1 extends LexicalTokenizer { - /* - * A URI fragment specifying the type of tokenizer. - */ - @Generated - private String odataType = "#Microsoft.Azure.Search.StandardTokenizer"; - - /* - * The maximum token length. Default is 255. Tokens longer than the maximum length are split. - */ - @Generated - private Integer maxTokenLength; - - /** - * Creates an instance of LuceneStandardTokenizerV1 class. - * - * @param name the name value to set. - */ - @Generated - public LuceneStandardTokenizerV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of tokenizer. - * - * @return the odataType value. - */ - @Generated - @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. - */ - @Generated - 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. - */ - @Generated - public LuceneStandardTokenizerV1 setMaxTokenLength(Integer maxTokenLength) { - this.maxTokenLength = maxTokenLength; - 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("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. - */ - @Generated - 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 3379b81291db..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/NGramTokenFilterV1.java +++ /dev/null @@ -1,164 +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.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. - */ -@Fluent -public final class NGramTokenFilterV1 extends TokenFilter { - /* - * A URI fragment specifying the type of token filter. - */ - @Generated - private String odataType = "#Microsoft.Azure.Search.NGramTokenFilter"; - - /* - * The minimum n-gram length. Default is 1. Must be less than the value of maxGram. - */ - @Generated - private Integer minGram; - - /* - * The maximum n-gram length. Default is 2. - */ - @Generated - private Integer maxGram; - - /** - * Creates an instance of NGramTokenFilterV1 class. - * - * @param name the name value to set. - */ - @Generated - public NGramTokenFilterV1(String name) { - super(name); - } - - /** - * Get the odataType property: A URI fragment specifying the type of token filter. - * - * @return the odataType value. - */ - @Generated - @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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - 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. - */ - @Generated - public NGramTokenFilterV1 setMaxGram(Integer maxGram) { - this.maxGram = maxGram; - 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("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. - */ - @Generated - 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 b3cec5412e53..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/RequestOptions.java +++ /dev/null @@ -1,52 +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.core.annotation.Generated; -import java.util.UUID; - -/** - * Parameter group. - */ -@Fluent -public final class RequestOptions { - /* - * The tracking ID sent with the request to help with debugging. - */ - @Generated - private UUID xMsClientRequestId; - - /** - * Creates an instance of RequestOptions class. - */ - @Generated - public RequestOptions() { - } - - /** - * Get the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @return the xMsClientRequestId value. - */ - @Generated - 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. - */ - @Generated - 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/SentimentSkillV1.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV1.java deleted file mode 100644 index 92a26c6f8b8c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/implementation/models/SentimentSkillV1.java +++ /dev/null @@ -1,198 +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.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 { - /* - * A URI fragment specifying the type of skill. - */ - @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. - * - * @param inputs the inputs value to set. - * @param outputs the outputs value to set. - */ - @Generated - public SentimentSkillV1(List inputs, List outputs) { - super(inputs, outputs); - } - - /** - * Get the odataType property: A URI fragment specifying the type of skill. - * - * @return the odataType value. - */ - @Generated - @Override - public String getOdataType() { - return this.odataType; - } - - /** - * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * - * @return the defaultLanguageCode value. - */ - @Generated - public SentimentSkillLanguage 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 SentimentSkillV1 object itself. - */ - @Generated - public SentimentSkillV1 setDefaultLanguageCode(SentimentSkillLanguage defaultLanguageCode) { - this.defaultLanguageCode = defaultLanguageCode; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public SentimentSkillV1 setName(String name) { - super.setName(name); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public SentimentSkillV1 setDescription(String description) { - super.setDescription(description); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public SentimentSkillV1 setContext(String context) { - super.setContext(context); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("outputs", getOutputs(), (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("name", getName()); - jsonWriter.writeStringField("description", getDescription()); - jsonWriter.writeStringField("context", getContext()); - jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeStringField("defaultLanguageCode", - this.defaultLanguageCode == null ? null : this.defaultLanguageCode.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SentimentSkillV1 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 - * 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. - */ - @Generated - public static SentimentSkillV1 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.SentimentSkill"; - SentimentSkillLanguage defaultLanguageCode = 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)) { - description = reader.getString(); - } else if ("context".equals(fieldName)) { - context = reader.getString(); - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); - } else if ("defaultLanguageCode".equals(fieldName)) { - defaultLanguageCode = SentimentSkillLanguage.fromString(reader.getString()); - } else { - 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)); - }); - } -} 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/AIFoundryModelCatalogName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java index 27cfe93d5479..a8a31ddcabb1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,42 +11,43 @@ * The name of the embedding model from the Azure AI Foundry Catalog that will be called. */ public final class AIFoundryModelCatalogName extends ExpandableStringEnum { + /** - * Static value OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32 for AIFoundryModelCatalogName. + * OpenAI-CLIP-Image-Text-Embeddings-vit-base-patch32. */ @Generated - public static final AIFoundryModelCatalogName OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VIT_BASE_PATCH32 + public static final AIFoundryModelCatalogName OPEN_AICLIPIMAGE_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 AIFoundryModelCatalogName. + * OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336. */ @Generated - public static final AIFoundryModelCatalogName OPEN_AICLIP_IMAGE_TEXT_EMBEDDINGS_VI_TLARGE_PATCH14336 + public static final AIFoundryModelCatalogName OPEN_AICLIPIMAGE_TEXT_EMBEDDINGS_VI_TLARGE_PATCH14336 = fromString("OpenAI-CLIP-Image-Text-Embeddings-ViT-Large-Patch14-336"); /** - * Static value Facebook-DinoV2-Image-Embeddings-ViT-Base for AIFoundryModelCatalogName. + * Facebook-DinoV2-Image-Embeddings-ViT-Base. */ @Generated public static final AIFoundryModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TBASE = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Base"); /** - * Static value Facebook-DinoV2-Image-Embeddings-ViT-Giant for AIFoundryModelCatalogName. + * Facebook-DinoV2-Image-Embeddings-ViT-Giant. */ @Generated public static final AIFoundryModelCatalogName FACEBOOK_DINO_V2IMAGE_EMBEDDINGS_VI_TGIANT = fromString("Facebook-DinoV2-Image-Embeddings-ViT-Giant"); /** - * Static value Cohere-embed-v3-english for AIFoundryModelCatalogName. + * Cohere-embed-v3-english. */ @Generated public static final AIFoundryModelCatalogName COHERE_EMBED_V3ENGLISH = fromString("Cohere-embed-v3-english"); /** - * Static value Cohere-embed-v3-multilingual for AIFoundryModelCatalogName. + * Cohere-embed-v3-multilingual. */ @Generated public static final AIFoundryModelCatalogName COHERE_EMBED_V3MULTILINGUAL @@ -63,7 +61,7 @@ public final class AIFoundryModelCatalogName extends ExpandableStringEnum { String description = 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 ("subdomainUrl".equals(fieldName)) { subdomainUrl = reader.getString(); - subdomainUrlFound = true; } else if ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("identity".equals(fieldName)) { @@ -154,16 +148,12 @@ public static AIServicesAccountIdentity fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (subdomainUrlFound) { - AIServicesAccountIdentity deserializedAIServicesAccountIdentity - = new AIServicesAccountIdentity(subdomainUrl); - deserializedAIServicesAccountIdentity.setDescription(description); - deserializedAIServicesAccountIdentity.odataType = odataType; - deserializedAIServicesAccountIdentity.identity = identity; - - return deserializedAIServicesAccountIdentity; - } - throw new IllegalStateException("Missing required property: subdomainUrl"); + AIServicesAccountIdentity deserializedAIServicesAccountIdentity + = new AIServicesAccountIdentity(subdomainUrl); + deserializedAIServicesAccountIdentity.setDescription(description); + deserializedAIServicesAccountIdentity.odataType = odataType; + deserializedAIServicesAccountIdentity.identity = identity; + 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/indexes/models/AIServicesAccountKey.java index 605b25de3ed8..8428265f9c04 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/indexes/models/AIServicesAccountKey.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,8 +9,6 @@ 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 @@ -21,8 +16,9 @@ */ @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"; @@ -41,7 +37,7 @@ public final class AIServicesAccountKey extends CognitiveServicesAccount { /** * Creates an instance of AIServicesAccountKey class. - * + * * @param key the key value to set. * @param subdomainUrl the subdomainUrl value to set. */ @@ -52,9 +48,8 @@ public AIServicesAccountKey(String key, String 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 @@ -65,7 +60,7 @@ 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 @@ -75,7 +70,7 @@ public String getKey() { /** * Get the subdomainUrl property: The subdomain url for the corresponding AI Service. - * + * * @return the subdomainUrl value. */ @Generated @@ -109,7 +104,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AIServicesAccountKey from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AIServicesAccountKey if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -120,46 +115,28 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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) { 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 ("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; - - 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)); + AIServicesAccountKey deserializedAIServicesAccountKey = new AIServicesAccountKey(key, subdomainUrl); + deserializedAIServicesAccountKey.setDescription(description); + deserializedAIServicesAccountKey.odataType = odataType; + 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/indexes/models/AIServicesVisionParameters.java index 9e0bb0f903e2..037d6f46156d 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/indexes/models/AIServicesVisionParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,14 +10,13 @@ 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. */ @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. @@ -50,7 +46,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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -181,24 +172,11 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + AIServicesVisionParameters deserializedAIServicesVisionParameters + = new AIServicesVisionParameters(modelVersion, resourceUri); + deserializedAIServicesVisionParameters.apiKey = apiKey; + deserializedAIServicesVisionParameters.authIdentity = authIdentity; + 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/indexes/models/AIServicesVisionVectorizer.java index 13c16e3893bf..441a243db993 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/indexes/models/AIServicesVisionVectorizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -14,12 +11,13 @@ 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; @@ -28,11 +26,11 @@ public final class AIServicesVisionVectorizer extends VectorSearchVectorizer { * Contains the parameters specific to AI Services Vision embedding vectorization. */ @Generated - private AIServicesVisionParameters aIServicesVisionParameters; + private AIServicesVisionParameters aiServicesVisionParameters; /** * Creates an instance of AIServicesVisionVectorizer class. - * + * * @param vectorizerName the vectorizerName value to set. */ @Generated @@ -41,8 +39,8 @@ public AIServicesVisionVectorizer(String 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 @@ -52,27 +50,27 @@ public VectorSearchVectorizerKind getKind() { } /** - * Get the aIServicesVisionParameters property: Contains the parameters specific to AI Services Vision embedding + * Get the aiServicesVisionParameters property: Contains the parameters specific to AI Services Vision embedding * vectorization. - * - * @return the aIServicesVisionParameters value. + * + * @return the aiServicesVisionParameters value. */ @Generated - public AIServicesVisionParameters getAIServicesVisionParameters() { - return this.aIServicesVisionParameters; + public AIServicesVisionParameters getAiServicesVisionParameters() { + return this.aiServicesVisionParameters; } /** - * Set the aIServicesVisionParameters property: Contains the parameters specific to AI Services Vision embedding + * Set the aiServicesVisionParameters property: Contains the parameters specific to AI Services Vision embedding * vectorization. - * - * @param aIServicesVisionParameters the aIServicesVisionParameters value to set. + * + * @param aiServicesVisionParameters the aiServicesVisionParameters value to set. * @return the AIServicesVisionVectorizer object itself. */ @Generated public AIServicesVisionVectorizer - setAIServicesVisionParameters(AIServicesVisionParameters aIServicesVisionParameters) { - this.aIServicesVisionParameters = aIServicesVisionParameters; + setAiServicesVisionParameters(AIServicesVisionParameters aiServicesVisionParameters) { + this.aiServicesVisionParameters = aiServicesVisionParameters; return this; } @@ -85,13 +83,13 @@ 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(); } /** * Reads an instance of AIServicesVisionVectorizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AIServicesVisionVectorizer if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -101,34 +99,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; + AIServicesVisionParameters aiServicesVisionParameters = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("aiServicesVisionParameters".equals(fieldName)) { - aIServicesVisionParameters = AIServicesVisionParameters.fromJson(reader); + aiServicesVisionParameters = AIServicesVisionParameters.fromJson(reader); } else { reader.skipChildren(); } } - if (vectorizerNameFound) { - AIServicesVisionVectorizer deserializedAIServicesVisionVectorizer - = new AIServicesVisionVectorizer(vectorizerName); - deserializedAIServicesVisionVectorizer.kind = kind; - deserializedAIServicesVisionVectorizer.aIServicesVisionParameters = aIServicesVisionParameters; - - return deserializedAIServicesVisionVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + AIServicesVisionVectorizer deserializedAIServicesVisionVectorizer + = new AIServicesVisionVectorizer(vectorizerName); + deserializedAIServicesVisionVectorizer.kind = kind; + deserializedAIServicesVisionVectorizer.aiServicesVisionParameters = aiServicesVisionParameters; + return deserializedAIServicesVisionVectorizer; }); } } 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/indexes/models/AnalyzeResult.java similarity index 81% 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/indexes/models/AnalyzeResult.java index 44012d2a3504..69e5e5783137 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/indexes/models/AnalyzeResult.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -12,7 +9,6 @@ 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; @@ -21,6 +17,7 @@ */ @Immutable public final class AnalyzeResult implements JsonSerializable { + /* * The list of tokens returned by the analyzer specified in the request. */ @@ -29,7 +26,7 @@ public final class AnalyzeResult implements JsonSerializable { /** * Creates an instance of AnalyzeResult class. - * + * * @param tokens the tokens value to set. */ @Generated @@ -39,7 +36,7 @@ public AnalyzeResult(List tokens) { /** * Get the tokens property: The list of tokens returned by the analyzer specified in the request. - * + * * @return the tokens value. */ @Generated @@ -60,7 +57,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AnalyzeResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AnalyzeResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -70,23 +67,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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(); reader.nextToken(); - 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/AnalyzeTextOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AnalyzeTextOptions.java index f8acc59b9739..dad549f90877 100644 --- 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 @@ -1,72 +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.indexes.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; /** - * Specifies some text and analysis components used to break that text into - * tokens. + * Specifies some text and analysis components used to break that text into tokens. */ @Fluent -public final class AnalyzeTextOptions { +public final class AnalyzeTextOptions 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. + * 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. */ - private final LexicalAnalyzerName analyzerName; + @Generated + private LexicalAnalyzerName analyzerName; /* - * The name of the tokenizer to use to break the given text. + * 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. */ - private final LexicalTokenizerName tokenizerName; + @Generated + private LexicalTokenizerName tokenizerName; /* - * An optional list of token filters to use when breaking the given text. + * The name of the normalizer to use to normalize the given text. */ - private List tokenFilters; + @Generated + private LexicalNormalizerName normalizerName; /* - * An optional list of character filters to use when breaking the given - * text. + * An optional list of token filters to use when breaking the given text. This parameter can only be set when using + * the tokenizer parameter. */ - private List charFilters; + @Generated + private List tokenFilters; /* - * The name of the normalizer to use to normalize the given text. + * An optional list of character filters to use when breaking the given text. This parameter can only be set when + * using the tokenizer parameter. */ - private LexicalNormalizerName normalizerName; - - /** - * 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; - } + @Generated + private List charFilters; /** - * Constructor to {@link AnalyzeTextOptions} which takes tokenizerName. + * Creates an instance of AnalyzeTextOptions class. * - * @param text The text break into tokens. - * @param tokenizerName The name of the tokenizer to use to break the given text. + * @param text the text value to set. */ - public AnalyzeTextOptions(String text, LexicalTokenizerName tokenizerName) { + @Generated + public AnalyzeTextOptions(String text) { this.text = text; - this.tokenizerName = tokenizerName; - this.analyzerName = null; } /** @@ -74,42 +74,100 @@ public AnalyzeTextOptions(String text, LexicalTokenizerName tokenizerName) { * * @return the text value. */ + @Generated public String getText() { return this.text; } /** - * Get the analyzer name property: The name of the analyzer to use to break the given text. + * Get the analyzerName 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. + * @return the analyzerName value. */ + @Generated public LexicalAnalyzerName getAnalyzerName() { return this.analyzerName; } /** - * Get the tokenizer name property: The name of the tokenizer to use to break the given text. + * Set the analyzerName 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 analyzerName the analyzerName value to set. + * @return the AnalyzeTextOptions object itself. + */ + @Generated + public AnalyzeTextOptions setAnalyzerName(LexicalAnalyzerName analyzerName) { + this.analyzerName = analyzerName; + return this; + } + + /** + * Get the tokenizerName 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. + * @return the tokenizerName value. */ + @Generated public LexicalTokenizerName getTokenizerName() { return this.tokenizerName; } /** - * Get the tokenFilters property: An optional list of token filters to use when breaking the given text. + * Set the tokenizerName 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 tokenizerName the tokenizerName value to set. + * @return the AnalyzeTextOptions object itself. + */ + @Generated + public AnalyzeTextOptions setTokenizerName(LexicalTokenizerName tokenizerName) { + this.tokenizerName = tokenizerName; + return this; + } + + /** + * Get the normalizerName property: The name of the normalizer to use to normalize the given text. + * + * @return the normalizerName value. + */ + @Generated + public LexicalNormalizerName getNormalizerName() { + return this.normalizerName; + } + + /** + * Set the normalizerName property: The name of the normalizer to use to normalize the given text. + * + * @param normalizerName the normalizerName value to set. + * @return the AnalyzeTextOptions object itself. + */ + @Generated + public AnalyzeTextOptions setNormalizerName(LexicalNormalizerName normalizerName) { + this.normalizerName = normalizerName; + return this; + } + + /** + * Get the tokenFilters property: An optional list of token filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. * * @return the tokenFilters value. */ + @Generated public List getTokenFilters() { return this.tokenFilters; } /** - * Set the tokenFilters property: An optional list of token filters to use when breaking the given text. + * Set the tokenFilters property: An optional list of token filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. * * @param tokenFilters the tokenFilters value to set. - * @return the AnalyzeRequest object itself. + * @return the AnalyzeTextOptions object itself. */ public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); @@ -117,19 +175,35 @@ public AnalyzeTextOptions setTokenFilters(TokenFilterName... tokenFilters) { } /** - * Get the charFilters property: An optional list of character filters to use when breaking the given text. + * Set the tokenFilters property: An optional list of token filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. + * + * @param tokenFilters the tokenFilters value to set. + * @return the AnalyzeTextOptions object itself. + */ + @Generated + public AnalyzeTextOptions setTokenFilters(List tokenFilters) { + this.tokenFilters = tokenFilters; + return this; + } + + /** + * Get the charFilters property: An optional list of character filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. * * @return the charFilters value. */ + @Generated public List getCharFilters() { return this.charFilters; } /** - * Set the charFilters property: An optional list of character filters to use when breaking the given text. + * Set the charFilters property: An optional list of character filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. * * @param charFilters the charFilters value to set. - * @return the AnalyzeRequest object itself. + * @return the AnalyzeTextOptions object itself. */ public AnalyzeTextOptions setCharFilters(CharFilterName... charFilters) { this.charFilters = (charFilters == null) ? null : Arrays.asList(charFilters); @@ -137,22 +211,80 @@ public AnalyzeTextOptions setCharFilters(CharFilterName... charFilters) { } /** - * Get the normalizer property: The name of the normalizer to use to normalize the given text. + * Set the charFilters property: An optional list of character filters to use when breaking the given text. This + * parameter can only be set when using the tokenizer parameter. * - * @return the normalizer value. + * @param charFilters the charFilters value to set. + * @return the AnalyzeTextOptions object itself. */ - public LexicalNormalizerName getNormalizerName() { - return this.normalizerName; + @Generated + public AnalyzeTextOptions setCharFilters(List charFilters) { + this.charFilters = charFilters; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("text", this.text); + jsonWriter.writeStringField("analyzer", this.analyzerName == null ? null : this.analyzerName.toString()); + jsonWriter.writeStringField("tokenizer", this.tokenizerName == null ? null : this.tokenizerName.toString()); + jsonWriter.writeStringField("normalizer", this.normalizerName == null ? null : this.normalizerName.toString()); + jsonWriter.writeArrayField("tokenFilters", this.tokenFilters, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + jsonWriter.writeArrayField("charFilters", this.charFilters, + (writer, element) -> writer.writeString(element == null ? null : element.toString())); + return jsonWriter.writeEndObject(); } /** - * Set the normalizer property: The name of the normalizer to use to normalize the given text. + * Reads an instance of AnalyzeTextOptions from the JsonReader. * - * @param normalizerName the normalizer value to set. - * @return the AnalyzeRequest object itself. + * @param jsonReader The JsonReader being read. + * @return An instance of AnalyzeTextOptions 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 AnalyzeTextOptions. */ - public AnalyzeTextOptions setNormalizerName(LexicalNormalizerName normalizerName) { - this.normalizerName = normalizerName; - return this; + @Generated + public static AnalyzeTextOptions fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String text = null; + LexicalAnalyzerName analyzerName = null; + LexicalTokenizerName tokenizerName = null; + LexicalNormalizerName normalizerName = null; + List tokenFilters = null; + List charFilters = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("text".equals(fieldName)) { + text = reader.getString(); + } else if ("analyzer".equals(fieldName)) { + analyzerName = LexicalAnalyzerName.fromString(reader.getString()); + } else if ("tokenizer".equals(fieldName)) { + tokenizerName = LexicalTokenizerName.fromString(reader.getString()); + } else if ("normalizer".equals(fieldName)) { + normalizerName = LexicalNormalizerName.fromString(reader.getString()); + } else if ("tokenFilters".equals(fieldName)) { + tokenFilters = reader.readArray(reader1 -> TokenFilterName.fromString(reader1.getString())); + } else if ("charFilters".equals(fieldName)) { + charFilters = reader.readArray(reader1 -> CharFilterName.fromString(reader1.getString())); + } else { + reader.skipChildren(); + } + } + AnalyzeTextOptions deserializedAnalyzeTextOptions = new AnalyzeTextOptions(text); + deserializedAnalyzeTextOptions.analyzerName = analyzerName; + deserializedAnalyzeTextOptions.tokenizerName = tokenizerName; + deserializedAnalyzeTextOptions.normalizerName = normalizerName; + deserializedAnalyzeTextOptions.tokenFilters = tokenFilters; + deserializedAnalyzeTextOptions.charFilters = charFilters; + return deserializedAnalyzeTextOptions; + }); } } 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/indexes/models/AnalyzedTokenInfo.java index 0fde938ae3b0..32d6ce60fda9 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/indexes/models/AnalyzedTokenInfo.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,31 +10,30 @@ 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. */ @Immutable public final class AnalyzedTokenInfo implements JsonSerializable { + /* * The token returned by the analyzer. */ @Generated - private final String token; + private String token; /* * The index of the first character of the token in the input text. */ @Generated - private final int startOffset; + private int startOffset; /* * The index of the last character of the token in the input text. */ @Generated - private final int endOffset; + private int endOffset; /* * The position of the token in the input text relative to other tokens. The first token in the input text has @@ -45,27 +41,18 @@ 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; + AnalyzedTokenInfo deserializedAnalyzedTokenInfo = new AnalyzedTokenInfo(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("token".equals(fieldName)) { - token = reader.getString(); - tokenFound = true; + deserializedAnalyzedTokenInfo.token = reader.getString(); } else if ("startOffset".equals(fieldName)) { - startOffset = reader.getInt(); - startOffsetFound = true; + deserializedAnalyzedTokenInfo.startOffset = reader.getInt(); } else if ("endOffset".equals(fieldName)) { - endOffset = reader.getInt(); - endOffsetFound = true; + deserializedAnalyzedTokenInfo.endOffset = reader.getInt(); } else if ("position".equals(fieldName)) { - position = reader.getInt(); - positionFound = true; + deserializedAnalyzedTokenInfo.position = reader.getInt(); } 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 deserializedAnalyzedTokenInfo; }); } } 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/indexes/models/AsciiFoldingTokenFilter.java index 526771685ac6..39245f9cd95b 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/indexes/models/AsciiFoldingTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,8 +17,9 @@ */ @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"; @@ -34,7 +32,7 @@ public final class AsciiFoldingTokenFilter extends TokenFilter { /** * Creates an instance of AsciiFoldingTokenFilter class. - * + * * @param name the name value to set. */ @Generated @@ -43,8 +41,8 @@ public AsciiFoldingTokenFilter(String 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 @@ -55,7 +53,7 @@ public String getOdataType() { /** * Get the preserveOriginal property: A value indicating whether the original token will be kept. Default is false. - * + * * @return the preserveOriginal value. */ @Generated @@ -65,7 +63,7 @@ public Boolean isPreserveOriginal() { /** * Set the preserveOriginal property: A value indicating whether the original token will be kept. Default is false. - * + * * @param preserveOriginal the preserveOriginal value to set. * @return the AsciiFoldingTokenFilter object itself. */ @@ -90,7 +88,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AsciiFoldingTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AsciiFoldingTokenFilter if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -100,17 +98,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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 ("preserveOriginal".equals(fieldName)) { @@ -119,14 +114,10 @@ public static AsciiFoldingTokenFilter fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - if (nameFound) { - AsciiFoldingTokenFilter deserializedAsciiFoldingTokenFilter = new AsciiFoldingTokenFilter(name); - deserializedAsciiFoldingTokenFilter.odataType = odataType; - deserializedAsciiFoldingTokenFilter.preserveOriginal = preserveOriginal; - - return deserializedAsciiFoldingTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + AsciiFoldingTokenFilter deserializedAsciiFoldingTokenFilter = new AsciiFoldingTokenFilter(name); + deserializedAsciiFoldingTokenFilter.odataType = odataType; + deserializedAsciiFoldingTokenFilter.preserveOriginal = preserveOriginal; + return deserializedAsciiFoldingTokenFilter; }); } } 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/indexes/models/AzureActiveDirectoryApplicationCredentials.java similarity index 79% 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/indexes/models/AzureActiveDirectoryApplicationCredentials.java index 4790f2fed552..2db2281961c3 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/indexes/models/AzureActiveDirectoryApplicationCredentials.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -21,13 +18,14 @@ @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 * Application. */ @Generated - private String applicationId; + private final String applicationId; /* * The authentication key of the specified AAD application. @@ -37,16 +35,19 @@ public final class AzureActiveDirectoryApplicationCredentials /** * Creates an instance of AzureActiveDirectoryApplicationCredentials class. + * + * @param applicationId the applicationId value to set. */ @Generated - public AzureActiveDirectoryApplicationCredentials() { + 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. - * + * * @return the applicationId value. */ @Generated @@ -54,23 +55,9 @@ 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. - */ - @Generated - 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 @@ -80,7 +67,7 @@ public String getApplicationSecret() { /** * Set the applicationSecret property: The authentication key of the specified AAD application. - * + * * @param applicationSecret the applicationSecret value to set. * @return the AzureActiveDirectoryApplicationCredentials object itself. */ @@ -104,30 +91,32 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureActiveDirectoryApplicationCredentials from the JsonReader. - * + * * @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/AzureBlobKnowledgeSource.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSource.java index c8ff531c0022..05d62f5e17e4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSource.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSource.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,14 +9,13 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Configuration for Azure Blob Storage knowledge source. */ @Fluent public final class AzureBlobKnowledgeSource extends KnowledgeSource { + /* * The type of the knowledge source. */ @@ -34,7 +30,7 @@ public final class AzureBlobKnowledgeSource extends KnowledgeSource { /** * Creates an instance of AzureBlobKnowledgeSource class. - * + * * @param name the name value to set. * @param azureBlobParameters the azureBlobParameters value to set. */ @@ -46,7 +42,7 @@ public AzureBlobKnowledgeSource(String name, AzureBlobKnowledgeSourceParameters /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -57,7 +53,7 @@ public KnowledgeSourceKind getKind() { /** * Get the azureBlobParameters property: The type of the knowledge source. - * + * * @return the azureBlobParameters value. */ @Generated @@ -113,7 +109,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureBlobKnowledgeSource from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureBlobKnowledgeSource if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -123,21 +119,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static AzureBlobKnowledgeSource fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String description = null; String eTag = null; SearchResourceEncryptionKey encryptionKey = null; - boolean azureBlobParametersFound = false; AzureBlobKnowledgeSourceParameters azureBlobParameters = null; KnowledgeSourceKind kind = KnowledgeSourceKind.AZURE_BLOB; 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 ("@odata.etag".equals(fieldName)) { @@ -146,33 +138,19 @@ public static AzureBlobKnowledgeSource fromJson(JsonReader jsonReader) throws IO encryptionKey = SearchResourceEncryptionKey.fromJson(reader); } else if ("azureBlobParameters".equals(fieldName)) { azureBlobParameters = AzureBlobKnowledgeSourceParameters.fromJson(reader); - azureBlobParametersFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeSourceKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound && azureBlobParametersFound) { - AzureBlobKnowledgeSource deserializedAzureBlobKnowledgeSource - = new AzureBlobKnowledgeSource(name, azureBlobParameters); - deserializedAzureBlobKnowledgeSource.setDescription(description); - deserializedAzureBlobKnowledgeSource.setETag(eTag); - deserializedAzureBlobKnowledgeSource.setEncryptionKey(encryptionKey); - deserializedAzureBlobKnowledgeSource.kind = kind; - - return deserializedAzureBlobKnowledgeSource; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!azureBlobParametersFound) { - missingProperties.add("azureBlobParameters"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + AzureBlobKnowledgeSource deserializedAzureBlobKnowledgeSource + = new AzureBlobKnowledgeSource(name, azureBlobParameters); + deserializedAzureBlobKnowledgeSource.setDescription(description); + deserializedAzureBlobKnowledgeSource.setETag(eTag); + deserializedAzureBlobKnowledgeSource.setEncryptionKey(encryptionKey); + deserializedAzureBlobKnowledgeSource.kind = kind; + return deserializedAzureBlobKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSourceParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSourceParameters.java index 65fd933310d4..4f33a91b7b45 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSourceParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSourceParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,16 +9,15 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; /** * Parameters for Azure Blob Storage knowledge source. */ @Fluent public final class AzureBlobKnowledgeSourceParameters implements JsonSerializable { + /* * Key-based connection string or the ResourceId format if using a managed identity. */ @@ -44,7 +40,7 @@ public final class AzureBlobKnowledgeSourceParameters implements JsonSerializabl * Set to true if connecting to an ADLS Gen2 storage account. Default is false. */ @Generated - private Boolean isAdlsGen2; + private Boolean isADLSGen2; /* * Consolidates all general ingestion settings. @@ -56,11 +52,11 @@ public final class AzureBlobKnowledgeSourceParameters implements JsonSerializabl * Resources created by the knowledge source. */ @Generated - private Map createdResources; + private CreatedResources createdResources; /** * Creates an instance of AzureBlobKnowledgeSourceParameters class. - * + * * @param connectionString the connectionString value to set. * @param containerName the containerName value to set. */ @@ -73,7 +69,7 @@ public AzureBlobKnowledgeSourceParameters(String connectionString, String contai /** * Get the connectionString property: Key-based connection string or the ResourceId format if using a managed * identity. - * + * * @return the connectionString value. */ @Generated @@ -83,7 +79,7 @@ public String getConnectionString() { /** * Get the containerName property: The name of the blob storage container. - * + * * @return the containerName value. */ @Generated @@ -93,7 +89,7 @@ public String getContainerName() { /** * Get the folderPath property: Optional folder path within the container. - * + * * @return the folderPath value. */ @Generated @@ -103,7 +99,7 @@ public String getFolderPath() { /** * Set the folderPath property: Optional folder path within the container. - * + * * @param folderPath the folderPath value to set. * @return the AzureBlobKnowledgeSourceParameters object itself. */ @@ -114,30 +110,30 @@ public AzureBlobKnowledgeSourceParameters setFolderPath(String folderPath) { } /** - * Get the isAdlsGen2 property: Set to true if connecting to an ADLS Gen2 storage account. Default is false. - * - * @return the isAdlsGen2 value. + * Get the isADLSGen2 property: Set to true if connecting to an ADLS Gen2 storage account. Default is false. + * + * @return the isADLSGen2 value. */ @Generated - public Boolean isAdlsGen2() { - return this.isAdlsGen2; + public Boolean isADLSGen2() { + return this.isADLSGen2; } /** - * Set the isAdlsGen2 property: Set to true if connecting to an ADLS Gen2 storage account. Default is false. - * - * @param isAdlsGen2 the isAdlsGen2 value to set. + * Set the isADLSGen2 property: Set to true if connecting to an ADLS Gen2 storage account. Default is false. + * + * @param isADLSGen2 the isADLSGen2 value to set. * @return the AzureBlobKnowledgeSourceParameters object itself. */ @Generated - public AzureBlobKnowledgeSourceParameters setIsAdlsGen2(Boolean isAdlsGen2) { - this.isAdlsGen2 = isAdlsGen2; + public AzureBlobKnowledgeSourceParameters setIsADLSGen2(Boolean isADLSGen2) { + this.isADLSGen2 = isADLSGen2; return this; } /** * Get the ingestionParameters property: Consolidates all general ingestion settings. - * + * * @return the ingestionParameters value. */ @Generated @@ -147,7 +143,7 @@ public KnowledgeSourceIngestionParameters getIngestionParameters() { /** * Set the ingestionParameters property: Consolidates all general ingestion settings. - * + * * @param ingestionParameters the ingestionParameters value to set. * @return the AzureBlobKnowledgeSourceParameters object itself. */ @@ -160,11 +156,11 @@ public KnowledgeSourceIngestionParameters getIngestionParameters() { /** * Get the createdResources property: Resources created by the knowledge source. - * + * * @return the createdResources value. */ @Generated - public Map getCreatedResources() { + public CreatedResources getCreatedResources() { return this.createdResources; } @@ -178,14 +174,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("connectionString", this.connectionString); jsonWriter.writeStringField("containerName", this.containerName); jsonWriter.writeStringField("folderPath", this.folderPath); - jsonWriter.writeBooleanField("isADLSGen2", this.isAdlsGen2); + jsonWriter.writeBooleanField("isADLSGen2", this.isADLSGen2); jsonWriter.writeJsonField("ingestionParameters", this.ingestionParameters); return jsonWriter.writeEndObject(); } /** * Reads an instance of AzureBlobKnowledgeSourceParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureBlobKnowledgeSourceParameters if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -195,56 +191,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static AzureBlobKnowledgeSourceParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean connectionStringFound = false; String connectionString = null; - boolean containerNameFound = false; String containerName = null; String folderPath = null; - Boolean isAdlsGen2 = null; + Boolean isADLSGen2 = null; KnowledgeSourceIngestionParameters ingestionParameters = null; - Map createdResources = null; + CreatedResources createdResources = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { connectionString = reader.getString(); - connectionStringFound = true; } else if ("containerName".equals(fieldName)) { containerName = reader.getString(); - containerNameFound = true; } else if ("folderPath".equals(fieldName)) { folderPath = reader.getString(); } else if ("isADLSGen2".equals(fieldName)) { - isAdlsGen2 = reader.getNullable(JsonReader::getBoolean); + isADLSGen2 = reader.getNullable(JsonReader::getBoolean); } else if ("ingestionParameters".equals(fieldName)) { ingestionParameters = KnowledgeSourceIngestionParameters.fromJson(reader); } else if ("createdResources".equals(fieldName)) { - createdResources = reader.readMap(reader1 -> reader1.getString()); + createdResources = CreatedResources.fromJson(reader); } else { reader.skipChildren(); } } - if (connectionStringFound && containerNameFound) { - AzureBlobKnowledgeSourceParameters deserializedAzureBlobKnowledgeSourceParameters - = new AzureBlobKnowledgeSourceParameters(connectionString, containerName); - deserializedAzureBlobKnowledgeSourceParameters.folderPath = folderPath; - deserializedAzureBlobKnowledgeSourceParameters.isAdlsGen2 = isAdlsGen2; - deserializedAzureBlobKnowledgeSourceParameters.ingestionParameters = ingestionParameters; - deserializedAzureBlobKnowledgeSourceParameters.createdResources = createdResources; - - return deserializedAzureBlobKnowledgeSourceParameters; - } - List missingProperties = new ArrayList<>(); - if (!connectionStringFound) { - missingProperties.add("connectionString"); - } - if (!containerNameFound) { - missingProperties.add("containerName"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + AzureBlobKnowledgeSourceParameters deserializedAzureBlobKnowledgeSourceParameters + = new AzureBlobKnowledgeSourceParameters(connectionString, containerName); + deserializedAzureBlobKnowledgeSourceParameters.folderPath = folderPath; + deserializedAzureBlobKnowledgeSourceParameters.isADLSGen2 = isADLSGen2; + deserializedAzureBlobKnowledgeSourceParameters.ingestionParameters = ingestionParameters; + deserializedAzureBlobKnowledgeSourceParameters.createdResources = createdResources; + return deserializedAzureBlobKnowledgeSourceParameters; }); } } 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/indexes/models/AzureMachineLearningParameters.java index a9e941b0283f..c76f3d63d073 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/indexes/models/AzureMachineLearningParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -21,6 +18,7 @@ */ @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. @@ -63,7 +61,7 @@ public final class AzureMachineLearningParameters implements JsonSerializable { - boolean scoringUriFound = false; String scoringUri = null; String authenticationKey = null; String resourceId = null; @@ -238,10 +235,8 @@ public static AzureMachineLearningParameters fromJson(JsonReader jsonReader) thr 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)) { @@ -256,18 +251,14 @@ public static AzureMachineLearningParameters fromJson(JsonReader jsonReader) thr 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/indexes/models/AzureMachineLearningSkill.java index b7e60ee90259..6c69e7f04c2e 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/indexes/models/AzureMachineLearningSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -14,7 +11,6 @@ import com.azure.json.JsonWriter; import java.io.IOException; import java.time.Duration; -import java.util.ArrayList; import java.util.List; /** @@ -23,8 +19,9 @@ */ @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"; @@ -75,7 +72,7 @@ public final class AzureMachineLearningSkill extends SearchIndexerSkill { /** * Creates an instance of AzureMachineLearningSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -85,8 +82,8 @@ public AzureMachineLearningSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -324,13 +319,10 @@ public static AzureMachineLearningSkill fromJson(JsonReader jsonReader) throws I 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)) { @@ -355,32 +347,19 @@ 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; - - 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)); + 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; }); } } 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/indexes/models/AzureMachineLearningVectorizer.java index 5e820db32ebc..049eaa99fc1f 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/indexes/models/AzureMachineLearningVectorizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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; @@ -33,7 +31,7 @@ public final class AzureMachineLearningVectorizer extends VectorSearchVectorizer /** * Creates an instance of AzureMachineLearningVectorizer class. - * + * * @param vectorizerName the vectorizerName value to set. */ @Generated @@ -42,8 +40,8 @@ public AzureMachineLearningVectorizer(String 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 @@ -54,7 +52,7 @@ public VectorSearchVectorizerKind getKind() { /** * Get the aMLParameters property: Specifies the properties of the AML vectorizer. - * + * * @return the aMLParameters value. */ @Generated @@ -64,7 +62,7 @@ public AzureMachineLearningParameters getAMLParameters() { /** * Set the aMLParameters property: Specifies the properties of the AML vectorizer. - * + * * @param aMLParameters the aMLParameters value to set. * @return the AzureMachineLearningVectorizer object itself. */ @@ -89,7 +87,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureMachineLearningVectorizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureMachineLearningVectorizer if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -99,17 +97,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("amlParameters".equals(fieldName)) { @@ -118,15 +113,11 @@ public static AzureMachineLearningVectorizer fromJson(JsonReader jsonReader) thr reader.skipChildren(); } } - if (vectorizerNameFound) { - AzureMachineLearningVectorizer deserializedAzureMachineLearningVectorizer - = new AzureMachineLearningVectorizer(vectorizerName); - deserializedAzureMachineLearningVectorizer.kind = kind; - deserializedAzureMachineLearningVectorizer.aMLParameters = aMLParameters; - - return deserializedAzureMachineLearningVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + AzureMachineLearningVectorizer deserializedAzureMachineLearningVectorizer + = new AzureMachineLearningVectorizer(vectorizerName); + deserializedAzureMachineLearningVectorizer.kind = kind; + deserializedAzureMachineLearningVectorizer.aMLParameters = aMLParameters; + 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/indexes/models/AzureOpenAIEmbeddingSkill.java index e5fc3c9d2de7..bafb04361399 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/indexes/models/AzureOpenAIEmbeddingSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,18 +16,12 @@ */ @Fluent public final class AzureOpenAIEmbeddingSkill extends SearchIndexerSkill { - /* - * A URI fragment specifying the type of skill. - */ - @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. + * The discriminator for derived types. */ @Generated - private Integer dimensions; + private String odataType = "#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill"; /* * The resource URI of the Azure OpenAI resource. @@ -63,9 +53,16 @@ public final class AzureOpenAIEmbeddingSkill extends SearchIndexerSkill { @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. */ @@ -75,8 +72,8 @@ public AzureOpenAIEmbeddingSkill(List inputs, List { - 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)) { @@ -315,8 +307,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)) { @@ -327,36 +317,25 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + 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; + 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/indexes/models/AzureOpenAIModelName.java index 54b6e186e695..55cf7be4226f 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/indexes/models/AzureOpenAIModelName.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,67 +13,67 @@ public final class AzureOpenAIModelName extends ExpandableStringEnum { /** - * Static value text-embedding-ada-002 for AzureOpenAIModelName. + * TextEmbeddingAda002 model. */ @Generated - public static final AzureOpenAIModelName TEXT_EMBEDDING_ADA_002 = fromString("text-embedding-ada-002"); + public static final AzureOpenAIModelName TEXT_EMBEDDING_ADA002 = fromString("text-embedding-ada-002"); /** - * Static value text-embedding-3-large for AzureOpenAIModelName. + * TextEmbedding3Large model. */ @Generated - public static final AzureOpenAIModelName TEXT_EMBEDDING_3_LARGE = fromString("text-embedding-3-large"); + public static final AzureOpenAIModelName TEXT_EMBEDDING3LARGE = fromString("text-embedding-3-large"); /** - * Static value text-embedding-3-small for AzureOpenAIModelName. + * TextEmbedding3Small model. */ @Generated - public static final AzureOpenAIModelName TEXT_EMBEDDING_3_SMALL = fromString("text-embedding-3-small"); + public static final AzureOpenAIModelName TEXT_EMBEDDING3SMALL = fromString("text-embedding-3-small"); /** - * Static value gpt-4o for AzureOpenAIModelName. + * Gpt4o model. */ @Generated public static final AzureOpenAIModelName GPT4O = fromString("gpt-4o"); /** - * Static value gpt-4o-mini for AzureOpenAIModelName. + * Gpt4oMini model. */ @Generated - public static final AzureOpenAIModelName GPT4OMINI = fromString("gpt-4o-mini"); + public static final AzureOpenAIModelName GPT4O_MINI = fromString("gpt-4o-mini"); /** - * Static value gpt-4.1 for AzureOpenAIModelName. + * Gpt41 model. */ @Generated public static final AzureOpenAIModelName GPT41 = fromString("gpt-4.1"); /** - * Static value gpt-4.1-mini for AzureOpenAIModelName. + * Gpt41Mini model. */ @Generated public static final AzureOpenAIModelName GPT41MINI = fromString("gpt-4.1-mini"); /** - * Static value gpt-4.1-nano for AzureOpenAIModelName. + * Gpt41Nano model. */ @Generated public static final AzureOpenAIModelName GPT41NANO = fromString("gpt-4.1-nano"); /** - * Static value gpt-5 for AzureOpenAIModelName. + * Gpt5 model. */ @Generated public static final AzureOpenAIModelName GPT5 = fromString("gpt-5"); /** - * Static value gpt-5-mini for AzureOpenAIModelName. + * Gpt5Mini model. */ @Generated public static final AzureOpenAIModelName GPT5MINI = fromString("gpt-5-mini"); /** - * Static value gpt-5-nano for AzureOpenAIModelName. + * Gpt5Nano model. */ @Generated public static final AzureOpenAIModelName GPT5NANO = fromString("gpt-5-nano"); 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/indexes/models/AzureOpenAITokenizerParameters.java index 50ee09988377..9f99007b545e 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/indexes/models/AzureOpenAITokenizerParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,13 +10,15 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; 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'. @@ -44,7 +43,7 @@ public AzureOpenAITokenizerParameters() { /** * Get the encoderModelName property: 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'. - * + * * @return the encoderModelName value. */ @Generated @@ -55,7 +54,7 @@ public SplitSkillEncoderModelName getEncoderModelName() { /** * Set the encoderModelName property: 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'. - * + * * @param encoderModelName the encoderModelName value to set. * @return the AzureOpenAITokenizerParameters object itself. */ @@ -68,7 +67,7 @@ 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. - * + * * @return the allowedSpecialTokens value. */ @Generated @@ -79,7 +78,19 @@ public List getAllowedSpecialTokens() { /** * 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. - * + * + * @param allowedSpecialTokens the allowedSpecialTokens value to set. + * @return the AzureOpenAITokenizerParameters object itself. + */ + public AzureOpenAITokenizerParameters setAllowedSpecialTokens(String... allowedSpecialTokens) { + this.allowedSpecialTokens = (allowedSpecialTokens == null) ? null : Arrays.asList(allowedSpecialTokens); + return this; + } + + /** + * 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. + * * @param allowedSpecialTokens the allowedSpecialTokens value to set. * @return the AzureOpenAITokenizerParameters object itself. */ @@ -105,7 +116,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureOpenAITokenizerParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureOpenAITokenizerParameters if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -119,7 +130,6 @@ public static AzureOpenAITokenizerParameters fromJson(JsonReader jsonReader) thr while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("encoderModelName".equals(fieldName)) { deserializedAzureOpenAITokenizerParameters.encoderModelName = SplitSkillEncoderModelName.fromString(reader.getString()); @@ -130,7 +140,6 @@ public static AzureOpenAITokenizerParameters fromJson(JsonReader jsonReader) thr reader.skipChildren(); } } - return 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/indexes/models/AzureOpenAIVectorizer.java index e48d4f6003ae..8a9b3c8ac0e9 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/indexes/models/AzureOpenAIVectorizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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; @@ -32,7 +30,7 @@ public final class AzureOpenAIVectorizer extends VectorSearchVectorizer { /** * Creates an instance of AzureOpenAIVectorizer class. - * + * * @param vectorizerName the vectorizerName value to set. */ @Generated @@ -41,8 +39,8 @@ public AzureOpenAIVectorizer(String 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 @@ -53,7 +51,7 @@ public VectorSearchVectorizerKind getKind() { /** * Get the parameters property: Contains the parameters specific to Azure OpenAI embedding vectorization. - * + * * @return the parameters value. */ @Generated @@ -63,7 +61,7 @@ public AzureOpenAIVectorizerParameters getParameters() { /** * Set the parameters property: Contains the parameters specific to Azure OpenAI embedding vectorization. - * + * * @param parameters the parameters value to set. * @return the AzureOpenAIVectorizer object itself. */ @@ -88,7 +86,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureOpenAIVectorizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureOpenAIVectorizer if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -98,17 +96,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("azureOpenAIParameters".equals(fieldName)) { @@ -117,14 +112,10 @@ public static AzureOpenAIVectorizer fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - if (vectorizerNameFound) { - AzureOpenAIVectorizer deserializedAzureOpenAIVectorizer = new AzureOpenAIVectorizer(vectorizerName); - deserializedAzureOpenAIVectorizer.kind = kind; - deserializedAzureOpenAIVectorizer.parameters = parameters; - - return deserializedAzureOpenAIVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + AzureOpenAIVectorizer deserializedAzureOpenAIVectorizer = new AzureOpenAIVectorizer(vectorizerName); + deserializedAzureOpenAIVectorizer.kind = kind; + deserializedAzureOpenAIVectorizer.parameters = parameters; + 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/indexes/models/AzureOpenAIVectorizerParameters.java index 2b61175f0c91..beeb078465c8 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/indexes/models/AzureOpenAIVectorizerParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,7 +15,8 @@ * 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. */ @@ -58,7 +56,7 @@ public AzureOpenAIVectorizerParameters() { /** * Get the resourceUrl property: The resource URI of the Azure OpenAI resource. - * + * * @return the resourceUrl value. */ @Generated @@ -68,7 +66,7 @@ public String getResourceUrl() { /** * Set the resourceUrl property: The resource URI of the Azure OpenAI resource. - * + * * @param resourceUrl the resourceUrl value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ @@ -80,7 +78,7 @@ public AzureOpenAIVectorizerParameters setResourceUrl(String resourceUrl) { /** * Get the deploymentName property: ID of the Azure OpenAI model deployment on the designated resource. - * + * * @return the deploymentName value. */ @Generated @@ -90,7 +88,7 @@ public String getDeploymentName() { /** * Set the deploymentName property: ID of the Azure OpenAI model deployment on the designated resource. - * + * * @param deploymentName the deploymentName value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ @@ -102,7 +100,7 @@ public AzureOpenAIVectorizerParameters setDeploymentName(String deploymentName) /** * Get the apiKey property: API key of the designated Azure OpenAI resource. - * + * * @return the apiKey value. */ @Generated @@ -112,7 +110,7 @@ public String getApiKey() { /** * Set the apiKey property: API key of the designated Azure OpenAI resource. - * + * * @param apiKey the apiKey value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ @@ -124,7 +122,7 @@ public AzureOpenAIVectorizerParameters setApiKey(String apiKey) { /** * Get the authIdentity property: The user-assigned managed identity used for outbound connections. - * + * * @return the authIdentity value. */ @Generated @@ -134,7 +132,7 @@ public SearchIndexerDataIdentity getAuthIdentity() { /** * Set the authIdentity property: The user-assigned managed identity used for outbound connections. - * + * * @param authIdentity the authIdentity value to set. * @return the AzureOpenAIVectorizerParameters object itself. */ @@ -146,7 +144,7 @@ public AzureOpenAIVectorizerParameters setAuthIdentity(SearchIndexerDataIdentity /** * Get the modelName property: The name of the embedding model that is deployed at the provided deploymentId path. - * + * * @return the modelName value. */ @Generated @@ -156,7 +154,7 @@ public AzureOpenAIModelName getModelName() { /** * 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. */ @@ -183,7 +181,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureOpenAIVectorizerParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureOpenAIVectorizerParameters if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -197,7 +195,6 @@ public static AzureOpenAIVectorizerParameters fromJson(JsonReader jsonReader) th while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("resourceUri".equals(fieldName)) { deserializedAzureOpenAIVectorizerParameters.resourceUrl = reader.getString(); } else if ("deploymentId".equals(fieldName)) { @@ -214,7 +211,6 @@ public static AzureOpenAIVectorizerParameters fromJson(JsonReader jsonReader) th reader.skipChildren(); } } - return 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/indexes/models/BM25SimilarityAlgorithm.java index cad5205caab9..7d99209706a5 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/indexes/models/BM25SimilarityAlgorithm.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,8 +17,9 @@ */ @Fluent public final class BM25SimilarityAlgorithm extends SimilarityAlgorithm { + /* - * The @odata.type property. + * The discriminator for derived types. */ @Generated private String odataType = "#Microsoft.Azure.Search.BM25Similarity"; @@ -50,8 +48,8 @@ public BM25SimilarityAlgorithm() { } /** - * Get the odataType property: The @odata.type property. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ @Generated @@ -64,7 +62,7 @@ public String getOdataType() { * 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 @@ -76,7 +74,7 @@ public Double getK1() { * 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. */ @@ -90,7 +88,7 @@ public BM25SimilarityAlgorithm setK1(Double k1) { * 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 @@ -102,7 +100,7 @@ public Double getB() { * 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. */ @@ -127,7 +125,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of BM25SimilarityAlgorithm from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of BM25SimilarityAlgorithm if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -140,7 +138,6 @@ public static BM25SimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOE while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedBM25SimilarityAlgorithm.odataType = reader.getString(); } else if ("k1".equals(fieldName)) { @@ -151,7 +148,6 @@ public static BM25SimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - return deserializedBM25SimilarityAlgorithm; }); } 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/indexes/models/BinaryQuantizationCompression.java index 38ae08e96392..990dfe12d81c 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/indexes/models/BinaryQuantizationCompression.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,15 +16,16 @@ */ @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; /** * Creates an instance of BinaryQuantizationCompression class. - * + * * @param compressionName the compressionName value to set. */ @Generated @@ -36,8 +34,8 @@ public BinaryQuantizationCompression(String 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 @@ -46,26 +44,6 @@ public VectorSearchCompressionKind getKind() { return this.kind; } - /** - * {@inheritDoc} - */ - @Generated - @Override - public BinaryQuantizationCompression setRerankWithOriginalVectors(Boolean rerankWithOriginalVectors) { - super.setRerankWithOriginalVectors(rerankWithOriginalVectors); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public BinaryQuantizationCompression setDefaultOversampling(Double defaultOversampling) { - super.setDefaultOversampling(defaultOversampling); - return this; - } - /** * {@inheritDoc} */ @@ -94,8 +72,6 @@ public BinaryQuantizationCompression setTruncationDimension(Integer truncationDi public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getCompressionName()); - jsonWriter.writeBooleanField("rerankWithOriginalVectors", isRerankWithOriginalVectors()); - jsonWriter.writeNumberField("defaultOversampling", getDefaultOversampling()); jsonWriter.writeJsonField("rescoringOptions", getRescoringOptions()); jsonWriter.writeNumberField("truncationDimension", getTruncationDimension()); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); @@ -104,7 +80,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of BinaryQuantizationCompression from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of BinaryQuantizationCompression if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -114,24 +90,15 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; RescoringOptions rescoringOptions = null; Integer truncationDimension = null; VectorSearchCompressionKind kind = VectorSearchCompressionKind.BINARY_QUANTIZATION; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { compressionName = reader.getString(); - compressionNameFound = true; - } else if ("rerankWithOriginalVectors".equals(fieldName)) { - rerankWithOriginalVectors = reader.getNullable(JsonReader::getBoolean); - } else if ("defaultOversampling".equals(fieldName)) { - defaultOversampling = reader.getNullable(JsonReader::getDouble); } else if ("rescoringOptions".equals(fieldName)) { rescoringOptions = RescoringOptions.fromJson(reader); } else if ("truncationDimension".equals(fieldName)) { @@ -142,18 +109,12 @@ 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; - - return deserializedBinaryQuantizationCompression; - } - throw new IllegalStateException("Missing required property: name"); + BinaryQuantizationCompression deserializedBinaryQuantizationCompression + = new BinaryQuantizationCompression(compressionName); + deserializedBinaryQuantizationCompression.setRescoringOptions(rescoringOptions); + deserializedBinaryQuantizationCompression.setTruncationDimension(truncationDimension); + deserializedBinaryQuantizationCompression.kind = kind; + 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/indexes/models/BlobIndexerDataToExtract.java index 7182e2978066..6089c987119d 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/indexes/models/BlobIndexerDataToExtract.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -16,6 +13,7 @@ * 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. */ @@ -37,7 +35,7 @@ public final class BlobIndexerDataToExtract extends ExpandableStringEnum { + /** * Ignores embedded images or image files in the data set. This is the default. */ @@ -43,7 +41,7 @@ public final class BlobIndexerImageAction extends ExpandableStringEnum { +public final class BlobIndexerPDFTextRotationAlgorithm + extends ExpandableStringEnum { + /** * Leverages normal text extraction. This is the default. */ @Generated - public static final BlobIndexerPdfTextRotationAlgorithm NONE = fromString("none"); + 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 @@ -28,36 +26,36 @@ public final class BlobIndexerPdfTextRotationAlgorithm * parameter does not apply. */ @Generated - public static final BlobIndexerPdfTextRotationAlgorithm DETECT_ANGLES = fromString("detectAngles"); + public static final BlobIndexerPDFTextRotationAlgorithm DETECT_ANGLES = fromString("detectAngles"); /** - * Creates a new instance of BlobIndexerPdfTextRotationAlgorithm value. - * + * Creates a new instance of BlobIndexerPDFTextRotationAlgorithm value. + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @Deprecated - public BlobIndexerPdfTextRotationAlgorithm() { + public BlobIndexerPDFTextRotationAlgorithm() { } /** - * Creates or finds a BlobIndexerPdfTextRotationAlgorithm from its string representation. - * + * Creates or finds a BlobIndexerPDFTextRotationAlgorithm from its string representation. + * * @param name a name to look for. - * @return the corresponding BlobIndexerPdfTextRotationAlgorithm. + * @return the corresponding BlobIndexerPDFTextRotationAlgorithm. */ @Generated - public static BlobIndexerPdfTextRotationAlgorithm fromString(String name) { - return fromString(name, BlobIndexerPdfTextRotationAlgorithm.class); + public static BlobIndexerPDFTextRotationAlgorithm fromString(String name) { + return fromString(name, BlobIndexerPDFTextRotationAlgorithm.class); } /** - * Gets known BlobIndexerPdfTextRotationAlgorithm values. - * - * @return known BlobIndexerPdfTextRotationAlgorithm values. + * Gets known BlobIndexerPDFTextRotationAlgorithm values. + * + * @return known BlobIndexerPDFTextRotationAlgorithm values. */ @Generated - public static Collection values() { - return values(BlobIndexerPdfTextRotationAlgorithm.class); + 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/indexes/models/BlobIndexerParsingMode.java index b0af229430a0..ec1a4c7cae60 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/indexes/models/BlobIndexerParsingMode.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Represents the parsing mode for indexing from an Azure blob data source. */ public final class BlobIndexerParsingMode extends ExpandableStringEnum { + /** * Set to default for normal file processing. */ @@ -58,7 +56,7 @@ public final class BlobIndexerParsingMode extends ExpandableStringEnum { + /* - * A URI fragment specifying the type of char filter. + * The discriminator for derived types. */ @Generated private String odataType = "CharFilter"; @@ -34,7 +32,7 @@ public class CharFilter implements JsonSerializable { /** * Creates an instance of CharFilter class. - * + * * @param name the name value to set. */ @Generated @@ -43,8 +41,8 @@ public CharFilter(String 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 @@ -55,7 +53,7 @@ public String getOdataType() { /** * 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 @@ -77,7 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CharFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CharFilter if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. @@ -89,7 +87,8 @@ public static CharFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -115,29 +114,22 @@ 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) { 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 { reader.skipChildren(); } } - if (nameFound) { - CharFilter deserializedCharFilter = new CharFilter(name); - deserializedCharFilter.odataType = odataType; - - return deserializedCharFilter; - } - throw new IllegalStateException("Missing required property: name"); + CharFilter deserializedCharFilter = new CharFilter(name); + deserializedCharFilter.odataType = odataType; + 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/indexes/models/CharFilterName.java index 7af847c8f6ad..5328e43662e9 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/indexes/models/CharFilterName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Defines the names of all character filters supported by the search engine. */ 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. @@ -23,7 +21,7 @@ public final class CharFilterName extends ExpandableStringEnum { /** * Creates a new instance of CharFilterName value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -33,7 +31,7 @@ public CharFilterName() { /** * Creates or finds a CharFilterName from its string representation. - * + * * @param name a name to look for. * @return the corresponding CharFilterName. */ @@ -44,7 +42,7 @@ public static CharFilterName fromString(String name) { /** * Gets known CharFilterName values. - * + * * @return known CharFilterName values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonModelParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionCommonModelParameters.java similarity index 59% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonModelParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionCommonModelParameters.java index c308c1ac7357..a33da5c137cd 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CommonModelParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionCommonModelParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,30 +10,33 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** * Common language model parameters for Chat Completions. If omitted, default values are used. */ @Fluent -public final class CommonModelParameters implements JsonSerializable { +public final class ChatCompletionCommonModelParameters + implements JsonSerializable { + /* * The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified. */ @Generated - private String model; + private String modelName; /* * A float in the range [-2,2] that reduces or increases likelihood of repeated tokens. Default is 0. */ @Generated - private Float frequencyPenalty; + private Double frequencyPenalty; /* * A float in the range [-2,2] that penalizes new tokens based on their existing presence. Default is 0. */ @Generated - private Float presencePenalty; + private Double presencePenalty; /* * Maximum number of tokens to generate. @@ -48,7 +48,7 @@ public final class CommonModelParameters implements JsonSerializable stop; /** - * Creates an instance of CommonModelParameters class. + * Creates an instance of ChatCompletionCommonModelParameters class. */ @Generated - public CommonModelParameters() { + public ChatCompletionCommonModelParameters() { } /** - * Get the model property: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified. - * - * @return the model value. + * Get the modelName property: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not + * specified. + * + * @return the modelName value. */ @Generated - public String getModel() { - return this.model; + public String getModelName() { + return this.modelName; } /** - * Set the model property: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not specified. - * - * @param model the model value to set. - * @return the CommonModelParameters object itself. + * Set the modelName property: The name of the model to use (e.g., 'gpt-4o', etc.). Default is null if not + * specified. + * + * @param modelName the modelName value to set. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setModel(String model) { - this.model = model; + public ChatCompletionCommonModelParameters setModelName(String modelName) { + this.modelName = modelName; return this; } /** * Get the frequencyPenalty property: A float in the range [-2,2] that reduces or increases likelihood of repeated * tokens. Default is 0. - * + * * @return the frequencyPenalty value. */ @Generated - public Float getFrequencyPenalty() { + public Double getFrequencyPenalty() { return this.frequencyPenalty; } /** * Set the frequencyPenalty property: A float in the range [-2,2] that reduces or increases likelihood of repeated * tokens. Default is 0. - * + * * @param frequencyPenalty the frequencyPenalty value to set. - * @return the CommonModelParameters object itself. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setFrequencyPenalty(Float frequencyPenalty) { + public ChatCompletionCommonModelParameters setFrequencyPenalty(Double frequencyPenalty) { this.frequencyPenalty = frequencyPenalty; return this; } @@ -118,30 +120,30 @@ public CommonModelParameters setFrequencyPenalty(Float frequencyPenalty) { /** * Get the presencePenalty property: A float in the range [-2,2] that penalizes new tokens based on their existing * presence. Default is 0. - * + * * @return the presencePenalty value. */ @Generated - public Float getPresencePenalty() { + public Double getPresencePenalty() { return this.presencePenalty; } /** * Set the presencePenalty property: A float in the range [-2,2] that penalizes new tokens based on their existing * presence. Default is 0. - * + * * @param presencePenalty the presencePenalty value to set. - * @return the CommonModelParameters object itself. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setPresencePenalty(Float presencePenalty) { + public ChatCompletionCommonModelParameters setPresencePenalty(Double presencePenalty) { this.presencePenalty = presencePenalty; return this; } /** * Get the maxTokens property: Maximum number of tokens to generate. - * + * * @return the maxTokens value. */ @Generated @@ -151,41 +153,41 @@ public Integer getMaxTokens() { /** * Set the maxTokens property: Maximum number of tokens to generate. - * + * * @param maxTokens the maxTokens value to set. - * @return the CommonModelParameters object itself. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setMaxTokens(Integer maxTokens) { + public ChatCompletionCommonModelParameters setMaxTokens(Integer maxTokens) { this.maxTokens = maxTokens; return this; } /** * Get the temperature property: Sampling temperature. Default is 0.7. - * + * * @return the temperature value. */ @Generated - public Float getTemperature() { + public Double getTemperature() { return this.temperature; } /** * Set the temperature property: Sampling temperature. Default is 0.7. - * + * * @param temperature the temperature value to set. - * @return the CommonModelParameters object itself. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setTemperature(Float temperature) { + public ChatCompletionCommonModelParameters setTemperature(Double temperature) { this.temperature = temperature; return this; } /** * Get the seed property: Random seed for controlling deterministic outputs. If omitted, randomization is used. - * + * * @return the seed value. */ @Generated @@ -195,19 +197,19 @@ public Integer getSeed() { /** * Set the seed property: Random seed for controlling deterministic outputs. If omitted, randomization is used. - * + * * @param seed the seed value to set. - * @return the CommonModelParameters object itself. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setSeed(Integer seed) { + public ChatCompletionCommonModelParameters setSeed(Integer seed) { this.seed = seed; return this; } /** * Get the stop property: List of stop sequences that will cut off text generation. Default is none. - * + * * @return the stop value. */ @Generated @@ -217,12 +219,23 @@ public List getStop() { /** * Set the stop property: List of stop sequences that will cut off text generation. Default is none. - * + * * @param stop the stop value to set. - * @return the CommonModelParameters object itself. + * @return the ChatCompletionCommonModelParameters object itself. + */ + public ChatCompletionCommonModelParameters setStop(String... stop) { + this.stop = (stop == null) ? null : Arrays.asList(stop); + return this; + } + + /** + * Set the stop property: List of stop sequences that will cut off text generation. Default is none. + * + * @param stop the stop value to set. + * @return the ChatCompletionCommonModelParameters object itself. */ @Generated - public CommonModelParameters setStop(List stop) { + public ChatCompletionCommonModelParameters setStop(List stop) { this.stop = stop; return this; } @@ -234,7 +247,7 @@ public CommonModelParameters setStop(List stop) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeStringField("model", this.model); + jsonWriter.writeStringField("model", this.modelName); jsonWriter.writeNumberField("frequencyPenalty", this.frequencyPenalty); jsonWriter.writeNumberField("presencePenalty", this.presencePenalty); jsonWriter.writeNumberField("maxTokens", this.maxTokens); @@ -245,42 +258,44 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of CommonModelParameters from the JsonReader. - * + * Reads an instance of ChatCompletionCommonModelParameters from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of CommonModelParameters 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 CommonModelParameters. + * @return An instance of ChatCompletionCommonModelParameters 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 ChatCompletionCommonModelParameters. */ @Generated - public static CommonModelParameters fromJson(JsonReader jsonReader) throws IOException { + public static ChatCompletionCommonModelParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - CommonModelParameters deserializedCommonModelParameters = new CommonModelParameters(); + ChatCompletionCommonModelParameters deserializedChatCompletionCommonModelParameters + = new ChatCompletionCommonModelParameters(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("model".equals(fieldName)) { - deserializedCommonModelParameters.model = reader.getString(); + deserializedChatCompletionCommonModelParameters.modelName = reader.getString(); } else if ("frequencyPenalty".equals(fieldName)) { - deserializedCommonModelParameters.frequencyPenalty = reader.getNullable(JsonReader::getFloat); + deserializedChatCompletionCommonModelParameters.frequencyPenalty + = reader.getNullable(JsonReader::getDouble); } else if ("presencePenalty".equals(fieldName)) { - deserializedCommonModelParameters.presencePenalty = reader.getNullable(JsonReader::getFloat); + deserializedChatCompletionCommonModelParameters.presencePenalty + = reader.getNullable(JsonReader::getDouble); } else if ("maxTokens".equals(fieldName)) { - deserializedCommonModelParameters.maxTokens = reader.getNullable(JsonReader::getInt); + deserializedChatCompletionCommonModelParameters.maxTokens = reader.getNullable(JsonReader::getInt); } else if ("temperature".equals(fieldName)) { - deserializedCommonModelParameters.temperature = reader.getNullable(JsonReader::getFloat); + deserializedChatCompletionCommonModelParameters.temperature + = reader.getNullable(JsonReader::getDouble); } else if ("seed".equals(fieldName)) { - deserializedCommonModelParameters.seed = reader.getNullable(JsonReader::getInt); + deserializedChatCompletionCommonModelParameters.seed = reader.getNullable(JsonReader::getInt); } else if ("stop".equals(fieldName)) { List stop = reader.readArray(reader1 -> reader1.getString()); - deserializedCommonModelParameters.stop = stop; + deserializedChatCompletionCommonModelParameters.stop = stop; } else { reader.skipChildren(); } } - - return deserializedCommonModelParameters; + return deserializedChatCompletionCommonModelParameters; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionExtraParametersBehavior.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionExtraParametersBehavior.java index f3cafc3c7bb3..6609e476f7a0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionExtraParametersBehavior.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionExtraParametersBehavior.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,11 +12,12 @@ */ public final class ChatCompletionExtraParametersBehavior extends ExpandableStringEnum { + /** * Passes any extra parameters directly to the model. */ @Generated - public static final ChatCompletionExtraParametersBehavior PASS_THROUGH = fromString("passThrough"); + public static final ChatCompletionExtraParametersBehavior PASS_THROUGH = fromString("pass-through"); /** * Drops all extra parameters. @@ -35,7 +33,7 @@ public final class ChatCompletionExtraParametersBehavior /** * Creates a new instance of ChatCompletionExtraParametersBehavior value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -45,7 +43,7 @@ public ChatCompletionExtraParametersBehavior() { /** * Creates or finds a ChatCompletionExtraParametersBehavior from its string representation. - * + * * @param name a name to look for. * @return the corresponding ChatCompletionExtraParametersBehavior. */ @@ -56,7 +54,7 @@ public static ChatCompletionExtraParametersBehavior fromString(String name) { /** * Gets known ChatCompletionExtraParametersBehavior values. - * + * * @return known ChatCompletionExtraParametersBehavior values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java index 798f977928cb..8280beb2c631 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,9 +16,9 @@ */ @Fluent public final class ChatCompletionResponseFormat implements JsonSerializable { + /* - * Specifies how the LLM should format the response. Possible values: 'text' (plain string), 'json_object' - * (arbitrary JSON), or 'json_schema' (adheres to provided schema). + * Specifies how the LLM should format the response. */ @Generated private ChatCompletionResponseFormatType type; @@ -30,7 +27,7 @@ public final class ChatCompletionResponseFormat implements JsonSerializable { + /** - * Static value text for ChatCompletionResponseFormatType. + * Plain text response format. */ @Generated public static final ChatCompletionResponseFormatType TEXT = fromString("text"); /** - * Static value jsonObject for ChatCompletionResponseFormatType. + * Arbitrary JSON object response format. */ @Generated public static final ChatCompletionResponseFormatType JSON_OBJECT = fromString("jsonObject"); /** - * Static value jsonSchema for ChatCompletionResponseFormatType. + * JSON schema-adhering response format. */ @Generated public static final ChatCompletionResponseFormatType JSON_SCHEMA = fromString("jsonSchema"); /** * Creates a new instance of ChatCompletionResponseFormatType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -45,7 +42,7 @@ public ChatCompletionResponseFormatType() { /** * Creates or finds a ChatCompletionResponseFormatType from its string representation. - * + * * @param name a name to look for. * @return the corresponding ChatCompletionResponseFormatType. */ @@ -56,7 +53,7 @@ public static ChatCompletionResponseFormatType fromString(String name) { /** * Gets known ChatCompletionResponseFormatType values. - * + * * @return known ChatCompletionResponseFormatType values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java index 2428ab0e010c..303b2ad15f0d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @Fluent public final class ChatCompletionSchema implements JsonSerializable { + /* * Type of schema representation. Usually 'object'. Default is 'object'. */ @@ -55,7 +54,7 @@ public ChatCompletionSchema() { /** * Get the type property: Type of schema representation. Usually 'object'. Default is 'object'. - * + * * @return the type value. */ @Generated @@ -65,7 +64,7 @@ public String getType() { /** * Set the type property: Type of schema representation. Usually 'object'. Default is 'object'. - * + * * @param type the type value to set. * @return the ChatCompletionSchema object itself. */ @@ -78,7 +77,7 @@ public ChatCompletionSchema setType(String type) { /** * Get the properties property: A JSON-formatted string that defines the output schema's properties and constraints * for the model. - * + * * @return the properties value. */ @Generated @@ -89,7 +88,7 @@ public String getProperties() { /** * Set the properties property: A JSON-formatted string that defines the output schema's properties and constraints * for the model. - * + * * @param properties the properties value to set. * @return the ChatCompletionSchema object itself. */ @@ -102,7 +101,7 @@ public ChatCompletionSchema setProperties(String properties) { /** * Get the required property: An array of the property names that are required to be part of the model's response. * All properties must be included for structured outputs. - * + * * @return the required value. */ @Generated @@ -113,7 +112,19 @@ public List getRequired() { /** * Set the required property: An array of the property names that are required to be part of the model's response. * All properties must be included for structured outputs. - * + * + * @param required the required value to set. + * @return the ChatCompletionSchema object itself. + */ + public ChatCompletionSchema setRequired(String... required) { + this.required = (required == null) ? null : Arrays.asList(required); + return this; + } + + /** + * Set the required property: An array of the property names that are required to be part of the model's response. + * All properties must be included for structured outputs. + * * @param required the required value to set. * @return the ChatCompletionSchema object itself. */ @@ -126,7 +137,7 @@ public ChatCompletionSchema setRequired(List required) { /** * Get the additionalProperties property: Controls whether it is allowable for an object to contain additional keys * / values that were not defined in the JSON Schema. Default is false. - * + * * @return the additionalProperties value. */ @Generated @@ -137,7 +148,7 @@ public Boolean isAdditionalProperties() { /** * Set the additionalProperties property: Controls whether it is allowable for an object to contain additional keys * / values that were not defined in the JSON Schema. Default is false. - * + * * @param additionalProperties the additionalProperties value to set. * @return the ChatCompletionSchema object itself. */ @@ -163,7 +174,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ChatCompletionSchema from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ChatCompletionSchema if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -176,7 +187,6 @@ public static ChatCompletionSchema fromJson(JsonReader jsonReader) throws IOExce while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("type".equals(fieldName)) { deserializedChatCompletionSchema.type = reader.getString(); } else if ("properties".equals(fieldName)) { @@ -190,7 +200,6 @@ public static ChatCompletionSchema fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - return deserializedChatCompletionSchema; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatJsonSchemaProperties.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchemaProperties.java similarity index 55% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatJsonSchemaProperties.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchemaProperties.java index 1f70e315f2b3..bd64b1b1d331 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatJsonSchemaProperties.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchemaProperties.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -15,13 +12,13 @@ import java.io.IOException; /** - * An open dictionary for extended properties. Required if 'type' == 'json_schema'. + * Properties for JSON schema response format. */ @Fluent -public final class ChatCompletionResponseFormatJsonSchemaProperties - implements JsonSerializable { +public final class ChatCompletionSchemaProperties implements JsonSerializable { + /* - * Name of the json schema the model will adhere to + * Name of the json schema the model will adhere to. */ @Generated private String name; @@ -33,27 +30,27 @@ public final class ChatCompletionResponseFormatJsonSchemaProperties private String description; /* - * Whether or not the model's response should use structured outputs. Default is true + * Whether or not the model's response should use structured outputs. Default is true. */ @Generated private Boolean strict; /* - * Object defining the custom schema the model will use to structure its output. + * The schema definition. */ @Generated private ChatCompletionSchema schema; /** - * Creates an instance of ChatCompletionResponseFormatJsonSchemaProperties class. + * Creates an instance of ChatCompletionSchemaProperties class. */ @Generated - public ChatCompletionResponseFormatJsonSchemaProperties() { + public ChatCompletionSchemaProperties() { } /** * Get the name property: Name of the json schema the model will adhere to. - * + * * @return the name value. */ @Generated @@ -63,19 +60,19 @@ public String getName() { /** * Set the name property: Name of the json schema the model will adhere to. - * + * * @param name the name value to set. - * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + * @return the ChatCompletionSchemaProperties object itself. */ @Generated - public ChatCompletionResponseFormatJsonSchemaProperties setName(String name) { + public ChatCompletionSchemaProperties setName(String name) { this.name = name; return this; } /** * Get the description property: Description of the json schema the model will adhere to. - * + * * @return the description value. */ @Generated @@ -85,19 +82,19 @@ public String getDescription() { /** * Set the description property: Description of the json schema the model will adhere to. - * + * * @param description the description value to set. - * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + * @return the ChatCompletionSchemaProperties object itself. */ @Generated - public ChatCompletionResponseFormatJsonSchemaProperties setDescription(String description) { + public ChatCompletionSchemaProperties setDescription(String description) { this.description = description; return this; } /** * Get the strict property: Whether or not the model's response should use structured outputs. Default is true. - * + * * @return the strict value. */ @Generated @@ -107,19 +104,19 @@ public Boolean isStrict() { /** * Set the strict property: Whether or not the model's response should use structured outputs. Default is true. - * + * * @param strict the strict value to set. - * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + * @return the ChatCompletionSchemaProperties object itself. */ @Generated - public ChatCompletionResponseFormatJsonSchemaProperties setStrict(Boolean strict) { + public ChatCompletionSchemaProperties setStrict(Boolean strict) { this.strict = strict; return this; } /** - * Get the schema property: Object defining the custom schema the model will use to structure its output. - * + * Get the schema property: The schema definition. + * * @return the schema value. */ @Generated @@ -128,13 +125,13 @@ public ChatCompletionSchema getSchema() { } /** - * Set the schema property: Object defining the custom schema the model will use to structure its output. - * + * Set the schema property: The schema definition. + * * @param schema the schema value to set. - * @return the ChatCompletionResponseFormatJsonSchemaProperties object itself. + * @return the ChatCompletionSchemaProperties object itself. */ @Generated - public ChatCompletionResponseFormatJsonSchemaProperties setSchema(ChatCompletionSchema schema) { + public ChatCompletionSchemaProperties setSchema(ChatCompletionSchema schema) { this.schema = schema; return this; } @@ -154,38 +151,34 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of ChatCompletionResponseFormatJsonSchemaProperties from the JsonReader. - * + * Reads an instance of ChatCompletionSchemaProperties from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of ChatCompletionResponseFormatJsonSchemaProperties 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 ChatCompletionResponseFormatJsonSchemaProperties. + * @return An instance of ChatCompletionSchemaProperties 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 ChatCompletionSchemaProperties. */ @Generated - public static ChatCompletionResponseFormatJsonSchemaProperties fromJson(JsonReader jsonReader) throws IOException { + public static ChatCompletionSchemaProperties fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - ChatCompletionResponseFormatJsonSchemaProperties deserializedChatCompletionResponseFormatJsonSchemaProperties - = new ChatCompletionResponseFormatJsonSchemaProperties(); + ChatCompletionSchemaProperties deserializedChatCompletionSchemaProperties + = new ChatCompletionSchemaProperties(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { - deserializedChatCompletionResponseFormatJsonSchemaProperties.name = reader.getString(); + deserializedChatCompletionSchemaProperties.name = reader.getString(); } else if ("description".equals(fieldName)) { - deserializedChatCompletionResponseFormatJsonSchemaProperties.description = reader.getString(); + deserializedChatCompletionSchemaProperties.description = reader.getString(); } else if ("strict".equals(fieldName)) { - deserializedChatCompletionResponseFormatJsonSchemaProperties.strict - = reader.getNullable(JsonReader::getBoolean); + deserializedChatCompletionSchemaProperties.strict = reader.getNullable(JsonReader::getBoolean); } else if ("schema".equals(fieldName)) { - deserializedChatCompletionResponseFormatJsonSchemaProperties.schema - = ChatCompletionSchema.fromJson(reader); + deserializedChatCompletionSchemaProperties.schema = ChatCompletionSchema.fromJson(reader); } else { reader.skipChildren(); } } - - return deserializedChatCompletionResponseFormatJsonSchemaProperties; + return deserializedChatCompletionSchemaProperties; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java index 741be0fef5a4..c000d5bad755 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -14,7 +11,6 @@ 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; @@ -22,13 +18,68 @@ * A skill that calls a language model via Azure AI Foundry's Chat Completions endpoint. */ @Fluent -public final class ChatCompletionSkill extends WebApiSkill { +public final class ChatCompletionSkill extends SearchIndexerSkill { + /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ @Generated private String odataType = "#Microsoft.Skills.Custom.ChatCompletionSkill"; + /* + * The url for the Web API. + */ + @Generated + private final String uri; + + /* + * The headers required to make the http request. + */ + @Generated + private WebApiHttpHeaders 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. + */ + @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. + */ + @Generated + private SearchIndexerDataIdentity authIdentity; + /* * API key for authenticating to the model. Both apiKey and authIdentity cannot be specified at the same time. */ @@ -39,11 +90,11 @@ public final class ChatCompletionSkill extends WebApiSkill { * Common language model parameters that customers can tweak. If omitted, reasonable defaults will be applied. */ @Generated - private CommonModelParameters commonModelParameters; + private ChatCompletionCommonModelParameters commonModelParameters; /* * Open-type dictionary for model-specific parameters that should be appended to the chat completions call. Follows - * Azure AI Foundry’s extensibility pattern. + * Azure AI Foundry's extensibility pattern. */ @Generated private Map extraParameters; @@ -62,19 +113,20 @@ public final class ChatCompletionSkill extends WebApiSkill { /** * Creates an instance of ChatCompletionSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. * @param uri the uri value to set. */ @Generated public ChatCompletionSkill(List inputs, List outputs, String uri) { - super(inputs, outputs, 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 @@ -83,10 +135,188 @@ public String getOdataType() { return this.odataType; } + /** + * Get the uri property: The url for the Web API. + * + * @return the uri value. + */ + @Generated + public String getUri() { + return this.uri; + } + + /** + * Get the httpHeaders property: The headers required to make the http request. + * + * @return the httpHeaders value. + */ + @Generated + public WebApiHttpHeaders getHttpHeaders() { + return this.httpHeaders; + } + + /** + * Set the httpHeaders property: The headers required to make the http request. + * + * @param httpHeaders the httpHeaders value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setHttpHeaders(WebApiHttpHeaders httpHeaders) { + this.httpHeaders = httpHeaders; + return this; + } + + /** + * Get the httpMethod property: The method for the http request. + * + * @return the httpMethod value. + */ + @Generated + public String getHttpMethod() { + return this.httpMethod; + } + + /** + * Set the httpMethod property: The method for the http request. + * + * @param httpMethod the httpMethod value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setHttpMethod(String httpMethod) { + this.httpMethod = httpMethod; + return this; + } + + /** + * Get the timeout property: The desired timeout for the request. Default is 30 seconds. + * + * @return the timeout value. + */ + @Generated + public Duration getTimeout() { + return this.timeout; + } + + /** + * Set the timeout property: The desired timeout for the request. Default is 30 seconds. + * + * @param timeout the timeout value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setTimeout(Duration timeout) { + this.timeout = timeout; + return this; + } + + /** + * Get the batchSize property: The desired batch size which indicates number of documents. + * + * @return the batchSize value. + */ + @Generated + public Integer getBatchSize() { + return this.batchSize; + } + + /** + * Set the batchSize property: The desired batch size which indicates number of documents. + * + * @param batchSize the batchSize value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setBatchSize(Integer batchSize) { + this.batchSize = batchSize; + return this; + } + + /** + * Get the degreeOfParallelism property: If set, the number of parallel calls that can be made to the Web API. + * + * @return the degreeOfParallelism value. + */ + @Generated + public Integer getDegreeOfParallelism() { + return this.degreeOfParallelism; + } + + /** + * Set the degreeOfParallelism property: If set, the number of parallel calls that can be made to the Web API. + * + * @param degreeOfParallelism the degreeOfParallelism value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setDegreeOfParallelism(Integer degreeOfParallelism) { + this.degreeOfParallelism = degreeOfParallelism; + return this; + } + + /** + * 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. + * + * @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. + * + * @param authResourceId the authResourceId value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setAuthResourceId(String authResourceId) { + this.authResourceId = authResourceId; + return this; + } + + /** + * 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. + * + * @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. + * + * @param authIdentity the authIdentity value to set. + * @return the ChatCompletionSkill object itself. + */ + @Generated + public ChatCompletionSkill setAuthIdentity(SearchIndexerDataIdentity authIdentity) { + this.authIdentity = authIdentity; + return this; + } + /** * Get the apiKey property: API key for authenticating to the model. Both apiKey and authIdentity cannot be * specified at the same time. - * + * * @return the apiKey value. */ @Generated @@ -97,7 +327,7 @@ public String getApiKey() { /** * Set the apiKey property: API key for authenticating to the model. Both apiKey and authIdentity cannot be * specified at the same time. - * + * * @param apiKey the apiKey value to set. * @return the ChatCompletionSkill object itself. */ @@ -110,31 +340,31 @@ public ChatCompletionSkill setApiKey(String apiKey) { /** * Get the commonModelParameters property: Common language model parameters that customers can tweak. If omitted, * reasonable defaults will be applied. - * + * * @return the commonModelParameters value. */ @Generated - public CommonModelParameters getCommonModelParameters() { + public ChatCompletionCommonModelParameters getCommonModelParameters() { return this.commonModelParameters; } /** * Set the commonModelParameters property: Common language model parameters that customers can tweak. If omitted, * reasonable defaults will be applied. - * + * * @param commonModelParameters the commonModelParameters value to set. * @return the ChatCompletionSkill object itself. */ @Generated - public ChatCompletionSkill setCommonModelParameters(CommonModelParameters commonModelParameters) { + public ChatCompletionSkill setCommonModelParameters(ChatCompletionCommonModelParameters commonModelParameters) { this.commonModelParameters = commonModelParameters; return this; } /** * Get the extraParameters property: Open-type dictionary for model-specific parameters that should be appended to - * the chat completions call. Follows Azure AI Foundry’s extensibility pattern. - * + * the chat completions call. Follows Azure AI Foundry's extensibility pattern. + * * @return the extraParameters value. */ @Generated @@ -144,8 +374,8 @@ public Map getExtraParameters() { /** * Set the extraParameters property: Open-type dictionary for model-specific parameters that should be appended to - * the chat completions call. Follows Azure AI Foundry’s extensibility pattern. - * + * the chat completions call. Follows Azure AI Foundry's extensibility pattern. + * * @param extraParameters the extraParameters value to set. * @return the ChatCompletionSkill object itself. */ @@ -158,7 +388,7 @@ public ChatCompletionSkill setExtraParameters(Map extraParameter /** * Get the extraParametersBehavior property: How extra parameters are handled by Azure AI Foundry. Default is * 'error'. - * + * * @return the extraParametersBehavior value. */ @Generated @@ -169,7 +399,7 @@ public ChatCompletionExtraParametersBehavior getExtraParametersBehavior() { /** * Set the extraParametersBehavior property: How extra parameters are handled by Azure AI Foundry. Default is * 'error'. - * + * * @param extraParametersBehavior the extraParametersBehavior value to set. * @return the ChatCompletionSkill object itself. */ @@ -183,7 +413,7 @@ public ChatCompletionExtraParametersBehavior getExtraParametersBehavior() { /** * Get the responseFormat property: Determines how the LLM should format its response. Defaults to 'text' response * type. - * + * * @return the responseFormat value. */ @Generated @@ -194,7 +424,7 @@ public ChatCompletionResponseFormat getResponseFormat() { /** * Set the responseFormat property: Determines how the LLM should format its response. Defaults to 'text' response * type. - * + * * @param responseFormat the responseFormat value to set. * @return the ChatCompletionSkill object itself. */ @@ -204,76 +434,6 @@ public ChatCompletionSkill setResponseFormat(ChatCompletionResponseFormat respon return this; } - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setHttpHeaders(Map httpHeaders) { - super.setHttpHeaders(httpHeaders); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setHttpMethod(String httpMethod) { - super.setHttpMethod(httpMethod); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setTimeout(Duration timeout) { - super.setTimeout(timeout); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setBatchSize(Integer batchSize) { - super.setBatchSize(batchSize); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setDegreeOfParallelism(Integer degreeOfParallelism) { - super.setDegreeOfParallelism(degreeOfParallelism); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setAuthResourceId(String authResourceId) { - super.setAuthResourceId(authResourceId); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ChatCompletionSkill setAuthIdentity(SearchIndexerDataIdentity authIdentity) { - super.setAuthIdentity(authIdentity); - return this; - } - /** * {@inheritDoc} */ @@ -313,18 +473,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeArrayField("inputs", getInputs(), (writer, element) -> writer.writeJson(element)); jsonWriter.writeArrayField("outputs", getOutputs(), (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("uri", getUri()); jsonWriter.writeStringField("name", getName()); jsonWriter.writeStringField("description", getDescription()); jsonWriter.writeStringField("context", getContext()); - jsonWriter.writeMapField("httpHeaders", getHttpHeaders(), (writer, element) -> writer.writeString(element)); - jsonWriter.writeStringField("httpMethod", getHttpMethod()); - jsonWriter.writeStringField("timeout", CoreUtils.durationToStringWithDays(getTimeout())); - jsonWriter.writeNumberField("batchSize", getBatchSize()); - jsonWriter.writeNumberField("degreeOfParallelism", getDegreeOfParallelism()); - jsonWriter.writeStringField("authResourceId", getAuthResourceId()); - jsonWriter.writeJsonField("authIdentity", getAuthIdentity()); + jsonWriter.writeStringField("uri", this.uri); jsonWriter.writeStringField("@odata.type", this.odataType); + jsonWriter.writeJsonField("httpHeaders", this.httpHeaders); + jsonWriter.writeStringField("httpMethod", this.httpMethod); + jsonWriter.writeStringField("timeout", CoreUtils.durationToStringWithDays(this.timeout)); + jsonWriter.writeNumberField("batchSize", this.batchSize); + jsonWriter.writeNumberField("degreeOfParallelism", this.degreeOfParallelism); + jsonWriter.writeStringField("authResourceId", this.authResourceId); + jsonWriter.writeJsonField("authIdentity", this.authIdentity); jsonWriter.writeStringField("apiKey", this.apiKey); jsonWriter.writeJsonField("commonModelParameters", this.commonModelParameters); jsonWriter.writeMapField("extraParameters", this.extraParameters, @@ -337,7 +497,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ChatCompletionSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ChatCompletionSkill if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -347,49 +507,44 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ChatCompletionSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; - boolean uriFound = false; - String uri = null; String name = null; String description = null; String context = null; - Map httpHeaders = null; + String uri = null; + String odataType = "#Microsoft.Skills.Custom.ChatCompletionSkill"; + WebApiHttpHeaders httpHeaders = null; String httpMethod = null; Duration timeout = null; Integer batchSize = null; Integer degreeOfParallelism = null; String authResourceId = null; SearchIndexerDataIdentity authIdentity = null; - String odataType = "#Microsoft.Skills.Custom.ChatCompletionSkill"; String apiKey = null; - CommonModelParameters commonModelParameters = null; + ChatCompletionCommonModelParameters commonModelParameters = null; Map extraParameters = null; ChatCompletionExtraParametersBehavior extraParametersBehavior = null; ChatCompletionResponseFormat responseFormat = 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 ("uri".equals(fieldName)) { - uri = reader.getString(); - uriFound = true; } else if ("name".equals(fieldName)) { name = reader.getString(); } else if ("description".equals(fieldName)) { description = reader.getString(); } else if ("context".equals(fieldName)) { context = reader.getString(); + } else if ("uri".equals(fieldName)) { + uri = reader.getString(); + } else if ("@odata.type".equals(fieldName)) { + odataType = reader.getString(); } else if ("httpHeaders".equals(fieldName)) { - httpHeaders = reader.readMap(reader1 -> reader1.getString()); + httpHeaders = WebApiHttpHeaders.fromJson(reader); } else if ("httpMethod".equals(fieldName)) { httpMethod = reader.getString(); } else if ("timeout".equals(fieldName)) { @@ -402,12 +557,10 @@ public static ChatCompletionSkill fromJson(JsonReader jsonReader) throws IOExcep authResourceId = reader.getString(); } else if ("authIdentity".equals(fieldName)) { authIdentity = SearchIndexerDataIdentity.fromJson(reader); - } else if ("@odata.type".equals(fieldName)) { - odataType = reader.getString(); } else if ("apiKey".equals(fieldName)) { apiKey = reader.getString(); } else if ("commonModelParameters".equals(fieldName)) { - commonModelParameters = CommonModelParameters.fromJson(reader); + commonModelParameters = ChatCompletionCommonModelParameters.fromJson(reader); } else if ("extraParameters".equals(fieldName)) { extraParameters = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("extraParametersBehavior".equals(fieldName)) { @@ -418,40 +571,24 @@ public static ChatCompletionSkill fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - if (inputsFound && outputsFound && uriFound) { - ChatCompletionSkill deserializedChatCompletionSkill = new ChatCompletionSkill(inputs, outputs, uri); - deserializedChatCompletionSkill.setName(name); - deserializedChatCompletionSkill.setDescription(description); - deserializedChatCompletionSkill.setContext(context); - deserializedChatCompletionSkill.setHttpHeaders(httpHeaders); - deserializedChatCompletionSkill.setHttpMethod(httpMethod); - deserializedChatCompletionSkill.setTimeout(timeout); - deserializedChatCompletionSkill.setBatchSize(batchSize); - deserializedChatCompletionSkill.setDegreeOfParallelism(degreeOfParallelism); - deserializedChatCompletionSkill.setAuthResourceId(authResourceId); - deserializedChatCompletionSkill.setAuthIdentity(authIdentity); - deserializedChatCompletionSkill.odataType = odataType; - deserializedChatCompletionSkill.apiKey = apiKey; - deserializedChatCompletionSkill.commonModelParameters = commonModelParameters; - deserializedChatCompletionSkill.extraParameters = extraParameters; - deserializedChatCompletionSkill.extraParametersBehavior = extraParametersBehavior; - deserializedChatCompletionSkill.responseFormat = responseFormat; - - return deserializedChatCompletionSkill; - } - 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)); + ChatCompletionSkill deserializedChatCompletionSkill = new ChatCompletionSkill(inputs, outputs, uri); + deserializedChatCompletionSkill.setName(name); + deserializedChatCompletionSkill.setDescription(description); + deserializedChatCompletionSkill.setContext(context); + deserializedChatCompletionSkill.odataType = odataType; + deserializedChatCompletionSkill.httpHeaders = httpHeaders; + deserializedChatCompletionSkill.httpMethod = httpMethod; + deserializedChatCompletionSkill.timeout = timeout; + deserializedChatCompletionSkill.batchSize = batchSize; + deserializedChatCompletionSkill.degreeOfParallelism = degreeOfParallelism; + deserializedChatCompletionSkill.authResourceId = authResourceId; + deserializedChatCompletionSkill.authIdentity = authIdentity; + deserializedChatCompletionSkill.apiKey = apiKey; + deserializedChatCompletionSkill.commonModelParameters = commonModelParameters; + deserializedChatCompletionSkill.extraParameters = extraParameters; + deserializedChatCompletionSkill.extraParametersBehavior = extraParametersBehavior; + deserializedChatCompletionSkill.responseFormat = responseFormat; + return deserializedChatCompletionSkill; }); } } 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/indexes/models/CjkBigramTokenFilter.java index 8fbf63739270..01fe4877863d 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/indexes/models/CjkBigramTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,7 +20,7 @@ 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"; @@ -51,7 +49,7 @@ public CjkBigramTokenFilter(String 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. */ @@ -71,6 +69,17 @@ 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. + */ + public CjkBigramTokenFilter setIgnoreScripts(CjkBigramTokenFilterScripts... ignoreScripts) { + this.ignoreScripts = (ignoreScripts == null) ? null : Arrays.asList(ignoreScripts); + return this; + } + /** * Set the ignoreScripts property: The scripts to ignore. * @@ -90,7 +99,7 @@ public CjkBigramTokenFilter setIgnoreScripts(List i * @return the outputUnigrams value. */ @Generated - public Boolean areOutputUnigrams() { + public Boolean isOutputUnigrams() { return this.outputUnigrams; } @@ -134,7 +143,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -144,7 +152,6 @@ public static CjkBigramTokenFilter fromJson(JsonReader jsonReader) throws IOExce 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)) { @@ -156,25 +163,11 @@ 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; + return deserializedCjkBigramTokenFilter; }); } - - /** - * 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; - } } 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 index 8bf0a5c2f51e..401dc8f0aa90 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/ClassicSimilarityAlgorithm.java index 71f9b0e35040..19a085360072 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/indexes/models/ClassicSimilarityAlgorithm.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -20,8 +17,9 @@ */ @Immutable public final class ClassicSimilarityAlgorithm extends SimilarityAlgorithm { + /* - * The @odata.type property. + * The discriminator for derived types. */ @Generated private String odataType = "#Microsoft.Azure.Search.ClassicSimilarity"; @@ -34,8 +32,8 @@ public ClassicSimilarityAlgorithm() { } /** - * Get the odataType property: The @odata.type property. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ @Generated @@ -57,7 +55,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ClassicSimilarityAlgorithm from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ClassicSimilarityAlgorithm if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -70,14 +68,12 @@ public static ClassicSimilarityAlgorithm fromJson(JsonReader jsonReader) throws while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedClassicSimilarityAlgorithm.odataType = reader.getString(); } else { reader.skipChildren(); } } - return deserializedClassicSimilarityAlgorithm; }); } 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/indexes/models/ClassicTokenizer.java index 4ffc1d68737c..50a77ce63846 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/indexes/models/ClassicTokenizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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"; @@ -34,7 +32,7 @@ public final class ClassicTokenizer extends LexicalTokenizer { /** * Creates an instance of ClassicTokenizer class. - * + * * @param name the name value to set. */ @Generated @@ -43,8 +41,8 @@ public ClassicTokenizer(String 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 @@ -56,7 +54,7 @@ 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 @@ -67,7 +65,7 @@ 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 ClassicTokenizer object itself. */ @@ -92,7 +90,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ClassicTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ClassicTokenizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -102,17 +100,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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)) { @@ -121,14 +116,10 @@ public static ClassicTokenizer fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (nameFound) { - ClassicTokenizer deserializedClassicTokenizer = new ClassicTokenizer(name); - deserializedClassicTokenizer.odataType = odataType; - deserializedClassicTokenizer.maxTokenLength = maxTokenLength; - - return deserializedClassicTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + ClassicTokenizer deserializedClassicTokenizer = new ClassicTokenizer(name); + deserializedClassicTokenizer.odataType = odataType; + deserializedClassicTokenizer.maxTokenLength = maxTokenLength; + 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/indexes/models/CognitiveServicesAccount.java index 30ef5ef4b0ae..6b5b388f826e 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/indexes/models/CognitiveServicesAccount.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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"; @@ -39,9 +37,8 @@ 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 @@ -51,7 +48,7 @@ public String getOdataType() { /** * Get the description property: Description of the Azure AI service resource attached to a skillset. - * + * * @return the description value. */ @Generated @@ -61,7 +58,7 @@ public String getDescription() { /** * Set the description property: Description of the Azure AI service resource attached to a skillset. - * + * * @param description the description value to set. * @return the CognitiveServicesAccount object itself. */ @@ -85,7 +82,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CognitiveServicesAccount from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CognitiveServicesAccount if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -96,7 +93,8 @@ public static CognitiveServicesAccount fromJson(JsonReader jsonReader) throws IO return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -130,7 +128,6 @@ static CognitiveServicesAccount fromJsonKnownDiscriminator(JsonReader jsonReader while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedCognitiveServicesAccount.odataType = reader.getString(); } else if ("description".equals(fieldName)) { @@ -139,7 +136,6 @@ static CognitiveServicesAccount fromJsonKnownDiscriminator(JsonReader jsonReader reader.skipChildren(); } } - return deserializedCognitiveServicesAccount; }); } 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/indexes/models/CognitiveServicesAccountKey.java index 12f4910f47d5..789e133794e6 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/indexes/models/CognitiveServicesAccountKey.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,7 +17,7 @@ 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"; @@ -28,7 +26,7 @@ public final class CognitiveServicesAccountKey extends CognitiveServicesAccount * The key used to provision the Azure AI service resource attached to a skillset. */ @Generated - private String key; + private final String key; /** * Creates an instance of CognitiveServicesAccountKey class. @@ -41,8 +39,7 @@ public CognitiveServicesAccountKey(String 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. */ @@ -98,7 +95,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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) { @@ -108,32 +104,16 @@ public static CognitiveServicesAccountKey fromJson(JsonReader jsonReader) throws 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; + return deserializedCognitiveServicesAccountKey; }); } - - /** - * 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; - } } 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/indexes/models/CommonGramTokenFilter.java index 55a585cad307..0643a6f2ff63 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/indexes/models/CommonGramTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -21,8 +18,9 @@ */ @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"; @@ -37,18 +35,29 @@ public final class CommonGramTokenFilter extends TokenFilter { * A value indicating whether common words matching will be case insensitive. Default is false. */ @Generated - private Boolean caseIgnored; + 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. */ @Generated - private Boolean queryModeUsed; + private Boolean useQueryMode; + + /** + * Creates an instance of CommonGramTokenFilter class. + * + * @param name the name value to set. + * @param commonWords the commonWords value to set. + */ + public CommonGramTokenFilter(String name, String... commonWords) { + super(name); + this.commonWords = (commonWords == null) ? null : Arrays.asList(commonWords); + } /** * Creates an instance of CommonGramTokenFilter class. - * + * * @param name the name value to set. * @param commonWords the commonWords value to set. */ @@ -59,8 +68,8 @@ public CommonGramTokenFilter(String name, List 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 @@ -71,7 +80,7 @@ public String getOdataType() { /** * Get the commonWords property: The set of common words. - * + * * @return the commonWords value. */ @Generated @@ -80,52 +89,52 @@ public List getCommonWords() { } /** - * Get the caseIgnored property: A value indicating whether common words matching will be case insensitive. Default + * 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. */ @Generated - public Boolean isCaseIgnored() { - return this.caseIgnored; + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether common words matching will be case insensitive. Default + * 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. */ @Generated - public CommonGramTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + 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 + * 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. */ @Generated - public Boolean isQueryModeUsed() { - return this.queryModeUsed; + 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 + * 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. */ @Generated - public CommonGramTokenFilter setQueryModeUsed(Boolean queryModeUsed) { - this.queryModeUsed = queryModeUsed; + public CommonGramTokenFilter setUseQueryMode(Boolean useQueryMode) { + this.useQueryMode = useQueryMode; return this; } @@ -139,14 +148,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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(); } /** * Reads an instance of CommonGramTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CommonGramTokenFilter if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -156,51 +165,33 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; - - 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)); + CommonGramTokenFilter deserializedCommonGramTokenFilter = new CommonGramTokenFilter(name, commonWords); + deserializedCommonGramTokenFilter.odataType = odataType; + deserializedCommonGramTokenFilter.ignoreCase = ignoreCase; + deserializedCommonGramTokenFilter.useQueryMode = useQueryMode; + 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/indexes/models/ConditionalSkill.java index 47ad1f55f330..2b9e8d443b09 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/indexes/models/ConditionalSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,15 +16,16 @@ */ @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"; /** * Creates an instance of ConditionalSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -38,8 +35,8 @@ public ConditionalSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -117,13 +112,10 @@ public static ConditionalSkill fromJson(JsonReader jsonReader) throws IOExceptio 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)) { @@ -136,25 +128,12 @@ 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; - - 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)); + ConditionalSkill deserializedConditionalSkill = new ConditionalSkill(inputs, outputs); + deserializedConditionalSkill.setName(name); + deserializedConditionalSkill.setDescription(description); + deserializedConditionalSkill.setContext(context); + deserializedConditionalSkill.odataType = odataType; + return deserializedConditionalSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkill.java index 723b32ecb05a..e3f472a44eb0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkill.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -21,14 +18,15 @@ */ @Fluent public final class ContentUnderstandingSkill extends SearchIndexerSkill { + /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ @Generated private String odataType = "#Microsoft.Skills.Util.ContentUnderstandingSkill"; /* - * Controls the cardinality of the content extracted from the document by the skill + * Controls the cardinality of the content extracted from the document by the skill. */ @Generated private List extractionOptions; @@ -41,7 +39,7 @@ public final class ContentUnderstandingSkill extends SearchIndexerSkill { /** * Creates an instance of ContentUnderstandingSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -51,8 +49,8 @@ public ContentUnderstandingSkill(List inputs, List getExtractionOptions() { /** * Set the extractionOptions property: Controls the cardinality of the content extracted from the document by the * skill. - * + * + * @param extractionOptions the extractionOptions value to set. + * @return the ContentUnderstandingSkill object itself. + */ + public ContentUnderstandingSkill + setExtractionOptions(ContentUnderstandingSkillExtractionOptions... extractionOptions) { + this.extractionOptions = (extractionOptions == null) ? null : Arrays.asList(extractionOptions); + return this; + } + + /** + * Set the extractionOptions property: Controls the cardinality of the content extracted from the document by the + * skill. + * * @param extractionOptions the extractionOptions value to set. * @return the ContentUnderstandingSkill object itself. */ @@ -88,7 +99,7 @@ public List getExtractionOptions() { /** * Get the chunkingProperties property: Controls the cardinality for chunking the content. - * + * * @return the chunkingProperties value. */ @Generated @@ -98,7 +109,7 @@ public ContentUnderstandingSkillChunkingProperties getChunkingProperties() { /** * Set the chunkingProperties property: Controls the cardinality for chunking the content. - * + * * @param chunkingProperties the chunkingProperties value to set. * @return the ContentUnderstandingSkill object itself. */ @@ -160,7 +171,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ContentUnderstandingSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ContentUnderstandingSkill if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -170,9 +181,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ContentUnderstandingSkill 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; @@ -183,13 +192,10 @@ public static ContentUnderstandingSkill fromJson(JsonReader jsonReader) throws I 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)) { @@ -207,28 +213,15 @@ public static ContentUnderstandingSkill fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (inputsFound && outputsFound) { - ContentUnderstandingSkill deserializedContentUnderstandingSkill - = new ContentUnderstandingSkill(inputs, outputs); - deserializedContentUnderstandingSkill.setName(name); - deserializedContentUnderstandingSkill.setDescription(description); - deserializedContentUnderstandingSkill.setContext(context); - deserializedContentUnderstandingSkill.odataType = odataType; - deserializedContentUnderstandingSkill.extractionOptions = extractionOptions; - deserializedContentUnderstandingSkill.chunkingProperties = chunkingProperties; - - return deserializedContentUnderstandingSkill; - } - List missingProperties = new ArrayList<>(); - if (!inputsFound) { - missingProperties.add("inputs"); - } - if (!outputsFound) { - missingProperties.add("outputs"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + ContentUnderstandingSkill deserializedContentUnderstandingSkill + = new ContentUnderstandingSkill(inputs, outputs); + deserializedContentUnderstandingSkill.setName(name); + deserializedContentUnderstandingSkill.setDescription(description); + deserializedContentUnderstandingSkill.setContext(context); + deserializedContentUnderstandingSkill.odataType = odataType; + deserializedContentUnderstandingSkill.extractionOptions = extractionOptions; + deserializedContentUnderstandingSkill.chunkingProperties = chunkingProperties; + return deserializedContentUnderstandingSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingProperties.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingProperties.java index 6b90d96cd534..f0e9adf41b60 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingProperties.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingProperties.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,6 +17,7 @@ @Fluent public final class ContentUnderstandingSkillChunkingProperties implements JsonSerializable { + /* * The unit of the chunk. */ @@ -47,7 +45,7 @@ public ContentUnderstandingSkillChunkingProperties() { /** * Get the unit property: The unit of the chunk. - * + * * @return the unit value. */ @Generated @@ -57,7 +55,7 @@ public ContentUnderstandingSkillChunkingUnit getUnit() { /** * Set the unit property: The unit of the chunk. - * + * * @param unit the unit value to set. * @return the ContentUnderstandingSkillChunkingProperties object itself. */ @@ -69,7 +67,7 @@ public ContentUnderstandingSkillChunkingProperties setUnit(ContentUnderstandingS /** * Get the maximumLength property: The maximum chunk length in characters. Default is 500. - * + * * @return the maximumLength value. */ @Generated @@ -79,7 +77,7 @@ public Integer getMaximumLength() { /** * Set the maximumLength property: The maximum chunk length in characters. Default is 500. - * + * * @param maximumLength the maximumLength value to set. * @return the ContentUnderstandingSkillChunkingProperties object itself. */ @@ -91,7 +89,7 @@ public ContentUnderstandingSkillChunkingProperties setMaximumLength(Integer maxi /** * Get the overlapLength property: The length of overlap provided between two text chunks. Default is 0. - * + * * @return the overlapLength value. */ @Generated @@ -101,7 +99,7 @@ public Integer getOverlapLength() { /** * Set the overlapLength property: The length of overlap provided between two text chunks. Default is 0. - * + * * @param overlapLength the overlapLength value to set. * @return the ContentUnderstandingSkillChunkingProperties object itself. */ @@ -126,7 +124,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ContentUnderstandingSkillChunkingProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ContentUnderstandingSkillChunkingProperties if the JsonReader was pointing to an instance * of it, or null if it was pointing to JSON null. @@ -140,7 +138,6 @@ public static ContentUnderstandingSkillChunkingProperties fromJson(JsonReader js while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("unit".equals(fieldName)) { deserializedContentUnderstandingSkillChunkingProperties.unit = ContentUnderstandingSkillChunkingUnit.fromString(reader.getString()); @@ -154,7 +151,6 @@ public static ContentUnderstandingSkillChunkingProperties fromJson(JsonReader js reader.skipChildren(); } } - return deserializedContentUnderstandingSkillChunkingProperties; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingUnit.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingUnit.java index a83ff1398964..261b593cf4b5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingUnit.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingUnit.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class ContentUnderstandingSkillChunkingUnit extends ExpandableStringEnum { + /** * Specifies chunk by characters. */ @@ -23,7 +21,7 @@ public final class ContentUnderstandingSkillChunkingUnit /** * Creates a new instance of ContentUnderstandingSkillChunkingUnit value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -33,7 +31,7 @@ public ContentUnderstandingSkillChunkingUnit() { /** * Creates or finds a ContentUnderstandingSkillChunkingUnit from its string representation. - * + * * @param name a name to look for. * @return the corresponding ContentUnderstandingSkillChunkingUnit. */ @@ -44,7 +42,7 @@ public static ContentUnderstandingSkillChunkingUnit fromString(String name) { /** * Gets known ContentUnderstandingSkillChunkingUnit values. - * + * * @return known ContentUnderstandingSkillChunkingUnit values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillExtractionOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillExtractionOptions.java index 90cf1e9c5d71..96031204dd46 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillExtractionOptions.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillExtractionOptions.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class ContentUnderstandingSkillExtractionOptions extends ExpandableStringEnum { + /** * Specify that image content should be extracted from the document. */ @@ -29,7 +27,7 @@ public final class ContentUnderstandingSkillExtractionOptions /** * Creates a new instance of ContentUnderstandingSkillExtractionOptions value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -39,7 +37,7 @@ public ContentUnderstandingSkillExtractionOptions() { /** * Creates or finds a ContentUnderstandingSkillExtractionOptions from its string representation. - * + * * @param name a name to look for. * @return the corresponding ContentUnderstandingSkillExtractionOptions. */ @@ -50,7 +48,7 @@ public static ContentUnderstandingSkillExtractionOptions fromString(String name) /** * Gets known ContentUnderstandingSkillExtractionOptions values. - * + * * @return known ContentUnderstandingSkillExtractionOptions values. */ @Generated 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/indexes/models/CorsOptions.java index 79c8f36d7a37..429a2e63e3c9 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/indexes/models/CorsOptions.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @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 @@ -36,7 +35,16 @@ public final class CorsOptions implements JsonSerializable { /** * Creates an instance of CorsOptions class. - * + * + * @param allowedOrigins the allowedOrigins value to set. + */ + public CorsOptions(String... allowedOrigins) { + this.allowedOrigins = (allowedOrigins == null) ? null : Arrays.asList(allowedOrigins); + } + + /** + * Creates an instance of CorsOptions class. + * * @param allowedOrigins the allowedOrigins value to set. */ @Generated @@ -48,7 +56,7 @@ public CorsOptions(List 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). - * + * * @return the allowedOrigins value. */ @Generated @@ -59,7 +67,7 @@ public List getAllowedOrigins() { /** * Get the maxAgeInSeconds property: The duration for which browsers should cache CORS preflight responses. Defaults * to 5 minutes. - * + * * @return the maxAgeInSeconds value. */ @Generated @@ -70,7 +78,7 @@ public Long getMaxAgeInSeconds() { /** * Set the maxAgeInSeconds property: The duration for which browsers should cache CORS preflight responses. Defaults * to 5 minutes. - * + * * @param maxAgeInSeconds the maxAgeInSeconds value to set. * @return the CorsOptions object itself. */ @@ -95,7 +103,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CorsOptions from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CorsOptions if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -105,29 +113,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedCorsOptions; - } - throw new IllegalStateException("Missing required property: allowedOrigins"); + CorsOptions deserializedCorsOptions = new CorsOptions(allowedOrigins); + deserializedCorsOptions.maxAgeInSeconds = maxAgeInSeconds; + return deserializedCorsOptions; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateDataSourceConnectionOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateDataSourceConnectionOptions.java deleted file mode 100644 index 5c4f092ca2db..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateDataSourceConnectionOptions.java +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import java.util.Objects; - -/** - * This model represents a property bag containing all options for creating or updating a {@link - * SearchIndexerDataSourceConnection data source connection}. - */ -public final class CreateOrUpdateDataSourceConnectionOptions { - private final SearchIndexerDataSourceConnection dataSourceConnection; - - private boolean onlyIfUnchanged; - private Boolean cacheResetRequirementsIgnored; - - /** - * Creates the property bag used to create or update a {@link SearchIndexerDataSourceConnection data source - * connection}. - * - * @param dataSourceConnection The {@link SearchIndexerDataSourceConnection data source connection} being created or - * updated. - * @throws NullPointerException If {@code dataSourceConnection} is null. - */ - public CreateOrUpdateDataSourceConnectionOptions(SearchIndexerDataSourceConnection dataSourceConnection) { - this.dataSourceConnection - = Objects.requireNonNull(dataSourceConnection, "'dataSourceConnection' cannot be null."); - } - - /** - * Gets the {@link SearchIndexerDataSourceConnection data source connection} that will be created or updated. - * - * @return The {@link SearchIndexerDataSourceConnection data source connection} that will be created or updated. - */ - public SearchIndexerDataSourceConnection getDataSourceConnection() { - return dataSourceConnection; - } - - /** - * Sets the flag that determines whether an update will only occur if the {@link SearchIndexerDataSourceConnection - * data source connection} has not been changed since the update has been triggered. - * - * @param onlyIfUnchanged Flag that determines whether an update will only occur if the {@link - * SearchIndexerDataSourceConnection data source connection} has not been changed since the update has been - * triggered. - * @return The updated CreateOrUpdateDataSourceConnectionOptions object. - */ - public CreateOrUpdateDataSourceConnectionOptions setOnlyIfUnchanged(boolean onlyIfUnchanged) { - this.onlyIfUnchanged = onlyIfUnchanged; - return this; - } - - /** - * Gets the flag that determines whether an update will only occur if the {@link SearchIndexerDataSourceConnection - * data source connection} has not been changed since the update has been triggered. - * - * @return Whether an update will only occur if the {@link SearchIndexerDataSourceConnection data source connection} - * has not been changed since the update has been triggered. - */ - public boolean isOnlyIfUnchanged() { - return onlyIfUnchanged; - } - - /** - * Sets an optional flag that determines whether the created or updated {@link SearchIndexerDataSourceConnection - * data source connection} ignores cache reset requirements. - * - * @param cacheResetRequirementsIgnored An optional flag that determines whether the created or updated {@link - * SearchIndexerDataSourceConnection data source connection} ignores cache reset requirements. - * @return The updated CreateOrUpdateDataSourceConnectionOptions object. - */ - public CreateOrUpdateDataSourceConnectionOptions - setCacheResetRequirementsIgnored(Boolean cacheResetRequirementsIgnored) { - this.cacheResetRequirementsIgnored = cacheResetRequirementsIgnored; - return this; - } - - /** - * Gets an optional flag that determines whether the created or updated {@link SearchIndexerDataSourceConnection - * data source connection} ignores cache reset requirements. - * - * @return Whether the created or updated {@link SearchIndexerDataSourceConnection data source connection} ignores - * cache reset requirements. - */ - public Boolean isCacheResetRequirementsIgnored() { - return cacheResetRequirementsIgnored; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateIndexerOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateIndexerOptions.java deleted file mode 100644 index f726fa0da869..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateIndexerOptions.java +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import java.util.Objects; - -/** - * This model represents a property bag containing all options for creating or updating an {@link SearchIndexer - * indexer}. - */ -public class CreateOrUpdateIndexerOptions { - private final SearchIndexer indexer; - - private boolean onlyIfUnchanged; - private Boolean cacheReprocessingChangeDetectionDisabled; - private Boolean cacheResetRequirementsIgnored; - - /** - * Creates the property bag used to create or update an {@link SearchIndexer indexer}. - * - * @param indexer The {@link SearchIndexer indexer} being created or updated. - * @throws NullPointerException If {@code indexer} is null. - */ - public CreateOrUpdateIndexerOptions(SearchIndexer indexer) { - this.indexer = Objects.requireNonNull(indexer, "'indexer' cannot be null."); - } - - /** - * Gets the {@link SearchIndexer indexer} that will be created or updated. - * - * @return The {@link SearchIndexer indexer} that will be created or updated. - */ - public SearchIndexer getIndexer() { - return indexer; - } - - /** - * Sets the flag that determines whether an update will only occur if the {@link SearchIndexer indexer} has not been - * changed since the update has been triggered. - * - * @param onlyIfUnchanged Flag that determines whether an update will only occur if the {@link SearchIndexer - * indexer} has not been changed since the update has been triggered. - * @return The updated CreateOrUpdateIndexerOptions object. - */ - public CreateOrUpdateIndexerOptions setOnlyIfUnchanged(boolean onlyIfUnchanged) { - this.onlyIfUnchanged = onlyIfUnchanged; - return this; - } - - /** - * Gets the flag that determines whether an update will only occur if the {@link SearchIndexer indexer} has not been - * changed since the update has been triggered. - * - * @return Whether an update will only occur if the {@link SearchIndexer indexer} has not been changed since the - * update has been triggered. - */ - public boolean isOnlyIfUnchanged() { - return onlyIfUnchanged; - } - - /** - * Sets an optional flag that determines whether the created or updated {@link SearchIndexer indexer} disables cache - * reprocessing change detection. - * - * @param cacheReprocessingChangeDetectionDisabled An optional flag that determines whether the created or updated - * {@link SearchIndexer indexer} disables cache reprocessing change detection. - * @return The updated CreateOrUpdateIndexerOptions object. - */ - public CreateOrUpdateIndexerOptions - setCacheReprocessingChangeDetectionDisabled(Boolean cacheReprocessingChangeDetectionDisabled) { - this.cacheReprocessingChangeDetectionDisabled = cacheReprocessingChangeDetectionDisabled; - return this; - } - - /** - * Gets an optional flag that determines whether the created or updated {@link SearchIndexer indexer} disables cache - * reprocessing change detection. - * - * @return Whether the created or updated {@link SearchIndexer indexer} disables cache reprocessing change - * detection. - */ - public Boolean isCacheReprocessingChangeDetectionDisabled() { - return cacheReprocessingChangeDetectionDisabled; - } - - /** - * Sets an optional flag that determines whether the created or updated {@link SearchIndexer indexer} ignores cache - * reset requirements. - * - * @param cacheResetRequirementsIgnored An optional flag that determines whether the created or updated {@link - * SearchIndexer indexer} ignores cache reset requirements. - * @return The updated CreateOrUpdateIndexerOptions object. - */ - public CreateOrUpdateIndexerOptions setCacheResetRequirementsIgnored(Boolean cacheResetRequirementsIgnored) { - this.cacheResetRequirementsIgnored = cacheResetRequirementsIgnored; - return this; - } - - /** - * Gets an optional flag that determines whether the created or updated {@link SearchIndexer indexer} ignores cache - * reset requirements. - * - * @return Whether the created or updated {@link SearchIndexer indexer} ignores cache reset requirements. - */ - public Boolean isCacheResetRequirementsIgnored() { - return cacheResetRequirementsIgnored; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateSkillsetOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateSkillsetOptions.java deleted file mode 100644 index 7fe6d7abd6b6..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreateOrUpdateSkillsetOptions.java +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.indexes.models; - -import java.util.Objects; - -/** - * This model represents a property bag containing all options for creating or updating a {@link SearchIndexerSkillset - * skillset}. - */ -public final class CreateOrUpdateSkillsetOptions { - private final SearchIndexerSkillset skillset; - - private boolean onlyIfUnchanged; - private Boolean cacheReprocessingChangeDetectionDisabled; - private Boolean cacheResetRequirementsIgnored; - - /** - * Creates the property bag used to create or update a {@link SearchIndexerSkillset skillset}. - * - * @param skillset The {@link SearchIndexerSkillset skillset} being created or updated. - * @throws NullPointerException If {@code skillset} is null. - */ - public CreateOrUpdateSkillsetOptions(SearchIndexerSkillset skillset) { - this.skillset = Objects.requireNonNull(skillset, "'skillset' cannot be null."); - } - - /** - * Gets the {@link SearchIndexerSkillset skillset} that will be created or updated. - * - * @return The {@link SearchIndexerSkillset skillset} that will be created or updated. - */ - public SearchIndexerSkillset getSkillset() { - return skillset; - } - - /** - * Sets the flag that determines whether an update will only occur if the {@link SearchIndexerSkillset skillset} has - * not been changed since the update has been triggered. - * - * @param onlyIfUnchanged Flag that determines whether an update will only occur if the {@link SearchIndexerSkillset - * skillset} has not been changed since the update has been triggered. - * @return The updated CreateOrUpdateSkillsetOptions object. - */ - public CreateOrUpdateSkillsetOptions setOnlyIfUnchanged(boolean onlyIfUnchanged) { - this.onlyIfUnchanged = onlyIfUnchanged; - return this; - } - - /** - * Gets the flag that determines whether an update will only occur if the {@link SearchIndexerSkillset skillset} has - * not been changed since the update has been triggered. - * - * @return Whether an update will only occur if the {@link SearchIndexerSkillset skillset} has not been changed - * since the update has been triggered. - */ - public boolean isOnlyIfUnchanged() { - return onlyIfUnchanged; - } - - /** - * Sets an optional flag that determines whether the created or updated {@link SearchIndexerSkillset skillset} - * disables cache reprocessing change detection. - * - * @param cacheReprocessingChangeDetectionDisabled An optional flag that determines whether the created or updated - * {@link SearchIndexerSkillset skillset} disables cache reprocessing change detection. - * @return The updated CreateOrUpdateSkillsetOptions object. - */ - public CreateOrUpdateSkillsetOptions - setCacheReprocessingChangeDetectionDisabled(Boolean cacheReprocessingChangeDetectionDisabled) { - this.cacheReprocessingChangeDetectionDisabled = cacheReprocessingChangeDetectionDisabled; - return this; - } - - /** - * Gets an optional flag that determines whether the created or updated {@link SearchIndexerSkillset skillset} - * disables cache reprocessing change detection. - * - * @return Whether the created or updated {@link SearchIndexerSkillset skillset} disables cache reprocessing change - * detection. - */ - public Boolean isCacheReprocessingChangeDetectionDisabled() { - return cacheReprocessingChangeDetectionDisabled; - } - - /** - * Sets an optional flag that determines whether the created or updated {@link SearchIndexerSkillset skillset} - * ignores cache reset requirements. - * - * @param cacheResetRequirementsIgnored An optional flag that determines whether the created or updated {@link - * SearchIndexerSkillset skillset} ignores cache reset requirements. - * @return The updated CreateOrUpdateSkillsetOptions object. - */ - public CreateOrUpdateSkillsetOptions setCacheResetRequirementsIgnored(Boolean cacheResetRequirementsIgnored) { - this.cacheResetRequirementsIgnored = cacheResetRequirementsIgnored; - return this; - } - - /** - * Gets an optional flag that determines whether the created or updated {@link SearchIndexerSkillset skillset} - * ignores cache reset requirements. - * - * @return Whether the created or updated {@link SearchIndexerSkillset skillset} ignores cache reset requirements. - */ - public Boolean isCacheResetRequirementsIgnored() { - return cacheResetRequirementsIgnored; - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreatedResources.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreatedResources.java new file mode 100644 index 000000000000..c662e57521e3 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CreatedResources.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.indexes.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.LinkedHashMap; +import java.util.Map; + +/** + * Resources created by the knowledge source. Keys represent resource types (e.g., 'datasource', 'indexer', 'skillset', + * 'index') and values represent resource names. + */ +@Immutable +public final class CreatedResources implements JsonSerializable { + + /* + * Resources created by the knowledge source. Keys represent resource types (e.g., 'datasource', 'indexer', + * 'skillset', 'index') and values represent resource names. + */ + @Generated + private Map additionalProperties; + + /** + * Creates an instance of CreatedResources class. + */ + @Generated + private CreatedResources() { + } + + /** + * Get the additionalProperties property: Resources created by the knowledge source. Keys represent resource types + * (e.g., 'datasource', 'indexer', 'skillset', 'index') and values represent resource names. + * + * @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.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of CreatedResources from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of CreatedResources 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 CreatedResources. + */ + @Generated + public static CreatedResources fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + CreatedResources deserializedCreatedResources = new CreatedResources(); + 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.getString()); + } + deserializedCreatedResources.additionalProperties = additionalProperties; + return deserializedCreatedResources; + }); + } +} 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/indexes/models/CustomAnalyzer.java index 1493d297e5d9..a90909c5ceb6 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/indexes/models/CustomAnalyzer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,7 +9,6 @@ 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; @@ -24,7 +21,7 @@ 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"; @@ -64,7 +61,7 @@ public CustomAnalyzer(String name, LexicalTokenizerName 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. */ @@ -97,6 +94,19 @@ 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. + * + * @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; + } + /** * 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 @@ -123,6 +133,19 @@ 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. + * + * @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; + } + /** * 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 @@ -166,9 +189,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -178,10 +199,8 @@ public static CustomAnalyzer fromJson(JsonReader jsonReader) throws IOException 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)) { @@ -192,48 +211,11 @@ 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)); + CustomAnalyzer deserializedCustomAnalyzer = new CustomAnalyzer(name, tokenizer); + deserializedCustomAnalyzer.odataType = odataType; + deserializedCustomAnalyzer.tokenFilters = tokenFilters; + deserializedCustomAnalyzer.charFilters = charFilters; + return deserializedCustomAnalyzer; }); } - - /** - * 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; - } - - /** - * 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; - } } 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/indexes/models/CustomEntity.java index 67c51cae85a6..3295d3a99a1d 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/indexes/models/CustomEntity.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @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. @@ -108,7 +107,7 @@ public final class CustomEntity implements JsonSerializable { /** * Creates an instance of CustomEntity class. - * + * * @param name the name value to set. */ @Generated @@ -119,7 +118,7 @@ public CustomEntity(String 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. - * + * * @return the name value. */ @Generated @@ -130,7 +129,7 @@ public String getName() { /** * 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. - * + * * @return the description value. */ @Generated @@ -141,7 +140,7 @@ public String getDescription() { /** * 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. - * + * * @param description the description value to set. * @return the CustomEntity object itself. */ @@ -154,7 +153,7 @@ public CustomEntity setDescription(String description) { /** * 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 @@ -165,7 +164,7 @@ public String getType() { /** * 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. */ @@ -178,7 +177,7 @@ public CustomEntity setType(String type) { /** * 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 @@ -189,7 +188,7 @@ public String getSubtype() { /** * 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. */ @@ -202,7 +201,7 @@ public CustomEntity setSubtype(String subtype) { /** * 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 @@ -213,7 +212,7 @@ public String getId() { /** * 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. */ @@ -227,7 +226,7 @@ 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. - * + * * @return the caseSensitive value. */ @Generated @@ -239,7 +238,7 @@ public Boolean isCaseSensitive() { * 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. - * + * * @param caseSensitive the caseSensitive value to set. * @return the CustomEntity object itself. */ @@ -252,7 +251,7 @@ public CustomEntity setCaseSensitive(Boolean caseSensitive) { /** * Get the accentSensitive property: Defaults to false. Boolean value denoting whether comparisons with the entity * name should be sensitive to accent. - * + * * @return the accentSensitive value. */ @Generated @@ -263,7 +262,7 @@ public Boolean isAccentSensitive() { /** * Set the accentSensitive property: Defaults to false. Boolean value denoting whether comparisons with the entity * name should be sensitive to accent. - * + * * @param accentSensitive the accentSensitive value to set. * @return the CustomEntity object itself. */ @@ -279,7 +278,7 @@ public CustomEntity setAccentSensitive(Boolean accentSensitive) { * 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 @@ -293,7 +292,7 @@ public Integer getFuzzyEditDistance() { * 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. */ @@ -306,7 +305,7 @@ public CustomEntity setFuzzyEditDistance(Integer fuzzyEditDistance) { /** * Get the defaultCaseSensitive property: Changes the default case sensitivity value for this entity. It be used to * change the default value of all aliases caseSensitive values. - * + * * @return the defaultCaseSensitive value. */ @Generated @@ -317,7 +316,7 @@ public Boolean isDefaultCaseSensitive() { /** * Set the defaultCaseSensitive property: Changes the default case sensitivity value for this entity. It be used to * change the default value of all aliases caseSensitive values. - * + * * @param defaultCaseSensitive the defaultCaseSensitive value to set. * @return the CustomEntity object itself. */ @@ -330,7 +329,7 @@ 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. - * + * * @return the defaultAccentSensitive value. */ @Generated @@ -341,7 +340,7 @@ public Boolean isDefaultAccentSensitive() { /** * 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. - * + * * @param defaultAccentSensitive the defaultAccentSensitive value to set. * @return the CustomEntity object itself. */ @@ -354,7 +353,7 @@ 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. - * + * * @return the defaultFuzzyEditDistance value. */ @Generated @@ -365,7 +364,7 @@ public Integer getDefaultFuzzyEditDistance() { /** * 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. - * + * * @param defaultFuzzyEditDistance the defaultFuzzyEditDistance value to set. * @return the CustomEntity object itself. */ @@ -378,7 +377,7 @@ public CustomEntity setDefaultFuzzyEditDistance(Integer defaultFuzzyEditDistance /** * 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 @@ -389,7 +388,19 @@ public List getAliases() { /** * 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. + */ + public CustomEntity setAliases(CustomEntityAlias... aliases) { + this.aliases = (aliases == null) ? null : Arrays.asList(aliases); + return this; + } + + /** + * 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. */ @@ -423,7 +434,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CustomEntity from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CustomEntity if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -433,7 +444,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -449,10 +459,8 @@ public static CustomEntity 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 ("type".equals(fieldName)) { @@ -479,23 +487,19 @@ 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/indexes/models/CustomEntityAlias.java index d7fbfb1b7433..6239a13ca353 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/indexes/models/CustomEntityAlias.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public final class CustomEntityAlias implements JsonSerializable { + /* * The text of the alias. */ @@ -45,7 +43,7 @@ public final class CustomEntityAlias implements JsonSerializable { - boolean textFound = false; String text = null; Boolean caseSensitive = null; Boolean accentSensitive = null; @@ -163,10 +160,8 @@ public static CustomEntityAlias fromJson(JsonReader jsonReader) throws IOExcepti while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("text".equals(fieldName)) { text = reader.getString(); - textFound = true; } else if ("caseSensitive".equals(fieldName)) { caseSensitive = reader.getNullable(JsonReader::getBoolean); } else if ("accentSensitive".equals(fieldName)) { @@ -177,15 +172,11 @@ 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; - - return deserializedCustomEntityAlias; - } - throw new IllegalStateException("Missing required property: text"); + CustomEntityAlias deserializedCustomEntityAlias = new CustomEntityAlias(text); + deserializedCustomEntityAlias.caseSensitive = caseSensitive; + deserializedCustomEntityAlias.accentSensitive = accentSensitive; + deserializedCustomEntityAlias.fuzzyEditDistance = fuzzyEditDistance; + 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/indexes/models/CustomEntityLookupSkill.java index 21bedd7837db..c0b5583730c6 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/indexes/models/CustomEntityLookupSkill.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,7 +9,6 @@ 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; @@ -22,7 +19,7 @@ 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"; @@ -80,7 +77,7 @@ public CustomEntityLookupSkill(List inputs, 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. + */ + public CustomEntityLookupSkill setInlineEntitiesDefinition(CustomEntity... inlineEntitiesDefinition) { + this.inlineEntitiesDefinition + = (inlineEntitiesDefinition == null) ? null : Arrays.asList(inlineEntitiesDefinition); + return this; + } + /** * Set the inlineEntitiesDefinition property: The inline CustomEntity definition. * @@ -298,9 +307,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -317,10 +324,8 @@ public static CustomEntityLookupSkill fromJson(JsonReader jsonReader) throws IOE 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)) { @@ -345,42 +350,18 @@ 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; + return deserializedCustomEntityLookupSkill; }); } - - /** - * 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; - } } 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/indexes/models/CustomEntityLookupSkillLanguage.java index dfcfd0e8a6b3..36e214fc3a87 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/indexes/models/CustomEntityLookupSkillLanguage.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The language codes supported for input text by CustomEntityLookupSkill. */ public final class CustomEntityLookupSkillLanguage extends ExpandableStringEnum { + /** * Danish. */ @@ -70,7 +68,7 @@ public final class CustomEntityLookupSkillLanguage extends ExpandableStringEnum< /** * Creates a new instance of CustomEntityLookupSkillLanguage value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -80,7 +78,7 @@ public CustomEntityLookupSkillLanguage() { /** * Creates or finds a CustomEntityLookupSkillLanguage from its string representation. - * + * * @param name a name to look for. * @return the corresponding CustomEntityLookupSkillLanguage. */ @@ -91,7 +89,7 @@ public static CustomEntityLookupSkillLanguage fromString(String name) { /** * Gets known CustomEntityLookupSkillLanguage values. - * + * * @return known CustomEntityLookupSkillLanguage values. */ @Generated 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/indexes/models/CustomNormalizer.java index 387deb9c97ed..bdc4b0cf7c41 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/indexes/models/CustomNormalizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,6 +9,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -21,8 +19,9 @@ */ @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"; @@ -43,7 +42,7 @@ public final class CustomNormalizer extends LexicalNormalizer { /** * Creates an instance of CustomNormalizer class. - * + * * @param name the name value to set. */ @Generated @@ -52,8 +51,8 @@ public CustomNormalizer(String 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 @@ -66,7 +65,7 @@ public String getOdataType() { * 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 @@ -78,7 +77,20 @@ public List getTokenFilters() { * 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. + */ + public CustomNormalizer setTokenFilters(TokenFilterName... tokenFilters) { + this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); + return this; + } + + /** + * 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. */ @@ -92,7 +104,7 @@ public CustomNormalizer setTokenFilters(List tokenFilters) { * 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 @@ -104,7 +116,20 @@ public List getCharFilters() { * 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. + */ + public CustomNormalizer setCharFilters(CharFilterName... charFilters) { + this.charFilters = (charFilters == null) ? null : Arrays.asList(charFilters); + return this; + } + + /** + * 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. */ @@ -132,7 +157,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of CustomNormalizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of CustomNormalizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -142,7 +167,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -150,10 +174,8 @@ public static CustomNormalizer 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 ("tokenFilters".equals(fieldName)) { @@ -164,15 +186,11 @@ 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; - - return deserializedCustomNormalizer; - } - throw new IllegalStateException("Missing required property: name"); + CustomNormalizer deserializedCustomNormalizer = new CustomNormalizer(name); + deserializedCustomNormalizer.odataType = odataType; + deserializedCustomNormalizer.tokenFilters = tokenFilters; + deserializedCustomNormalizer.charFilters = charFilters; + 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/indexes/models/DataChangeDetectionPolicy.java index b815ea5f2120..29efc4134a5e 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/indexes/models/DataChangeDetectionPolicy.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @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"; @@ -33,8 +31,8 @@ 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 @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DataChangeDetectionPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DataChangeDetectionPolicy if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -66,7 +64,8 @@ public static DataChangeDetectionPolicy fromJson(JsonReader jsonReader) throws I return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -96,14 +95,12 @@ static DataChangeDetectionPolicy fromJsonKnownDiscriminator(JsonReader jsonReade while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedDataChangeDetectionPolicy.odataType = reader.getString(); } else { reader.skipChildren(); } } - return deserializedDataChangeDetectionPolicy; }); } 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/indexes/models/DataDeletionDetectionPolicy.java index 250aeb6b0c62..f4206692dae8 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/indexes/models/DataDeletionDetectionPolicy.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @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"; @@ -33,8 +31,8 @@ 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 @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DataDeletionDetectionPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DataDeletionDetectionPolicy if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -66,7 +64,8 @@ public static DataDeletionDetectionPolicy fromJson(JsonReader jsonReader) throws return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -97,14 +96,12 @@ static DataDeletionDetectionPolicy fromJsonKnownDiscriminator(JsonReader jsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedDataDeletionDetectionPolicy.odataType = reader.getString(); } else { reader.skipChildren(); } } - return deserializedDataDeletionDetectionPolicy; }); } 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/indexes/models/DataSourceCredentials.java similarity index 93% 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/indexes/models/DataSourceCredentials.java index a100e48c5dcd..8b387b6d83e2 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/indexes/models/DataSourceCredentials.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -19,6 +16,7 @@ */ @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. @@ -37,7 +35,7 @@ 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. - * + * * @return the connectionString value. */ @Generated @@ -49,7 +47,7 @@ public String getConnectionString() { * 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. - * + * * @param connectionString the connectionString value to set. * @return the DataSourceCredentials object itself. */ @@ -72,7 +70,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DataSourceCredentials from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DataSourceCredentials if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -85,14 +83,12 @@ public static DataSourceCredentials fromJson(JsonReader jsonReader) throws IOExc while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { deserializedDataSourceCredentials.connectionString = reader.getString(); } else { reader.skipChildren(); } } - return deserializedDataSourceCredentials; }); } 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/indexes/models/DefaultCognitiveServicesAccount.java index c4079cd4cc03..ed644340689d 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/indexes/models/DefaultCognitiveServicesAccount.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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"; @@ -32,9 +30,8 @@ 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 @@ -67,7 +64,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DefaultCognitiveServicesAccount from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DefaultCognitiveServicesAccount if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -81,7 +78,6 @@ public static DefaultCognitiveServicesAccount fromJson(JsonReader jsonReader) th while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("description".equals(fieldName)) { deserializedDefaultCognitiveServicesAccount.setDescription(reader.getString()); } else if ("@odata.type".equals(fieldName)) { @@ -90,7 +86,6 @@ public static DefaultCognitiveServicesAccount fromJson(JsonReader jsonReader) th reader.skipChildren(); } } - return 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/indexes/models/DictionaryDecompounderTokenFilter.java index 7a7b1cb3fcb0..4ba601736769 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/indexes/models/DictionaryDecompounderTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -20,8 +17,9 @@ */ @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"; @@ -54,11 +52,22 @@ public final class DictionaryDecompounderTokenFilter extends TokenFilter { * A value indicating whether to add only the longest matching subword to the output. Default is false. */ @Generated - private Boolean onlyLongestMatched; + private Boolean onlyLongestMatch; + + /** + * Creates an instance of DictionaryDecompounderTokenFilter class. + * + * @param name the name value to set. + * @param wordList the wordList value to set. + */ + public DictionaryDecompounderTokenFilter(String name, String... wordList) { + super(name); + this.wordList = (wordList == null) ? null : Arrays.asList(wordList); + } /** * Creates an instance of DictionaryDecompounderTokenFilter class. - * + * * @param name the name value to set. * @param wordList the wordList value to set. */ @@ -69,8 +78,8 @@ public DictionaryDecompounderTokenFilter(String name, List 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 @@ -81,7 +90,7 @@ public String getOdataType() { /** * Get the wordList property: The list of words to match against. - * + * * @return the wordList value. */ @Generated @@ -92,7 +101,7 @@ public List getWordList() { /** * Get the minWordSize property: The minimum word size. Only words longer than this get processed. Default is 5. * Maximum is 300. - * + * * @return the minWordSize value. */ @Generated @@ -103,7 +112,7 @@ public Integer getMinWordSize() { /** * Set the minWordSize property: The minimum word size. Only words longer than this get processed. Default is 5. * Maximum is 300. - * + * * @param minWordSize the minWordSize value to set. * @return the DictionaryDecompounderTokenFilter object itself. */ @@ -116,7 +125,7 @@ public DictionaryDecompounderTokenFilter setMinWordSize(Integer minWordSize) { /** * Get the minSubwordSize property: The minimum subword size. Only subwords longer than this are outputted. Default * is 2. Maximum is 300. - * + * * @return the minSubwordSize value. */ @Generated @@ -127,7 +136,7 @@ public Integer getMinSubwordSize() { /** * Set the minSubwordSize property: The minimum subword size. Only subwords longer than this are outputted. Default * is 2. Maximum is 300. - * + * * @param minSubwordSize the minSubwordSize value to set. * @return the DictionaryDecompounderTokenFilter object itself. */ @@ -140,7 +149,7 @@ public DictionaryDecompounderTokenFilter setMinSubwordSize(Integer minSubwordSiz /** * 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 @@ -151,7 +160,7 @@ public Integer getMaxSubwordSize() { /** * 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. */ @@ -162,26 +171,26 @@ public DictionaryDecompounderTokenFilter setMaxSubwordSize(Integer maxSubwordSiz } /** - * 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. */ @Generated - public Boolean isOnlyLongestMatched() { - return this.onlyLongestMatched; + 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. */ @Generated - public DictionaryDecompounderTokenFilter setOnlyLongestMatched(Boolean onlyLongestMatched) { - this.onlyLongestMatched = onlyLongestMatched; + public DictionaryDecompounderTokenFilter setOnlyLongestMatch(Boolean onlyLongestMatch) { + this.onlyLongestMatch = onlyLongestMatch; return this; } @@ -198,13 +207,13 @@ 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(); } /** * Reads an instance of DictionaryDecompounderTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DictionaryDecompounderTokenFilter if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -214,25 +223,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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)) { @@ -242,32 +246,19 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + DictionaryDecompounderTokenFilter deserializedDictionaryDecompounderTokenFilter + = new DictionaryDecompounderTokenFilter(name, wordList); + deserializedDictionaryDecompounderTokenFilter.odataType = odataType; + deserializedDictionaryDecompounderTokenFilter.minWordSize = minWordSize; + deserializedDictionaryDecompounderTokenFilter.minSubwordSize = minSubwordSize; + deserializedDictionaryDecompounderTokenFilter.maxSubwordSize = maxSubwordSize; + deserializedDictionaryDecompounderTokenFilter.onlyLongestMatch = onlyLongestMatch; + 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/indexes/models/DistanceScoringFunction.java index 9b0da1809d27..96ce75990dd8 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/indexes/models/DistanceScoringFunction.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,17 +9,15 @@ 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. */ @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"; @@ -35,7 +30,7 @@ public final class DistanceScoringFunction extends ScoringFunction { /** * Creates an instance of DistanceScoringFunction class. - * + * * @param fieldName the fieldName value to set. * @param boost the boost value to set. * @param parameters the parameters value to set. @@ -47,9 +42,8 @@ public DistanceScoringFunction(String fieldName, double boost, DistanceScoringPa } /** - * 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 @@ -60,7 +54,7 @@ public String getType() { /** * Get the parameters property: Parameter values for the distance scoring function. - * + * * @return the parameters value. */ @Generated @@ -95,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DistanceScoringFunction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DistanceScoringFunction if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -105,56 +99,33 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String jsonFieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + DistanceScoringFunction deserializedDistanceScoringFunction + = new DistanceScoringFunction(fieldName, boost, parameters); + deserializedDistanceScoringFunction.setInterpolation(interpolation); + deserializedDistanceScoringFunction.type = type; + 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/indexes/models/DistanceScoringParameters.java index 62dc6138b6dc..6534086d7977 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/indexes/models/DistanceScoringParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,14 +10,13 @@ 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. */ @Immutable public final class DistanceScoringParameters implements JsonSerializable { + /* * The name of the parameter passed in search queries to specify the reference location. */ @@ -35,7 +31,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(); reader.nextToken(); - 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/indexes/models/DocumentExtractionSkill.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentExtractionSkill.java index f399c79fcfc3..35c210dd5185 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/indexes/models/DocumentExtractionSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ 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,8 +17,9 @@ */ @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"; @@ -47,7 +44,7 @@ public final class DocumentExtractionSkill extends SearchIndexerSkill { /** * Creates an instance of DocumentExtractionSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -57,8 +54,8 @@ public DocumentExtractionSkill(List inputs, List getConfiguration() { /** * Set the configuration property: A dictionary of configurations for the skill. - * + * * @param configuration the configuration value to set. * @return the DocumentExtractionSkill object itself. */ @@ -187,7 +184,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DocumentExtractionSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DocumentExtractionSkill if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -197,9 +194,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -211,13 +206,10 @@ public static DocumentExtractionSkill 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)) { @@ -236,29 +228,15 @@ public static DocumentExtractionSkill fromJson(JsonReader jsonReader) throws IOE 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/indexes/models/DocumentIntelligenceLayoutSkill.java index b3d10991cd9f..edbde7785fcd 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/indexes/models/DocumentIntelligenceLayoutSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -21,14 +18,15 @@ */ @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 format. Default is 'markdown'. + * Controls the output format. Default is 'markdown'. */ @Generated private DocumentIntelligenceLayoutSkillOutputFormat outputFormat; @@ -46,7 +44,7 @@ public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { private DocumentIntelligenceLayoutSkillMarkdownHeaderDepth markdownHeaderDepth; /* - * Controls the cardinality of the content extracted from the document by the skill + * Controls the cardinality of the content extracted from the document by the skill. */ @Generated private List extractionOptions; @@ -59,7 +57,7 @@ public final class DocumentIntelligenceLayoutSkill extends SearchIndexerSkill { /** * Creates an instance of DocumentIntelligenceLayoutSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -69,8 +67,8 @@ public DocumentIntelligenceLayoutSkill(List inputs, List } /** - * 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 @@ -80,8 +78,8 @@ public String getOdataType() { } /** - * Get the outputFormat property: Controls the cardinality of the output format. Default is 'markdown'. - * + * Get the outputFormat property: Controls the output format. Default is 'markdown'. + * * @return the outputFormat value. */ @Generated @@ -90,8 +88,8 @@ public DocumentIntelligenceLayoutSkillOutputFormat getOutputFormat() { } /** - * Set the outputFormat property: Controls the cardinality of the output format. Default is 'markdown'. - * + * Set the outputFormat property: Controls the output format. Default is 'markdown'. + * * @param outputFormat the outputFormat value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ @@ -104,7 +102,7 @@ public DocumentIntelligenceLayoutSkill setOutputFormat(DocumentIntelligenceLayou /** * Get the outputMode property: Controls the cardinality of the output produced by the skill. Default is * 'oneToMany'. - * + * * @return the outputMode value. */ @Generated @@ -115,7 +113,7 @@ public DocumentIntelligenceLayoutSkillOutputMode getOutputMode() { /** * Set the outputMode property: Controls the cardinality of the output produced by the skill. Default is * 'oneToMany'. - * + * * @param outputMode the outputMode value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ @@ -127,7 +125,7 @@ public DocumentIntelligenceLayoutSkill setOutputMode(DocumentIntelligenceLayoutS /** * Get the markdownHeaderDepth property: The depth of headers in the markdown output. Default is h6. - * + * * @return the markdownHeaderDepth value. */ @Generated @@ -137,7 +135,7 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth getMarkdownHeaderDepth /** * Set the markdownHeaderDepth property: The depth of headers in the markdown output. Default is h6. - * + * * @param markdownHeaderDepth the markdownHeaderDepth value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ @@ -151,7 +149,7 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth getMarkdownHeaderDepth /** * Get the extractionOptions property: Controls the cardinality of the content extracted from the document by the * skill. - * + * * @return the extractionOptions value. */ @Generated @@ -162,7 +160,20 @@ public List getExtractionOptio /** * Set the extractionOptions property: Controls the cardinality of the content extracted from the document by the * skill. - * + * + * @param extractionOptions the extractionOptions value to set. + * @return the DocumentIntelligenceLayoutSkill object itself. + */ + public DocumentIntelligenceLayoutSkill + setExtractionOptions(DocumentIntelligenceLayoutSkillExtractionOptions... extractionOptions) { + this.extractionOptions = (extractionOptions == null) ? null : Arrays.asList(extractionOptions); + return this; + } + + /** + * Set the extractionOptions property: Controls the cardinality of the content extracted from the document by the + * skill. + * * @param extractionOptions the extractionOptions value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ @@ -175,7 +186,7 @@ public List getExtractionOptio /** * Get the chunkingProperties property: Controls the cardinality for chunking the content. - * + * * @return the chunkingProperties value. */ @Generated @@ -185,7 +196,7 @@ public DocumentIntelligenceLayoutSkillChunkingProperties getChunkingProperties() /** * Set the chunkingProperties property: Controls the cardinality for chunking the content. - * + * * @param chunkingProperties the chunkingProperties value to set. * @return the DocumentIntelligenceLayoutSkill object itself. */ @@ -251,7 +262,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DocumentIntelligenceLayoutSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DocumentIntelligenceLayoutSkill if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -261,9 +272,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -277,13 +286,10 @@ public static DocumentIntelligenceLayoutSkill fromJson(JsonReader jsonReader) th 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)) { @@ -308,31 +314,18 @@ 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.outputFormat = outputFormat; - deserializedDocumentIntelligenceLayoutSkill.outputMode = outputMode; - deserializedDocumentIntelligenceLayoutSkill.markdownHeaderDepth = markdownHeaderDepth; - deserializedDocumentIntelligenceLayoutSkill.extractionOptions = extractionOptions; - deserializedDocumentIntelligenceLayoutSkill.chunkingProperties = chunkingProperties; - - 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.outputFormat = outputFormat; + deserializedDocumentIntelligenceLayoutSkill.outputMode = outputMode; + deserializedDocumentIntelligenceLayoutSkill.markdownHeaderDepth = markdownHeaderDepth; + deserializedDocumentIntelligenceLayoutSkill.extractionOptions = extractionOptions; + deserializedDocumentIntelligenceLayoutSkill.chunkingProperties = chunkingProperties; + return deserializedDocumentIntelligenceLayoutSkill; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java index d652242d7fc8..a2910e2123ba 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,6 +17,7 @@ @Fluent public final class DocumentIntelligenceLayoutSkillChunkingProperties implements JsonSerializable { + /* * The unit of the chunk. */ @@ -47,7 +45,7 @@ public DocumentIntelligenceLayoutSkillChunkingProperties() { /** * Get the unit property: The unit of the chunk. - * + * * @return the unit value. */ @Generated @@ -57,7 +55,7 @@ public DocumentIntelligenceLayoutSkillChunkingUnit getUnit() { /** * Set the unit property: The unit of the chunk. - * + * * @param unit the unit value to set. * @return the DocumentIntelligenceLayoutSkillChunkingProperties object itself. */ @@ -69,7 +67,7 @@ public DocumentIntelligenceLayoutSkillChunkingProperties setUnit(DocumentIntelli /** * Get the maximumLength property: The maximum chunk length in characters. Default is 500. - * + * * @return the maximumLength value. */ @Generated @@ -79,7 +77,7 @@ public Integer getMaximumLength() { /** * Set the maximumLength property: The maximum chunk length in characters. Default is 500. - * + * * @param maximumLength the maximumLength value to set. * @return the DocumentIntelligenceLayoutSkillChunkingProperties object itself. */ @@ -91,7 +89,7 @@ public DocumentIntelligenceLayoutSkillChunkingProperties setMaximumLength(Intege /** * Get the overlapLength property: The length of overlap provided between two text chunks. Default is 0. - * + * * @return the overlapLength value. */ @Generated @@ -101,7 +99,7 @@ public Integer getOverlapLength() { /** * Set the overlapLength property: The length of overlap provided between two text chunks. Default is 0. - * + * * @param overlapLength the overlapLength value to set. * @return the DocumentIntelligenceLayoutSkillChunkingProperties object itself. */ @@ -126,7 +124,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DocumentIntelligenceLayoutSkillChunkingProperties from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DocumentIntelligenceLayoutSkillChunkingProperties if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -140,7 +138,6 @@ public static DocumentIntelligenceLayoutSkillChunkingProperties fromJson(JsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("unit".equals(fieldName)) { deserializedDocumentIntelligenceLayoutSkillChunkingProperties.unit = DocumentIntelligenceLayoutSkillChunkingUnit.fromString(reader.getString()); @@ -154,7 +151,6 @@ public static DocumentIntelligenceLayoutSkillChunkingProperties fromJson(JsonRea reader.skipChildren(); } } - return deserializedDocumentIntelligenceLayoutSkillChunkingProperties; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java index 2d468292ecd7..03c685b12eea 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class DocumentIntelligenceLayoutSkillChunkingUnit extends ExpandableStringEnum { + /** * Specifies chunk by characters. */ @@ -23,7 +21,7 @@ public final class DocumentIntelligenceLayoutSkillChunkingUnit /** * Creates a new instance of DocumentIntelligenceLayoutSkillChunkingUnit value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -33,7 +31,7 @@ public DocumentIntelligenceLayoutSkillChunkingUnit() { /** * Creates or finds a DocumentIntelligenceLayoutSkillChunkingUnit from its string representation. - * + * * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillChunkingUnit. */ @@ -44,7 +42,7 @@ public static DocumentIntelligenceLayoutSkillChunkingUnit fromString(String name /** * Gets known DocumentIntelligenceLayoutSkillChunkingUnit values. - * + * * @return known DocumentIntelligenceLayoutSkillChunkingUnit values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java index 4b8ab380f9fb..3b0cfd65458b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class DocumentIntelligenceLayoutSkillExtractionOptions extends ExpandableStringEnum { + /** * Specify that image content should be extracted from the document. */ @@ -30,7 +28,7 @@ public final class DocumentIntelligenceLayoutSkillExtractionOptions /** * Creates a new instance of DocumentIntelligenceLayoutSkillExtractionOptions value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -40,7 +38,7 @@ public DocumentIntelligenceLayoutSkillExtractionOptions() { /** * Creates or finds a DocumentIntelligenceLayoutSkillExtractionOptions from its string representation. - * + * * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillExtractionOptions. */ @@ -51,7 +49,7 @@ public static DocumentIntelligenceLayoutSkillExtractionOptions fromString(String /** * Gets known DocumentIntelligenceLayoutSkillExtractionOptions values. - * + * * @return known DocumentIntelligenceLayoutSkillExtractionOptions values. */ @Generated 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/indexes/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java index 89fbf7e0e0d1..fb3c919f5a9c 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/indexes/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth extends ExpandableStringEnum { + /** * Header level 1. */ @@ -53,7 +51,7 @@ public final class DocumentIntelligenceLayoutSkillMarkdownHeaderDepth /** * Creates a new instance of DocumentIntelligenceLayoutSkillMarkdownHeaderDepth value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -63,7 +61,7 @@ public DocumentIntelligenceLayoutSkillMarkdownHeaderDepth() { /** * Creates or finds a DocumentIntelligenceLayoutSkillMarkdownHeaderDepth from its string representation. - * + * * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillMarkdownHeaderDepth. */ @@ -74,7 +72,7 @@ public static DocumentIntelligenceLayoutSkillMarkdownHeaderDepth fromString(Stri /** * Gets known DocumentIntelligenceLayoutSkillMarkdownHeaderDepth values. - * + * * @return known DocumentIntelligenceLayoutSkillMarkdownHeaderDepth values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java index 54b24087f9fd..23c6a1222d38 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class DocumentIntelligenceLayoutSkillOutputFormat extends ExpandableStringEnum { + /** * Specify the format of the output as text. */ @@ -29,7 +27,7 @@ public final class DocumentIntelligenceLayoutSkillOutputFormat /** * Creates a new instance of DocumentIntelligenceLayoutSkillOutputFormat value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -39,7 +37,7 @@ public DocumentIntelligenceLayoutSkillOutputFormat() { /** * Creates or finds a DocumentIntelligenceLayoutSkillOutputFormat from its string representation. - * + * * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillOutputFormat. */ @@ -50,7 +48,7 @@ public static DocumentIntelligenceLayoutSkillOutputFormat fromString(String name /** * Gets known DocumentIntelligenceLayoutSkillOutputFormat values. - * + * * @return known DocumentIntelligenceLayoutSkillOutputFormat values. */ @Generated 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/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java index f1666db2c7de..6e4e4e7e5001 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/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class DocumentIntelligenceLayoutSkillOutputMode extends ExpandableStringEnum { + /** * Specify that the output should be parsed as 'oneToMany'. */ @@ -23,7 +21,7 @@ public final class DocumentIntelligenceLayoutSkillOutputMode /** * Creates a new instance of DocumentIntelligenceLayoutSkillOutputMode value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -33,7 +31,7 @@ public DocumentIntelligenceLayoutSkillOutputMode() { /** * Creates or finds a DocumentIntelligenceLayoutSkillOutputMode from its string representation. - * + * * @param name a name to look for. * @return the corresponding DocumentIntelligenceLayoutSkillOutputMode. */ @@ -44,7 +42,7 @@ public static DocumentIntelligenceLayoutSkillOutputMode fromString(String name) /** * Gets known DocumentIntelligenceLayoutSkillOutputMode values. - * + * * @return known DocumentIntelligenceLayoutSkillOutputMode values. */ @Generated 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/indexes/models/DocumentKeysOrIds.java similarity index 79% 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/indexes/models/DocumentKeysOrIds.java index be05c85fcf6f..524b81bd1fea 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/indexes/models/DocumentKeysOrIds.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -13,13 +10,15 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** - * The DocumentKeysOrIds model. + * The type of the keysOrIds. */ @Fluent public final class DocumentKeysOrIds implements JsonSerializable { + /* * document keys to be reset */ @@ -41,7 +40,7 @@ public DocumentKeysOrIds() { /** * Get the documentKeys property: document keys to be reset. - * + * * @return the documentKeys value. */ @Generated @@ -51,7 +50,18 @@ public List getDocumentKeys() { /** * Set the documentKeys property: document keys to be reset. - * + * + * @param documentKeys the documentKeys value to set. + * @return the DocumentKeysOrIds object itself. + */ + public DocumentKeysOrIds setDocumentKeys(String... documentKeys) { + this.documentKeys = (documentKeys == null) ? null : Arrays.asList(documentKeys); + return this; + } + + /** + * Set the documentKeys property: document keys to be reset. + * * @param documentKeys the documentKeys value to set. * @return the DocumentKeysOrIds object itself. */ @@ -63,7 +73,7 @@ public DocumentKeysOrIds setDocumentKeys(List documentKeys) { /** * Get the datasourceDocumentIds property: datasource document identifiers to be reset. - * + * * @return the datasourceDocumentIds value. */ @Generated @@ -73,7 +83,18 @@ public List getDatasourceDocumentIds() { /** * Set the datasourceDocumentIds property: datasource document identifiers to be reset. - * + * + * @param datasourceDocumentIds the datasourceDocumentIds value to set. + * @return the DocumentKeysOrIds object itself. + */ + public DocumentKeysOrIds setDatasourceDocumentIds(String... datasourceDocumentIds) { + this.datasourceDocumentIds = (datasourceDocumentIds == null) ? null : Arrays.asList(datasourceDocumentIds); + return this; + } + + /** + * Set the datasourceDocumentIds property: datasource document identifiers to be reset. + * * @param datasourceDocumentIds the datasourceDocumentIds value to set. * @return the DocumentKeysOrIds object itself. */ @@ -98,7 +119,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DocumentKeysOrIds from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DocumentKeysOrIds if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -111,7 +132,6 @@ public static DocumentKeysOrIds fromJson(JsonReader jsonReader) throws IOExcepti while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("documentKeys".equals(fieldName)) { List documentKeys = reader.readArray(reader1 -> reader1.getString()); deserializedDocumentKeysOrIds.documentKeys = documentKeys; @@ -122,7 +142,6 @@ public static DocumentKeysOrIds fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedDocumentKeysOrIds; }); } 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 index 3a51ce77df99..648345df1a9d 100644 --- 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 @@ -1,73 +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.indexes.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.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. + * 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 EdgeNGramTokenFilter extends TokenFilter { - private final EdgeNGramTokenFilterV1 v1Filter; - private final EdgeNGramTokenFilterV2 v2Filter; - EdgeNGramTokenFilter(EdgeNGramTokenFilterV1 v1Filter) { - super(v1Filter.getName()); + /* + * The discriminator for derived types. + */ + @Generated + private String odataType = "#Microsoft.Azure.Search.EdgeNGramTokenFilter"; - this.v1Filter = v1Filter; - this.v2Filter = null; - } + /* + * The minimum n-gram length. Default is 1. Must be less than the value of maxGram. + */ + @Generated + private Integer minGram; - EdgeNGramTokenFilter(EdgeNGramTokenFilterV2 v2Filter) { - super(v2Filter.getName()); + /* + * The maximum n-gram length. Default is 2. + */ + @Generated + private Integer maxGram; - this.v1Filter = null; - this.v2Filter = v2Filter; - } + /* + * Specifies which side of the input the n-gram should be generated from. Default is "front". + */ + @Generated + private EdgeNGramTokenFilterSide side; /** - * Constructor of {@link TokenFilter}. + * Creates an instance of EdgeNGramTokenFilter class. * - * @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. + * @param name the name value to set. */ + @Generated public EdgeNGramTokenFilter(String name) { super(name); + } - this.v1Filter = null; - this.v2Filter = new EdgeNGramTokenFilterV2(name); + /** + * 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. Must - * be less than the value of maxGram. + * Get the minGram property: The minimum n-gram length. Default is 1. Must be less than the value of maxGram. * * @return the minGram value. */ + @Generated public Integer getMinGram() { - return (v1Filter != null) ? v1Filter.getMinGram() : v2Filter.getMinGram(); + return this.minGram; } /** - * Set the minGram property: The minimum n-gram length. Default is 1. Must - * be less than the value of maxGram. + * 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. */ + @Generated public EdgeNGramTokenFilter setMinGram(Integer minGram) { - if (v1Filter != null) { - v1Filter.setMinGram(minGram); - } else { - v2Filter.setMinGram(minGram); - } + this.minGram = minGram; return this; } @@ -76,8 +89,9 @@ public EdgeNGramTokenFilter setMinGram(Integer minGram) { * * @return the maxGram value. */ + @Generated public Integer getMaxGram() { - return (v1Filter != null) ? v1Filter.getMaxGram() : v2Filter.getMaxGram(); + return this.maxGram; } /** @@ -86,45 +100,89 @@ public Integer getMaxGram() { * @param maxGram the maxGram value to set. * @return the EdgeNGramTokenFilter object itself. */ + @Generated public EdgeNGramTokenFilter setMaxGram(Integer maxGram) { - if (v1Filter != null) { - v1Filter.setMaxGram(maxGram); - } else { - v2Filter.setMaxGram(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". Possible values include: - * 'Front', 'Back'. + * 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 (v1Filter != null) ? v1Filter.getSide() : v2Filter.getSide(); + return this.side; } /** - * 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'. + * 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 EdgeNGramTokenFilter object itself. */ + @Generated public EdgeNGramTokenFilter setSide(EdgeNGramTokenFilterSide side) { - if (v1Filter != null) { - v1Filter.setSide(side); - } else { - v2Filter.setSide(side); - } + this.side = side; return this; } + /** + * {@inheritDoc} + */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Filter != null) ? v1Filter.toJson(jsonWriter) : v2Filter.toJson(jsonWriter); + 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 EdgeNGramTokenFilter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of EdgeNGramTokenFilter 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 EdgeNGramTokenFilter. + */ + @Generated + public static EdgeNGramTokenFilter fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + 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(); + } 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(); + } + } + EdgeNGramTokenFilter deserializedEdgeNGramTokenFilter = new EdgeNGramTokenFilter(name); + deserializedEdgeNGramTokenFilter.odataType = odataType; + deserializedEdgeNGramTokenFilter.minGram = minGram; + deserializedEdgeNGramTokenFilter.maxGram = maxGram; + deserializedEdgeNGramTokenFilter.side = side; + return deserializedEdgeNGramTokenFilter; + }); } } 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 index f4bc300842f4..809bbb79120b 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/EdgeNGramTokenFilterV2.java similarity index 82% 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/indexes/models/EdgeNGramTokenFilterV2.java index b6421c172e07..bc00799fb5e2 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/indexes/models/EdgeNGramTokenFilterV2.java @@ -1,18 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.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; /** @@ -21,8 +16,9 @@ */ @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"; @@ -47,7 +43,7 @@ public final class EdgeNGramTokenFilterV2 extends TokenFilter { /** * Creates an instance of EdgeNGramTokenFilterV2 class. - * + * * @param name the name value to set. */ @Generated @@ -56,8 +52,8 @@ public EdgeNGramTokenFilterV2(String 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 @@ -69,7 +65,7 @@ public String getOdataType() { /** * 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 @@ -80,7 +76,7 @@ public Integer getMinGram() { /** * 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. */ @@ -92,7 +88,7 @@ public EdgeNGramTokenFilterV2 setMinGram(Integer minGram) { /** * Get the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @return the maxGram value. */ @Generated @@ -102,7 +98,7 @@ public Integer getMaxGram() { /** * Set the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @param maxGram the maxGram value to set. * @return the EdgeNGramTokenFilterV2 object itself. */ @@ -114,7 +110,7 @@ public EdgeNGramTokenFilterV2 setMaxGram(Integer maxGram) { /** * 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 @@ -124,7 +120,7 @@ public EdgeNGramTokenFilterSide getSide() { /** * 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. */ @@ -151,7 +147,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of EdgeNGramTokenFilterV2 from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of EdgeNGramTokenFilterV2 if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -161,7 +157,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -170,10 +165,8 @@ public static EdgeNGramTokenFilterV2 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 ("minGram".equals(fieldName)) { @@ -186,16 +179,12 @@ 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/indexes/models/EdgeNGramTokenizer.java index be1b51e06e11..fcc3e94ca147 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/indexes/models/EdgeNGramTokenizer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,7 +20,7 @@ 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"; @@ -56,7 +54,7 @@ public EdgeNGramTokenizer(String 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. */ @@ -122,6 +120,17 @@ 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. + */ + public EdgeNGramTokenizer setTokenChars(TokenCharacterKind... tokenChars) { + this.tokenChars = (tokenChars == null) ? null : Arrays.asList(tokenChars); + return this; + } + /** * Set the tokenChars property: Character classes to keep in the tokens. * @@ -162,7 +171,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -173,7 +181,6 @@ public static EdgeNGramTokenizer fromJson(JsonReader jsonReader) throws IOExcept 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)) { @@ -186,26 +193,12 @@ 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; + return deserializedEdgeNGramTokenizer; }); } - - /** - * 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; - } } 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/indexes/models/ElisionTokenFilter.java index 70b0a0ac8cbd..2820a213ec78 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/indexes/models/ElisionTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,7 +20,7 @@ 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"; @@ -44,7 +42,7 @@ public ElisionTokenFilter(String 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. */ @@ -64,6 +62,17 @@ 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. + */ + public ElisionTokenFilter setArticles(String... articles) { + this.articles = (articles == null) ? null : Arrays.asList(articles); + return this; + } + /** * Set the articles property: The set of articles to remove. * @@ -101,7 +110,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -110,7 +118,6 @@ public static ElisionTokenFilter fromJson(JsonReader jsonReader) throws IOExcept 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)) { @@ -119,24 +126,10 @@ 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; + return deserializedElisionTokenFilter; }); } - - /** - * 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; - } } 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/indexes/models/EntityCategory.java deleted file mode 100644 index 107e50ab8f78..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityCategory.java +++ /dev/null @@ -1,89 +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.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * A string indicating what entity categories to return. - */ -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"); - - /** - * Creates a new instance of EntityCategory value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public EntityCategory() { - } - - /** - * Creates or finds a EntityCategory from its string representation. - * - * @param name a name to look for. - * @return the corresponding EntityCategory. - */ - @Generated - public static EntityCategory fromString(String name) { - return fromString(name, EntityCategory.class); - } - - /** - * Gets known EntityCategory values. - * - * @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/indexes/models/EntityLinkingSkill.java index 1d7b77b958a6..cd169241f55b 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/indexes/models/EntityLinkingSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,8 +16,9 @@ */ @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"; @@ -48,7 +45,7 @@ public final class EntityLinkingSkill extends SearchIndexerSkill { /** * Creates an instance of EntityLinkingSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -58,8 +55,8 @@ public EntityLinkingSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -217,13 +212,10 @@ public static EntityLinkingSkill 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)) { @@ -242,28 +234,15 @@ 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/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/EntityRecognitionSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillLanguage.java deleted file mode 100644 index d5d444c829e4..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillLanguage.java +++ /dev/null @@ -1,185 +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.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * 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"); - - /** - * Creates a new instance of EntityRecognitionSkillLanguage value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public EntityRecognitionSkillLanguage() { - } - - /** - * Creates or finds a EntityRecognitionSkillLanguage from its string representation. - * - * @param name a name to look for. - * @return the corresponding EntityRecognitionSkillLanguage. - */ - @Generated - public static EntityRecognitionSkillLanguage fromString(String name) { - return fromString(name, EntityRecognitionSkillLanguage.class); - } - - /** - * Gets known EntityRecognitionSkillLanguage values. - * - * @return known EntityRecognitionSkillLanguage values. - */ - @Generated - public static Collection 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/indexes/models/EntityRecognitionSkillV3.java similarity index 81% 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/indexes/models/EntityRecognitionSkillV3.java index 22a9a0d68c50..7099e09db30a 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/indexes/models/EntityRecognitionSkillV3.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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.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.Arrays; import java.util.List; /** @@ -23,8 +17,9 @@ */ @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"; @@ -57,7 +52,7 @@ public final class EntityRecognitionSkillV3 extends SearchIndexerSkill { /** * Creates an instance of EntityRecognitionSkillV3 class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -67,8 +62,8 @@ public EntityRecognitionSkillV3(List inputs, List getCategories() { /** * Set the categories property: A list of entity categories that should be extracted. - * + * + * @param categories the categories value to set. + * @return the EntityRecognitionSkillV3 object itself. + */ + public EntityRecognitionSkillV3 setCategories(String... categories) { + this.categories = (categories == null) ? null : Arrays.asList(categories); + return this; + } + + /** + * Set the categories property: A list of entity categories that should be extracted. + * * @param categories the categories value to set. * @return the EntityRecognitionSkillV3 object itself. */ @@ -101,7 +107,7 @@ public EntityRecognitionSkillV3 setCategories(List categories) { /** * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @return the defaultLanguageCode value. */ @Generated @@ -111,7 +117,7 @@ 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 EntityRecognitionSkillV3 object itself. */ @@ -125,7 +131,7 @@ 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. - * + * * @return the minimumPrecision value. */ @Generated @@ -137,7 +143,7 @@ public Double 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 EntityRecognitionSkillV3 object itself. */ @@ -151,7 +157,7 @@ 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. - * + * * @return the modelVersion value. */ @Generated @@ -163,7 +169,7 @@ public String getModelVersion() { * 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. - * + * * @param modelVersion the modelVersion value to set. * @return the EntityRecognitionSkillV3 object itself. */ @@ -225,7 +231,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of EntityRecognitionSkillV3 from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of EntityRecognitionSkillV3 if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -235,9 +241,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -250,13 +254,10 @@ public static EntityRecognitionSkillV3 fromJson(JsonReader jsonReader) throws IO 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)) { @@ -277,30 +278,17 @@ 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; - - 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)); + 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; }); } } 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/ExhaustiveKnnAlgorithmConfiguration.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnAlgorithmConfiguration.java index fec1c15a5523..54a13603d6c2 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/indexes/models/ExhaustiveKnnAlgorithmConfiguration.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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; @@ -33,7 +31,7 @@ public final class ExhaustiveKnnAlgorithmConfiguration extends VectorSearchAlgor /** * Creates an instance of ExhaustiveKnnAlgorithmConfiguration class. - * + * * @param name the name value to set. */ @Generated @@ -42,8 +40,8 @@ public ExhaustiveKnnAlgorithmConfiguration(String 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 @@ -54,7 +52,7 @@ public VectorSearchAlgorithmKind getKind() { /** * Get the parameters property: Contains the parameters specific to exhaustive KNN algorithm. - * + * * @return the parameters value. */ @Generated @@ -64,7 +62,7 @@ public ExhaustiveKnnParameters getParameters() { /** * Set the parameters property: Contains the parameters specific to exhaustive KNN algorithm. - * + * * @param parameters the parameters value to set. * @return the ExhaustiveKnnAlgorithmConfiguration object itself. */ @@ -89,7 +87,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ExhaustiveKnnAlgorithmConfiguration from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ExhaustiveKnnAlgorithmConfiguration if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -99,17 +97,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchAlgorithmKind.fromString(reader.getString()); } else if ("exhaustiveKnnParameters".equals(fieldName)) { @@ -118,15 +113,11 @@ public static ExhaustiveKnnAlgorithmConfiguration fromJson(JsonReader jsonReader reader.skipChildren(); } } - if (nameFound) { - ExhaustiveKnnAlgorithmConfiguration deserializedExhaustiveKnnAlgorithmConfiguration - = new ExhaustiveKnnAlgorithmConfiguration(name); - deserializedExhaustiveKnnAlgorithmConfiguration.kind = kind; - deserializedExhaustiveKnnAlgorithmConfiguration.parameters = parameters; - - return deserializedExhaustiveKnnAlgorithmConfiguration; - } - throw new IllegalStateException("Missing required property: name"); + ExhaustiveKnnAlgorithmConfiguration deserializedExhaustiveKnnAlgorithmConfiguration + = new ExhaustiveKnnAlgorithmConfiguration(name); + deserializedExhaustiveKnnAlgorithmConfiguration.kind = kind; + deserializedExhaustiveKnnAlgorithmConfiguration.parameters = parameters; + 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/indexes/models/ExhaustiveKnnParameters.java index ab5cca14a990..31a9f55fc60a 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/indexes/models/ExhaustiveKnnParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public final class ExhaustiveKnnParameters implements JsonSerializable { + /* * The similarity metric to use for vector comparisons. */ @@ -34,7 +32,7 @@ public ExhaustiveKnnParameters() { /** * Get the metric property: The similarity metric to use for vector comparisons. - * + * * @return the metric value. */ @Generated @@ -44,7 +42,7 @@ public VectorSearchAlgorithmMetric getMetric() { /** * Set the metric property: The similarity metric to use for vector comparisons. - * + * * @param metric the metric value to set. * @return the ExhaustiveKnnParameters object itself. */ @@ -67,7 +65,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ExhaustiveKnnParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ExhaustiveKnnParameters if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -80,7 +78,6 @@ public static ExhaustiveKnnParameters fromJson(JsonReader jsonReader) throws IOE while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("metric".equals(fieldName)) { deserializedExhaustiveKnnParameters.metric = VectorSearchAlgorithmMetric.fromString(reader.getString()); @@ -88,7 +85,6 @@ public static ExhaustiveKnnParameters fromJson(JsonReader jsonReader) throws IOE reader.skipChildren(); } } - return deserializedExhaustiveKnnParameters; }); } 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/FieldMapping.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/FieldMapping.java index 85e21f5e9cc4..1b94c3277135 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/indexes/models/FieldMapping.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public final class FieldMapping implements JsonSerializable { + /* * The name of the field in the data source. */ @@ -39,7 +37,7 @@ public final class FieldMapping implements JsonSerializable { /** * Creates an instance of FieldMapping class. - * + * * @param sourceFieldName the sourceFieldName value to set. */ @Generated @@ -49,7 +47,7 @@ public FieldMapping(String sourceFieldName) { /** * Get the sourceFieldName property: The name of the field in the data source. - * + * * @return the sourceFieldName value. */ @Generated @@ -60,7 +58,7 @@ public String getSourceFieldName() { /** * Get the targetFieldName property: The name of the target field in the index. Same as the source field name by * default. - * + * * @return the targetFieldName value. */ @Generated @@ -71,7 +69,7 @@ public String getTargetFieldName() { /** * Set the targetFieldName property: The name of the target field in the index. Same as the source field name by * default. - * + * * @param targetFieldName the targetFieldName value to set. * @return the FieldMapping object itself. */ @@ -83,7 +81,7 @@ public FieldMapping setTargetFieldName(String targetFieldName) { /** * Get the mappingFunction property: A function to apply to each source field value before indexing. - * + * * @return the mappingFunction value. */ @Generated @@ -93,7 +91,7 @@ public FieldMappingFunction getMappingFunction() { /** * Set the mappingFunction property: A function to apply to each source field value before indexing. - * + * * @param mappingFunction the mappingFunction value to set. * @return the FieldMapping object itself. */ @@ -118,7 +116,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of FieldMapping from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of FieldMapping if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -128,17 +126,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("sourceFieldName".equals(fieldName)) { sourceFieldName = reader.getString(); - sourceFieldNameFound = true; } else if ("targetFieldName".equals(fieldName)) { targetFieldName = reader.getString(); } else if ("mappingFunction".equals(fieldName)) { @@ -147,14 +142,10 @@ public static FieldMapping fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (sourceFieldNameFound) { - FieldMapping deserializedFieldMapping = new FieldMapping(sourceFieldName); - deserializedFieldMapping.targetFieldName = targetFieldName; - deserializedFieldMapping.mappingFunction = mappingFunction; - - return deserializedFieldMapping; - } - throw new IllegalStateException("Missing required property: sourceFieldName"); + FieldMapping deserializedFieldMapping = new FieldMapping(sourceFieldName); + deserializedFieldMapping.targetFieldName = targetFieldName; + deserializedFieldMapping.mappingFunction = mappingFunction; + 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/indexes/models/FieldMappingFunction.java index 7fe46dd96959..4af6222f3339 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/indexes/models/FieldMappingFunction.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,6 +17,7 @@ */ @Fluent public final class FieldMappingFunction implements JsonSerializable { + /* * The name of the field mapping function. */ @@ -34,7 +32,7 @@ public final class FieldMappingFunction implements JsonSerializable getParameters() { /** * 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. */ @@ -90,7 +88,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of FieldMappingFunction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of FieldMappingFunction if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -100,29 +98,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static FieldMappingFunction fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = 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()); } else { reader.skipChildren(); } } - if (nameFound) { - FieldMappingFunction deserializedFieldMappingFunction = new FieldMappingFunction(name); - deserializedFieldMappingFunction.parameters = parameters; - - return deserializedFieldMappingFunction; - } - throw new IllegalStateException("Missing required property: name"); + FieldMappingFunction deserializedFieldMappingFunction = new FieldMappingFunction(name); + deserializedFieldMappingFunction.parameters = parameters; + 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/indexes/models/FreshnessScoringFunction.java index c37bba4b2c70..dc9af5eca4de 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/indexes/models/FreshnessScoringFunction.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,17 +9,15 @@ 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. */ @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"; @@ -35,7 +30,7 @@ public final class FreshnessScoringFunction extends ScoringFunction { /** * Creates an instance of FreshnessScoringFunction class. - * + * * @param fieldName the fieldName value to set. * @param boost the boost value to set. * @param parameters the parameters value to set. @@ -47,9 +42,8 @@ public FreshnessScoringFunction(String fieldName, double boost, FreshnessScoring } /** - * 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 @@ -60,7 +54,7 @@ public String getType() { /** * Get the parameters property: Parameter values for the freshness scoring function. - * + * * @return the parameters value. */ @Generated @@ -95,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of FreshnessScoringFunction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of FreshnessScoringFunction if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -105,56 +99,33 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String jsonFieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + FreshnessScoringFunction deserializedFreshnessScoringFunction + = new FreshnessScoringFunction(fieldName, boost, parameters); + deserializedFreshnessScoringFunction.setInterpolation(interpolation); + deserializedFreshnessScoringFunction.type = type; + 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/indexes/models/FreshnessScoringParameters.java index 3b212d614b36..5c6d1e8b6f9c 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/indexes/models/FreshnessScoringParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -21,6 +18,7 @@ */ @Immutable public final class FreshnessScoringParameters implements JsonSerializable { + /* * The expiration period after which boosting will stop for a particular document. */ @@ -29,7 +27,7 @@ public final class FreshnessScoringParameters implements JsonSerializable { - boolean boostingDurationFound = false; Duration boostingDuration = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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/indexes/models/GetIndexStatisticsResult.java similarity index 51% 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/indexes/models/GetIndexStatisticsResult.java index 0b772e1fc55b..c7a0d4e840c4 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/indexes/models/GetIndexStatisticsResult.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,47 +10,41 @@ 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. */ @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; + private long documentCount; /* * The amount of storage in bytes consumed by the index. */ @Generated - private final long storageSize; + private long storageSize; /* * The amount of memory in bytes consumed by vectors in the index. */ @Generated - private Long vectorIndexSize; + private long vectorIndexSize; /** - * Creates an instance of SearchIndexStatistics class. - * - * @param documentCount the documentCount value to set. - * @param storageSize the storageSize value to set. + * Creates an instance of GetIndexStatisticsResult class. */ @Generated - public SearchIndexStatistics(long documentCount, long storageSize) { - this.documentCount = documentCount; - this.storageSize = storageSize; + public GetIndexStatisticsResult() { } /** * Get the documentCount property: The number of documents in the index. - * + * * @return the documentCount value. */ @Generated @@ -63,7 +54,7 @@ public long getDocumentCount() { /** * Get the storageSize property: The amount of storage in bytes consumed by the index. - * + * * @return the storageSize value. */ @Generated @@ -73,11 +64,11 @@ public long getStorageSize() { /** * Get the vectorIndexSize property: The amount of memory in bytes consumed by vectors in the index. - * + * * @return the vectorIndexSize value. */ @Generated - public Long getVectorIndexSize() { + public long getVectorIndexSize() { return this.vectorIndexSize; } @@ -92,55 +83,32 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * 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. */ @Generated - public static SearchIndexStatistics fromJson(JsonReader jsonReader) throws IOException { + 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; + GetIndexStatisticsResult deserializedGetIndexStatisticsResult = new GetIndexStatisticsResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("documentCount".equals(fieldName)) { - documentCount = reader.getLong(); - documentCountFound = true; + deserializedGetIndexStatisticsResult.documentCount = reader.getLong(); } else if ("storageSize".equals(fieldName)) { - storageSize = reader.getLong(); - storageSizeFound = true; + deserializedGetIndexStatisticsResult.storageSize = reader.getLong(); } else if ("vectorIndexSize".equals(fieldName)) { - vectorIndexSize = reader.getNullable(JsonReader::getLong); + deserializedGetIndexStatisticsResult.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 deserializedGetIndexStatisticsResult; }); } } 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/indexes/models/HighWaterMarkChangeDetectionPolicy.java index 034db95dcd0c..1b98ce7cfa0d 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/indexes/models/HighWaterMarkChangeDetectionPolicy.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -18,8 +15,9 @@ */ @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"; @@ -32,7 +30,7 @@ public final class HighWaterMarkChangeDetectionPolicy extends DataChangeDetectio /** * Creates an instance of HighWaterMarkChangeDetectionPolicy class. - * + * * @param highWaterMarkColumnName the highWaterMarkColumnName value to set. */ @Generated @@ -41,8 +39,8 @@ public HighWaterMarkChangeDetectionPolicy(String 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 @@ -53,7 +51,7 @@ public String getOdataType() { /** * Get the highWaterMarkColumnName property: The name of the high water mark column. - * + * * @return the highWaterMarkColumnName value. */ @Generated @@ -75,7 +73,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of HighWaterMarkChangeDetectionPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of HighWaterMarkChangeDetectionPolicy if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -85,30 +83,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedHighWaterMarkChangeDetectionPolicy; - } - throw new IllegalStateException("Missing required property: highWaterMarkColumnName"); + HighWaterMarkChangeDetectionPolicy deserializedHighWaterMarkChangeDetectionPolicy + = new HighWaterMarkChangeDetectionPolicy(highWaterMarkColumnName); + deserializedHighWaterMarkChangeDetectionPolicy.odataType = odataType; + 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/indexes/models/HnswAlgorithmConfiguration.java index ce7085d5d56b..8f32a4d1c090 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/indexes/models/HnswAlgorithmConfiguration.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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; @@ -33,7 +31,7 @@ public final class HnswAlgorithmConfiguration extends VectorSearchAlgorithmConfi /** * Creates an instance of HnswAlgorithmConfiguration class. - * + * * @param name the name value to set. */ @Generated @@ -42,8 +40,8 @@ public HnswAlgorithmConfiguration(String 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 @@ -54,7 +52,7 @@ public VectorSearchAlgorithmKind getKind() { /** * Get the parameters property: Contains the parameters specific to HNSW algorithm. - * + * * @return the parameters value. */ @Generated @@ -64,7 +62,7 @@ public HnswParameters getParameters() { /** * Set the parameters property: Contains the parameters specific to HNSW algorithm. - * + * * @param parameters the parameters value to set. * @return the HnswAlgorithmConfiguration object itself. */ @@ -89,7 +87,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of HnswAlgorithmConfiguration from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of HnswAlgorithmConfiguration if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -99,17 +97,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchAlgorithmKind.fromString(reader.getString()); } else if ("hnswParameters".equals(fieldName)) { @@ -118,15 +113,10 @@ public static HnswAlgorithmConfiguration fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (nameFound) { - HnswAlgorithmConfiguration deserializedHnswAlgorithmConfiguration - = new HnswAlgorithmConfiguration(name); - deserializedHnswAlgorithmConfiguration.kind = kind; - deserializedHnswAlgorithmConfiguration.parameters = parameters; - - return deserializedHnswAlgorithmConfiguration; - } - throw new IllegalStateException("Missing required property: name"); + HnswAlgorithmConfiguration deserializedHnswAlgorithmConfiguration = new HnswAlgorithmConfiguration(name); + deserializedHnswAlgorithmConfiguration.kind = kind; + deserializedHnswAlgorithmConfiguration.parameters = parameters; + 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/indexes/models/HnswParameters.java index a8d8c3e81da8..5200e248ef75 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/indexes/models/HnswParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @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 @@ -60,7 +58,7 @@ 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. - * + * * @return the m value. */ @Generated @@ -72,7 +70,7 @@ public Integer getM() { * 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. */ @@ -86,7 +84,7 @@ 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. - * + * * @return the efConstruction value. */ @Generated @@ -98,7 +96,7 @@ public Integer getEfConstruction() { * 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. - * + * * @param efConstruction the efConstruction value to set. * @return the HnswParameters object itself. */ @@ -112,7 +110,7 @@ public HnswParameters setEfConstruction(Integer efConstruction) { * 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 @@ -124,7 +122,7 @@ public Integer getEfSearch() { * 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. */ @@ -136,7 +134,7 @@ public HnswParameters setEfSearch(Integer efSearch) { /** * Get the metric property: The similarity metric to use for vector comparisons. - * + * * @return the metric value. */ @Generated @@ -146,7 +144,7 @@ public VectorSearchAlgorithmMetric getMetric() { /** * Set the metric property: The similarity metric to use for vector comparisons. - * + * * @param metric the metric value to set. * @return the HnswParameters object itself. */ @@ -172,7 +170,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of HnswParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of HnswParameters if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -185,7 +183,6 @@ public static HnswParameters fromJson(JsonReader jsonReader) throws IOException while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("m".equals(fieldName)) { deserializedHnswParameters.m = reader.getNullable(JsonReader::getInt); } else if ("efConstruction".equals(fieldName)) { @@ -198,7 +195,6 @@ public static HnswParameters fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedHnswParameters; }); } 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/indexes/models/ImageAnalysisSkill.java index bd3b1b7da543..a637ec6970b8 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/indexes/models/ImageAnalysisSkill.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,7 +9,6 @@ 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; @@ -22,7 +19,7 @@ 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"; @@ -57,7 +54,7 @@ public ImageAnalysisSkill(List inputs, 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. + */ + public ImageAnalysisSkill setVisualFeatures(VisualFeature... visualFeatures) { + this.visualFeatures = (visualFeatures == null) ? null : Arrays.asList(visualFeatures); + return this; + } + /** * Set the visualFeatures property: A list of visual features. * @@ -121,6 +129,17 @@ 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. + */ + public ImageAnalysisSkill setDetails(ImageDetail... details) { + this.details = (details == null) ? null : Arrays.asList(details); + return this; + } + /** * Set the details property: A string indicating which domain-specific details to return. * @@ -197,9 +216,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -213,10 +230,8 @@ public static ImageAnalysisSkill fromJson(JsonReader jsonReader) throws IOExcept 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)) { @@ -235,48 +250,15 @@ 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/indexes/models/ImageAnalysisSkillLanguage.java index 7ea97ae0c697..3a991e206d47 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/indexes/models/ImageAnalysisSkillLanguage.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The language codes supported for input by ImageAnalysisSkill. */ public final class ImageAnalysisSkillLanguage extends ExpandableStringEnum { + /** * Arabic. */ @@ -328,7 +326,7 @@ public final class ImageAnalysisSkillLanguage extends ExpandableStringEnum { + /** * Details recognized as celebrities. */ @@ -28,7 +26,7 @@ public final class ImageDetail extends ExpandableStringEnum { /** * Creates a new instance of ImageDetail value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -38,7 +36,7 @@ public ImageDetail() { /** * Creates or finds a ImageDetail from its string representation. - * + * * @param name a name to look for. * @return the corresponding ImageDetail. */ @@ -49,7 +47,7 @@ public static ImageDetail fromString(String name) { /** * Gets known ImageDetail values. - * + * * @return known ImageDetail values. */ @Generated 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/IndexProjectionMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexProjectionMode.java index 214a056ca47e..112657488a2e 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/indexes/models/IndexProjectionMode.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * 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. */ @@ -29,7 +27,7 @@ public final class IndexProjectionMode extends ExpandableStringEnum { + /* * The name of the index. */ @@ -31,39 +27,33 @@ public final class IndexStatisticsSummary implements JsonSerializable { - boolean nameFound = false; String name = null; - boolean documentCountFound = false; long documentCount = 0L; - boolean storageSizeFound = false; long storageSize = 0L; - boolean vectorIndexSizeFound = false; long vectorIndexSize = 0L; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else 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.getLong(); - vectorIndexSizeFound = true; } else { reader.skipChildren(); } } - if (nameFound && documentCountFound && storageSizeFound && vectorIndexSizeFound) { - return new IndexStatisticsSummary(name, documentCount, storageSize, vectorIndexSize); - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!documentCountFound) { - missingProperties.add("documentCount"); - } - if (!storageSizeFound) { - missingProperties.add("storageSize"); - } - if (!vectorIndexSizeFound) { - missingProperties.add("vectorIndexSize"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexStatisticsSummary deserializedIndexStatisticsSummary = new IndexStatisticsSummary(name); + deserializedIndexStatisticsSummary.documentCount = documentCount; + deserializedIndexStatisticsSummary.storageSize = storageSize; + deserializedIndexStatisticsSummary.vectorIndexSize = vectorIndexSize; + return deserializedIndexStatisticsSummary; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSource.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSource.java index 03efa558c935..6e98cfe5ee59 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSource.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSource.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,14 +9,13 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Configuration for OneLake knowledge source. */ @Fluent public final class IndexedOneLakeKnowledgeSource extends KnowledgeSource { + /* * The type of the knowledge source. */ @@ -27,14 +23,14 @@ public final class IndexedOneLakeKnowledgeSource extends KnowledgeSource { private KnowledgeSourceKind kind = KnowledgeSourceKind.INDEXED_ONE_LAKE; /* - * The parameters for the OneLake knowledge source. + * The parameters for the knowledge source. */ @Generated private final IndexedOneLakeKnowledgeSourceParameters indexedOneLakeParameters; /** * Creates an instance of IndexedOneLakeKnowledgeSource class. - * + * * @param name the name value to set. * @param indexedOneLakeParameters the indexedOneLakeParameters value to set. */ @@ -47,7 +43,7 @@ public IndexedOneLakeKnowledgeSource(String name, /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -57,8 +53,8 @@ public KnowledgeSourceKind getKind() { } /** - * Get the indexedOneLakeParameters property: The parameters for the OneLake knowledge source. - * + * Get the indexedOneLakeParameters property: The parameters for the knowledge source. + * * @return the indexedOneLakeParameters value. */ @Generated @@ -114,7 +110,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexedOneLakeKnowledgeSource from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexedOneLakeKnowledgeSource if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -124,21 +120,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexedOneLakeKnowledgeSource fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String description = null; String eTag = null; SearchResourceEncryptionKey encryptionKey = null; - boolean indexedOneLakeParametersFound = false; IndexedOneLakeKnowledgeSourceParameters indexedOneLakeParameters = null; KnowledgeSourceKind kind = KnowledgeSourceKind.INDEXED_ONE_LAKE; 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 ("@odata.etag".equals(fieldName)) { @@ -147,33 +139,19 @@ public static IndexedOneLakeKnowledgeSource fromJson(JsonReader jsonReader) thro encryptionKey = SearchResourceEncryptionKey.fromJson(reader); } else if ("indexedOneLakeParameters".equals(fieldName)) { indexedOneLakeParameters = IndexedOneLakeKnowledgeSourceParameters.fromJson(reader); - indexedOneLakeParametersFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeSourceKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound && indexedOneLakeParametersFound) { - IndexedOneLakeKnowledgeSource deserializedIndexedOneLakeKnowledgeSource - = new IndexedOneLakeKnowledgeSource(name, indexedOneLakeParameters); - deserializedIndexedOneLakeKnowledgeSource.setDescription(description); - deserializedIndexedOneLakeKnowledgeSource.setETag(eTag); - deserializedIndexedOneLakeKnowledgeSource.setEncryptionKey(encryptionKey); - deserializedIndexedOneLakeKnowledgeSource.kind = kind; - - return deserializedIndexedOneLakeKnowledgeSource; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!indexedOneLakeParametersFound) { - missingProperties.add("indexedOneLakeParameters"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexedOneLakeKnowledgeSource deserializedIndexedOneLakeKnowledgeSource + = new IndexedOneLakeKnowledgeSource(name, indexedOneLakeParameters); + deserializedIndexedOneLakeKnowledgeSource.setDescription(description); + deserializedIndexedOneLakeKnowledgeSource.setETag(eTag); + deserializedIndexedOneLakeKnowledgeSource.setEncryptionKey(encryptionKey); + deserializedIndexedOneLakeKnowledgeSource.kind = kind; + return deserializedIndexedOneLakeKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSourceParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSourceParameters.java index c05d8e8428f4..0b09c5428ae8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSourceParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSourceParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,10 +9,8 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; /** * Parameters for OneLake knowledge source. @@ -23,6 +18,7 @@ @Fluent public final class IndexedOneLakeKnowledgeSourceParameters implements JsonSerializable { + /* * OneLake workspace ID. */ @@ -51,11 +47,11 @@ public final class IndexedOneLakeKnowledgeSourceParameters * Resources created by the knowledge source. */ @Generated - private Map createdResources; + private CreatedResources createdResources; /** * Creates an instance of IndexedOneLakeKnowledgeSourceParameters class. - * + * * @param fabricWorkspaceId the fabricWorkspaceId value to set. * @param lakehouseId the lakehouseId value to set. */ @@ -67,7 +63,7 @@ public IndexedOneLakeKnowledgeSourceParameters(String fabricWorkspaceId, String /** * Get the fabricWorkspaceId property: OneLake workspace ID. - * + * * @return the fabricWorkspaceId value. */ @Generated @@ -77,7 +73,7 @@ public String getFabricWorkspaceId() { /** * Get the lakehouseId property: Specifies which OneLake lakehouse to access. - * + * * @return the lakehouseId value. */ @Generated @@ -87,7 +83,7 @@ public String getLakehouseId() { /** * Get the targetPath property: Optional OneLakehouse folder or shortcut to filter OneLake content. - * + * * @return the targetPath value. */ @Generated @@ -97,7 +93,7 @@ public String getTargetPath() { /** * Set the targetPath property: Optional OneLakehouse folder or shortcut to filter OneLake content. - * + * * @param targetPath the targetPath value to set. * @return the IndexedOneLakeKnowledgeSourceParameters object itself. */ @@ -109,7 +105,7 @@ public IndexedOneLakeKnowledgeSourceParameters setTargetPath(String targetPath) /** * Get the ingestionParameters property: Consolidates all general ingestion settings. - * + * * @return the ingestionParameters value. */ @Generated @@ -119,7 +115,7 @@ public KnowledgeSourceIngestionParameters getIngestionParameters() { /** * Set the ingestionParameters property: Consolidates all general ingestion settings. - * + * * @param ingestionParameters the ingestionParameters value to set. * @return the IndexedOneLakeKnowledgeSourceParameters object itself. */ @@ -132,11 +128,11 @@ public KnowledgeSourceIngestionParameters getIngestionParameters() { /** * Get the createdResources property: Resources created by the knowledge source. - * + * * @return the createdResources value. */ @Generated - public Map getCreatedResources() { + public CreatedResources getCreatedResources() { return this.createdResources; } @@ -156,7 +152,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexedOneLakeKnowledgeSourceParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexedOneLakeKnowledgeSourceParameters if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -166,52 +162,34 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexedOneLakeKnowledgeSourceParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean fabricWorkspaceIdFound = false; String fabricWorkspaceId = null; - boolean lakehouseIdFound = false; String lakehouseId = null; String targetPath = null; KnowledgeSourceIngestionParameters ingestionParameters = null; - Map createdResources = null; + CreatedResources createdResources = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("fabricWorkspaceId".equals(fieldName)) { fabricWorkspaceId = reader.getString(); - fabricWorkspaceIdFound = true; } else if ("lakehouseId".equals(fieldName)) { lakehouseId = reader.getString(); - lakehouseIdFound = true; } else if ("targetPath".equals(fieldName)) { targetPath = reader.getString(); } else if ("ingestionParameters".equals(fieldName)) { ingestionParameters = KnowledgeSourceIngestionParameters.fromJson(reader); } else if ("createdResources".equals(fieldName)) { - createdResources = reader.readMap(reader1 -> reader1.getString()); + createdResources = CreatedResources.fromJson(reader); } else { reader.skipChildren(); } } - if (fabricWorkspaceIdFound && lakehouseIdFound) { - IndexedOneLakeKnowledgeSourceParameters deserializedIndexedOneLakeKnowledgeSourceParameters - = new IndexedOneLakeKnowledgeSourceParameters(fabricWorkspaceId, lakehouseId); - deserializedIndexedOneLakeKnowledgeSourceParameters.targetPath = targetPath; - deserializedIndexedOneLakeKnowledgeSourceParameters.ingestionParameters = ingestionParameters; - deserializedIndexedOneLakeKnowledgeSourceParameters.createdResources = createdResources; - - return deserializedIndexedOneLakeKnowledgeSourceParameters; - } - List missingProperties = new ArrayList<>(); - if (!fabricWorkspaceIdFound) { - missingProperties.add("fabricWorkspaceId"); - } - if (!lakehouseIdFound) { - missingProperties.add("lakehouseId"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexedOneLakeKnowledgeSourceParameters deserializedIndexedOneLakeKnowledgeSourceParameters + = new IndexedOneLakeKnowledgeSourceParameters(fabricWorkspaceId, lakehouseId); + deserializedIndexedOneLakeKnowledgeSourceParameters.targetPath = targetPath; + deserializedIndexedOneLakeKnowledgeSourceParameters.ingestionParameters = ingestionParameters; + deserializedIndexedOneLakeKnowledgeSourceParameters.createdResources = createdResources; + return deserializedIndexedOneLakeKnowledgeSourceParameters; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointContainerName.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointContainerName.java index 3a6da72766a3..d6cfe2df5894 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointContainerName.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointContainerName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Specifies which SharePoint libraries to access. */ public final class IndexedSharePointContainerName extends ExpandableStringEnum { + /** * Index content from the site's default document library. */ @@ -27,14 +25,14 @@ public final class IndexedSharePointContainerName extends ExpandableStringEnum { - boolean nameFound = false; String name = null; String description = null; String eTag = null; SearchResourceEncryptionKey encryptionKey = null; - boolean indexedSharePointParametersFound = false; IndexedSharePointKnowledgeSourceParameters indexedSharePointParameters = null; KnowledgeSourceKind kind = KnowledgeSourceKind.INDEXED_SHARE_POINT; 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 ("@odata.etag".equals(fieldName)) { @@ -147,33 +139,19 @@ public static IndexedSharePointKnowledgeSource fromJson(JsonReader jsonReader) t encryptionKey = SearchResourceEncryptionKey.fromJson(reader); } else if ("indexedSharePointParameters".equals(fieldName)) { indexedSharePointParameters = IndexedSharePointKnowledgeSourceParameters.fromJson(reader); - indexedSharePointParametersFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeSourceKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound && indexedSharePointParametersFound) { - IndexedSharePointKnowledgeSource deserializedIndexedSharePointKnowledgeSource - = new IndexedSharePointKnowledgeSource(name, indexedSharePointParameters); - deserializedIndexedSharePointKnowledgeSource.setDescription(description); - deserializedIndexedSharePointKnowledgeSource.setETag(eTag); - deserializedIndexedSharePointKnowledgeSource.setEncryptionKey(encryptionKey); - deserializedIndexedSharePointKnowledgeSource.kind = kind; - - return deserializedIndexedSharePointKnowledgeSource; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!indexedSharePointParametersFound) { - missingProperties.add("indexedSharePointParameters"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexedSharePointKnowledgeSource deserializedIndexedSharePointKnowledgeSource + = new IndexedSharePointKnowledgeSource(name, indexedSharePointParameters); + deserializedIndexedSharePointKnowledgeSource.setDescription(description); + deserializedIndexedSharePointKnowledgeSource.setETag(eTag); + deserializedIndexedSharePointKnowledgeSource.setEncryptionKey(encryptionKey); + deserializedIndexedSharePointKnowledgeSource.kind = kind; + return deserializedIndexedSharePointKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointKnowledgeSourceParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointKnowledgeSourceParameters.java index b0b569a2569e..54d5907dae7e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointKnowledgeSourceParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointKnowledgeSourceParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,10 +9,8 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; /** * Parameters for SharePoint knowledge source. @@ -23,6 +18,7 @@ @Fluent public final class IndexedSharePointKnowledgeSourceParameters implements JsonSerializable { + /* * SharePoint connection string with format: SharePointOnlineEndpoint=[SharePoint site url];ApplicationId=[Azure AD * App ID];ApplicationSecret=[Azure AD App client secret];TenantId=[SharePoint site tenant id] @@ -52,11 +48,11 @@ public final class IndexedSharePointKnowledgeSourceParameters * Resources created by the knowledge source. */ @Generated - private Map createdResources; + private CreatedResources createdResources; /** * Creates an instance of IndexedSharePointKnowledgeSourceParameters class. - * + * * @param connectionString the connectionString value to set. * @param containerName the containerName value to set. */ @@ -71,7 +67,7 @@ public IndexedSharePointKnowledgeSourceParameters(String connectionString, * Get the connectionString property: SharePoint connection string with format: SharePointOnlineEndpoint=[SharePoint * site url];ApplicationId=[Azure AD App ID];ApplicationSecret=[Azure AD App client secret];TenantId=[SharePoint * site tenant id]. - * + * * @return the connectionString value. */ @Generated @@ -81,7 +77,7 @@ public String getConnectionString() { /** * Get the containerName property: Specifies which SharePoint libraries to access. - * + * * @return the containerName value. */ @Generated @@ -91,7 +87,7 @@ public IndexedSharePointContainerName getContainerName() { /** * Get the query property: Optional query to filter SharePoint content. - * + * * @return the query value. */ @Generated @@ -101,7 +97,7 @@ public String getQuery() { /** * Set the query property: Optional query to filter SharePoint content. - * + * * @param query the query value to set. * @return the IndexedSharePointKnowledgeSourceParameters object itself. */ @@ -113,7 +109,7 @@ public IndexedSharePointKnowledgeSourceParameters setQuery(String query) { /** * Get the ingestionParameters property: Consolidates all general ingestion settings. - * + * * @return the ingestionParameters value. */ @Generated @@ -123,7 +119,7 @@ public KnowledgeSourceIngestionParameters getIngestionParameters() { /** * Set the ingestionParameters property: Consolidates all general ingestion settings. - * + * * @param ingestionParameters the ingestionParameters value to set. * @return the IndexedSharePointKnowledgeSourceParameters object itself. */ @@ -136,11 +132,11 @@ public KnowledgeSourceIngestionParameters getIngestionParameters() { /** * Get the createdResources property: Resources created by the knowledge source. - * + * * @return the createdResources value. */ @Generated - public Map getCreatedResources() { + public CreatedResources getCreatedResources() { return this.createdResources; } @@ -160,7 +156,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexedSharePointKnowledgeSourceParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexedSharePointKnowledgeSourceParameters if the JsonReader was pointing to an instance * of it, or null if it was pointing to JSON null. @@ -170,52 +166,34 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexedSharePointKnowledgeSourceParameters fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean connectionStringFound = false; String connectionString = null; - boolean containerNameFound = false; IndexedSharePointContainerName containerName = null; String query = null; KnowledgeSourceIngestionParameters ingestionParameters = null; - Map createdResources = null; + CreatedResources createdResources = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("connectionString".equals(fieldName)) { connectionString = reader.getString(); - connectionStringFound = true; } else if ("containerName".equals(fieldName)) { containerName = IndexedSharePointContainerName.fromString(reader.getString()); - containerNameFound = true; } else if ("query".equals(fieldName)) { query = reader.getString(); } else if ("ingestionParameters".equals(fieldName)) { ingestionParameters = KnowledgeSourceIngestionParameters.fromJson(reader); } else if ("createdResources".equals(fieldName)) { - createdResources = reader.readMap(reader1 -> reader1.getString()); + createdResources = CreatedResources.fromJson(reader); } else { reader.skipChildren(); } } - if (connectionStringFound && containerNameFound) { - IndexedSharePointKnowledgeSourceParameters deserializedIndexedSharePointKnowledgeSourceParameters - = new IndexedSharePointKnowledgeSourceParameters(connectionString, containerName); - deserializedIndexedSharePointKnowledgeSourceParameters.query = query; - deserializedIndexedSharePointKnowledgeSourceParameters.ingestionParameters = ingestionParameters; - deserializedIndexedSharePointKnowledgeSourceParameters.createdResources = createdResources; - - return deserializedIndexedSharePointKnowledgeSourceParameters; - } - List missingProperties = new ArrayList<>(); - if (!connectionStringFound) { - missingProperties.add("connectionString"); - } - if (!containerNameFound) { - missingProperties.add("containerName"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexedSharePointKnowledgeSourceParameters deserializedIndexedSharePointKnowledgeSourceParameters + = new IndexedSharePointKnowledgeSourceParameters(connectionString, containerName); + deserializedIndexedSharePointKnowledgeSourceParameters.query = query; + deserializedIndexedSharePointKnowledgeSourceParameters.ingestionParameters = ingestionParameters; + deserializedIndexedSharePointKnowledgeSourceParameters.createdResources = createdResources; + return deserializedIndexedSharePointKnowledgeSourceParameters; }); } } 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/indexes/models/IndexerCurrentState.java index 3cd4791b3e0d..9ad0bfe12e07 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/indexes/models/IndexerCurrentState.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -20,6 +17,7 @@ */ @Immutable public final class IndexerCurrentState implements JsonSerializable { + /* * The mode the indexer is running in. */ @@ -51,41 +49,41 @@ public final class IndexerCurrentState implements JsonSerializable resetDocumentKeys; + private String resyncInitialTrackingState; /* - * 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. + * Change tracking state value when indexing finishes on selective options from the datasource. */ @Generated - private List resetDatasourceDocumentIds; + private String resyncFinalTrackingState; /* - * Change tracking state used when indexing starts on selective options from the datasource. + * 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 String resyncInitialTrackingState; + private List resetDocumentKeys; /* - * Change tracking state value when indexing finishes on selective options from the datasource. + * 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 String resyncFinalTrackingState; + private List resetDatasourceDocumentIds; /** * Creates an instance of IndexerCurrentState class. */ @Generated - public IndexerCurrentState() { + private IndexerCurrentState() { } /** * Get the mode property: The mode the indexer is running in. - * + * * @return the mode value. */ @Generated @@ -96,7 +94,7 @@ public IndexingMode getMode() { /** * Get the allDocsInitialTrackingState property: Change tracking state used when indexing starts on all documents in * the datasource. - * + * * @return the allDocsInitialTrackingState value. */ @Generated @@ -107,7 +105,7 @@ public String getAllDocsInitialTrackingState() { /** * Get the allDocsFinalTrackingState property: Change tracking state value when indexing finishes on all documents * in the datasource. - * + * * @return the allDocsFinalTrackingState value. */ @Generated @@ -118,7 +116,7 @@ public String getAllDocsFinalTrackingState() { /** * Get the resetDocsInitialTrackingState property: Change tracking state used when indexing starts on select, reset * documents in the datasource. - * + * * @return the resetDocsInitialTrackingState value. */ @Generated @@ -129,7 +127,7 @@ public String getResetDocsInitialTrackingState() { /** * Get the resetDocsFinalTrackingState property: Change tracking state value when indexing finishes on select, reset * documents in the datasource. - * + * * @return the resetDocsFinalTrackingState value. */ @Generated @@ -137,11 +135,33 @@ public String getResetDocsFinalTrackingState() { return this.resetDocsFinalTrackingState; } + /** + * Get the resyncInitialTrackingState property: Change tracking state used when indexing starts on selective options + * from the datasource. + * + * @return the resyncInitialTrackingState value. + */ + @Generated + public String getResyncInitialTrackingState() { + return this.resyncInitialTrackingState; + } + + /** + * Get the resyncFinalTrackingState property: Change tracking state value when indexing finishes on selective + * options from the datasource. + * + * @return the resyncFinalTrackingState value. + */ + @Generated + public String getResyncFinalTrackingState() { + return this.resyncFinalTrackingState; + } + /** * 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. - * + * * @return the resetDocumentKeys value. */ @Generated @@ -153,7 +173,7 @@ public List getResetDocumentKeys() { * 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. - * + * * @return the resetDatasourceDocumentIds value. */ @Generated @@ -161,28 +181,6 @@ public List getResetDatasourceDocumentIds() { return this.resetDatasourceDocumentIds; } - /** - * Get the resyncInitialTrackingState property: Change tracking state used when indexing starts on selective options - * from the datasource. - * - * @return the resyncInitialTrackingState value. - */ - @Generated - public String getResyncInitialTrackingState() { - return this.resyncInitialTrackingState; - } - - /** - * Get the resyncFinalTrackingState property: Change tracking state value when indexing finishes on selective - * options from the datasource. - * - * @return the resyncFinalTrackingState value. - */ - @Generated - public String getResyncFinalTrackingState() { - return this.resyncFinalTrackingState; - } - /** * {@inheritDoc} */ @@ -195,7 +193,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexerCurrentState from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexerCurrentState if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -208,7 +206,6 @@ public static IndexerCurrentState fromJson(JsonReader jsonReader) throws IOExcep while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("mode".equals(fieldName)) { deserializedIndexerCurrentState.mode = IndexingMode.fromString(reader.getString()); } else if ("allDocsInitialTrackingState".equals(fieldName)) { @@ -219,21 +216,20 @@ public static IndexerCurrentState fromJson(JsonReader jsonReader) throws IOExcep deserializedIndexerCurrentState.resetDocsInitialTrackingState = reader.getString(); } else if ("resetDocsFinalTrackingState".equals(fieldName)) { deserializedIndexerCurrentState.resetDocsFinalTrackingState = reader.getString(); + } else if ("resyncInitialTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.resyncInitialTrackingState = reader.getString(); + } else if ("resyncFinalTrackingState".equals(fieldName)) { + deserializedIndexerCurrentState.resyncFinalTrackingState = reader.getString(); } else if ("resetDocumentKeys".equals(fieldName)) { List resetDocumentKeys = reader.readArray(reader1 -> reader1.getString()); deserializedIndexerCurrentState.resetDocumentKeys = resetDocumentKeys; } else if ("resetDatasourceDocumentIds".equals(fieldName)) { List resetDatasourceDocumentIds = reader.readArray(reader1 -> reader1.getString()); deserializedIndexerCurrentState.resetDatasourceDocumentIds = resetDatasourceDocumentIds; - } else if ("resyncInitialTrackingState".equals(fieldName)) { - deserializedIndexerCurrentState.resyncInitialTrackingState = reader.getString(); - } else if ("resyncFinalTrackingState".equals(fieldName)) { - deserializedIndexerCurrentState.resyncFinalTrackingState = reader.getString(); } else { reader.skipChildren(); } } - return deserializedIndexerCurrentState; }); } 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/indexes/models/IndexerExecutionEnvironment.java index 734a15fc2fa0..f3d2d2b318ce 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/indexes/models/IndexerExecutionEnvironment.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Specifies the environment in which the indexer should execute. */ 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. @@ -31,7 +29,7 @@ public final class IndexerExecutionEnvironment extends ExpandableStringEnum { + /* * The outcome of this indexer execution. */ @Generated - private final IndexerExecutionStatus status; + private IndexerExecutionStatus status; /* * The outcome of this indexer execution. @@ -63,26 +60,26 @@ public final class IndexerExecutionResult implements JsonSerializable errors; + private List errors; /* * The item-level indexing warnings. */ @Generated - private final List warnings; + private 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. */ @Generated - private final int itemCount; + private int itemCount; /* * The number of items that failed to be indexed during this indexer execution. */ @Generated - private final int failedItemCount; + private int failedItemCount; /* * Change tracking state with which an indexer execution started. @@ -98,26 +95,14 @@ public final class IndexerExecutionResult implements JsonSerializable errors, - List warnings, int itemCount, int failedItemCount) { - this.status = status; - this.errors = errors; - this.warnings = warnings; - this.itemCount = itemCount; - this.failedItemCount = failedItemCount; + private IndexerExecutionResult() { } /** * Get the status property: The outcome of this indexer execution. - * + * * @return the status value. */ @Generated @@ -127,7 +112,7 @@ public IndexerExecutionStatus getStatus() { /** * Get the statusDetail property: The outcome of this indexer execution. - * + * * @return the statusDetail value. */ @Generated @@ -137,7 +122,7 @@ public IndexerExecutionStatusDetail getStatusDetail() { /** * Get the mode property: The mode the indexer is running in. - * + * * @return the mode value. */ @Generated @@ -147,7 +132,7 @@ public IndexingMode getMode() { /** * Get the errorMessage property: The error message indicating the top-level error, if any. - * + * * @return the errorMessage value. */ @Generated @@ -157,7 +142,7 @@ public String getErrorMessage() { /** * Get the startTime property: The start time of this indexer execution. - * + * * @return the startTime value. */ @Generated @@ -167,7 +152,7 @@ public OffsetDateTime getStartTime() { /** * Get the endTime property: The end time of this indexer execution, if the execution has already completed. - * + * * @return the endTime value. */ @Generated @@ -177,7 +162,7 @@ public OffsetDateTime getEndTime() { /** * Get the errors property: The item-level indexing errors. - * + * * @return the errors value. */ @Generated @@ -187,7 +172,7 @@ public List getErrors() { /** * Get the warnings property: The item-level indexing warnings. - * + * * @return the warnings value. */ @Generated @@ -198,7 +183,7 @@ public List getWarnings() { /** * 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 @@ -208,7 +193,7 @@ public int getItemCount() { /** * Get the failedItemCount property: The number of items that failed to be indexed during this indexer execution. - * + * * @return the failedItemCount value. */ @Generated @@ -218,7 +203,7 @@ public int getFailedItemCount() { /** * Get the initialTrackingState property: Change tracking state with which an indexer execution started. - * + * * @return the initialTrackingState value. */ @Generated @@ -228,7 +213,7 @@ public String getInitialTrackingState() { /** * Get the finalTrackingState property: Change tracking state with which an indexer execution finished. - * + * * @return the finalTrackingState value. */ @Generated @@ -248,7 +233,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexerExecutionResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexerExecutionResult if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -258,94 +243,45 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; - IndexingMode mode = null; - String errorMessage = null; - OffsetDateTime startTime = null; - OffsetDateTime endTime = null; - String initialTrackingState = null; - String finalTrackingState = null; + IndexerExecutionResult deserializedIndexerExecutionResult = new IndexerExecutionResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("status".equals(fieldName)) { - status = IndexerExecutionStatus.fromString(reader.getString()); - statusFound = true; + deserializedIndexerExecutionResult.status = IndexerExecutionStatus.fromString(reader.getString()); } else if ("errors".equals(fieldName)) { - errors = reader.readArray(reader1 -> SearchIndexerError.fromJson(reader1)); - errorsFound = true; + List errors = reader.readArray(reader1 -> SearchIndexerError.fromJson(reader1)); + deserializedIndexerExecutionResult.errors = errors; } else if ("warnings".equals(fieldName)) { - warnings = reader.readArray(reader1 -> SearchIndexerWarning.fromJson(reader1)); - warningsFound = true; + List warnings + = reader.readArray(reader1 -> SearchIndexerWarning.fromJson(reader1)); + deserializedIndexerExecutionResult.warnings = warnings; } else if ("itemsProcessed".equals(fieldName)) { - itemCount = reader.getInt(); - itemCountFound = true; + deserializedIndexerExecutionResult.itemCount = reader.getInt(); } else if ("itemsFailed".equals(fieldName)) { - failedItemCount = reader.getInt(); - failedItemCountFound = true; + deserializedIndexerExecutionResult.failedItemCount = reader.getInt(); } else if ("statusDetail".equals(fieldName)) { - statusDetail = IndexerExecutionStatusDetail.fromString(reader.getString()); + deserializedIndexerExecutionResult.statusDetail + = IndexerExecutionStatusDetail.fromString(reader.getString()); } else if ("mode".equals(fieldName)) { - mode = IndexingMode.fromString(reader.getString()); + deserializedIndexerExecutionResult.mode = IndexingMode.fromString(reader.getString()); } else if ("errorMessage".equals(fieldName)) { - errorMessage = reader.getString(); + deserializedIndexerExecutionResult.errorMessage = reader.getString(); } else if ("startTime".equals(fieldName)) { - startTime = reader + deserializedIndexerExecutionResult.startTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("endTime".equals(fieldName)) { - endTime = reader + deserializedIndexerExecutionResult.endTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); } else if ("initialTrackingState".equals(fieldName)) { - initialTrackingState = reader.getString(); + deserializedIndexerExecutionResult.initialTrackingState = reader.getString(); } else if ("finalTrackingState".equals(fieldName)) { - finalTrackingState = reader.getString(); + deserializedIndexerExecutionResult.finalTrackingState = reader.getString(); } else { reader.skipChildren(); } } - if (statusFound && errorsFound && warningsFound && itemCountFound && failedItemCountFound) { - IndexerExecutionResult deserializedIndexerExecutionResult - = new IndexerExecutionResult(status, errors, warnings, itemCount, failedItemCount); - deserializedIndexerExecutionResult.statusDetail = statusDetail; - deserializedIndexerExecutionResult.mode = mode; - 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)); + return deserializedIndexerExecutionResult; }); } } 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 index 5f58151ef9b2..24333ce343c8 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/IndexerExecutionStatusDetail.java index afcb98795474..bd505ea49705 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/indexes/models/IndexerExecutionStatusDetail.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Details the status of an individual indexer execution. */ public final class IndexerExecutionStatusDetail extends ExpandableStringEnum { + /** * Indicates that the reset that occurred was for a call to ResetDocs. */ @@ -28,7 +26,7 @@ public final class IndexerExecutionStatusDetail extends ExpandableStringEnum { + /** * Indexer to ingest ACL userIds from data source to index. */ @@ -34,7 +32,7 @@ public final class IndexerPermissionOption extends ExpandableStringEnum { + /* * Re-sync options that have been pre-defined from data source. */ @@ -35,7 +34,7 @@ public IndexerResyncBody() { /** * Get the options property: Re-sync options that have been pre-defined from data source. - * + * * @return the options value. */ @Generated @@ -45,7 +44,18 @@ public List getOptions() { /** * Set the options property: Re-sync options that have been pre-defined from data source. - * + * + * @param options the options value to set. + * @return the IndexerResyncBody object itself. + */ + public IndexerResyncBody setOptions(IndexerResyncOption... options) { + this.options = (options == null) ? null : Arrays.asList(options); + return this; + } + + /** + * Set the options property: Re-sync options that have been pre-defined from data source. + * * @param options the options value to set. * @return the IndexerResyncBody object itself. */ @@ -69,7 +79,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexerResyncBody from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexerResyncBody if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -82,7 +92,6 @@ public static IndexerResyncBody fromJson(JsonReader jsonReader) throws IOExcepti while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("options".equals(fieldName)) { List options = reader.readArray(reader1 -> IndexerResyncOption.fromString(reader1.getString())); @@ -91,7 +100,6 @@ public static IndexerResyncBody fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedIndexerResyncBody; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java index fda39ba7a1ab..b23f364c0f2a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Options with various types of permission data to index. */ public final class IndexerResyncOption extends ExpandableStringEnum { + /** * Indexer to re-ingest pre-selected permissions data from data source to index. */ @@ -22,7 +20,7 @@ public final class IndexerResyncOption extends ExpandableStringEnum { + /* * Cumulative runtime of the indexer from the beginningTime to endingTime, in seconds. */ @@ -50,13 +46,13 @@ public final class IndexerRuntime implements JsonSerializable { /** * Creates an instance of IndexerRuntime class. - * + * * @param usedSeconds the usedSeconds value to set. * @param beginningTime the beginningTime value to set. * @param endingTime the endingTime value to set. */ @Generated - public IndexerRuntime(long usedSeconds, OffsetDateTime beginningTime, OffsetDateTime endingTime) { + private IndexerRuntime(long usedSeconds, OffsetDateTime beginningTime, OffsetDateTime endingTime) { this.usedSeconds = usedSeconds; this.beginningTime = beginningTime; this.endingTime = endingTime; @@ -64,7 +60,7 @@ public IndexerRuntime(long usedSeconds, OffsetDateTime beginningTime, OffsetDate /** * Get the usedSeconds property: Cumulative runtime of the indexer from the beginningTime to endingTime, in seconds. - * + * * @return the usedSeconds value. */ @Generated @@ -75,7 +71,7 @@ public long getUsedSeconds() { /** * Get the remainingSeconds property: Cumulative runtime remaining for all indexers in the service from the * beginningTime to endingTime, in seconds. - * + * * @return the remainingSeconds value. */ @Generated @@ -83,23 +79,10 @@ public Long getRemainingSeconds() { return this.remainingSeconds; } - /** - * Set the remainingSeconds property: Cumulative runtime remaining for all indexers in the service from the - * beginningTime to endingTime, in seconds. - * - * @param remainingSeconds the remainingSeconds value to set. - * @return the IndexerRuntime object itself. - */ - @Generated - public IndexerRuntime setRemainingSeconds(Long remainingSeconds) { - this.remainingSeconds = remainingSeconds; - return this; - } - /** * Get the beginningTime property: Beginning UTC time of the 24-hour period considered for indexer runtime usage * (inclusive). - * + * * @return the beginningTime value. */ @Generated @@ -109,7 +92,7 @@ public OffsetDateTime getBeginningTime() { /** * Get the endingTime property: End UTC time of the 24-hour period considered for indexer runtime usage (inclusive). - * + * * @return the endingTime value. */ @Generated @@ -135,7 +118,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexerRuntime from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexerRuntime if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -145,53 +128,30 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexerRuntime fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean usedSecondsFound = false; long usedSeconds = 0L; - boolean beginningTimeFound = false; OffsetDateTime beginningTime = null; - boolean endingTimeFound = false; OffsetDateTime endingTime = null; Long remainingSeconds = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("usedSeconds".equals(fieldName)) { usedSeconds = reader.getLong(); - usedSecondsFound = true; } else if ("beginningTime".equals(fieldName)) { beginningTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - beginningTimeFound = true; } else if ("endingTime".equals(fieldName)) { endingTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - endingTimeFound = true; } else if ("remainingSeconds".equals(fieldName)) { remainingSeconds = reader.getNullable(JsonReader::getLong); } else { reader.skipChildren(); } } - if (usedSecondsFound && beginningTimeFound && endingTimeFound) { - IndexerRuntime deserializedIndexerRuntime = new IndexerRuntime(usedSeconds, beginningTime, endingTime); - deserializedIndexerRuntime.remainingSeconds = remainingSeconds; - - return deserializedIndexerRuntime; - } - List missingProperties = new ArrayList<>(); - if (!usedSecondsFound) { - missingProperties.add("usedSeconds"); - } - if (!beginningTimeFound) { - missingProperties.add("beginningTime"); - } - if (!endingTimeFound) { - missingProperties.add("endingTime"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + IndexerRuntime deserializedIndexerRuntime = new IndexerRuntime(usedSeconds, beginningTime, endingTime); + deserializedIndexerRuntime.remainingSeconds = remainingSeconds; + return deserializedIndexerRuntime; }); } } 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 index 7b7b8c76b497..6bccf0eb208c 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/IndexingMode.java index 992ba44e675e..f3330dcbb59e 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/indexes/models/IndexingMode.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Represents the mode the indexer is executing in. */ public final class IndexingMode extends ExpandableStringEnum { + /** * The indexer is indexing all documents in the datasource. */ @@ -35,7 +33,7 @@ public final class IndexingMode extends ExpandableStringEnum { /** * Creates a new instance of IndexingMode value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -45,7 +43,7 @@ public IndexingMode() { /** * Creates or finds a IndexingMode from its string representation. - * + * * @param name a name to look for. * @return the corresponding IndexingMode. */ @@ -56,7 +54,7 @@ public static IndexingMode fromString(String name) { /** * Gets known IndexingMode values. - * + * * @return known IndexingMode values. */ @Generated 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/indexes/models/IndexingParameters.java index 889e80aff538..84151e01d471 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/indexes/models/IndexingParameters.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,9 +9,7 @@ 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. @@ -135,7 +131,7 @@ public IndexingParameters setMaxFailedItemsPerBatch(Integer maxFailedItemsPerBat * @return the configuration value. */ @Generated - public IndexingParametersConfiguration getIndexingParametersConfiguration() { + public IndexingParametersConfiguration getConfiguration() { return this.configuration; } @@ -147,9 +143,8 @@ public IndexingParametersConfiguration getIndexingParametersConfiguration() { * @return the IndexingParameters object itself. */ @Generated - public IndexingParameters setIndexingParametersConfiguration(IndexingParametersConfiguration configuration) { + public IndexingParameters setConfiguration(IndexingParametersConfiguration configuration) { this.configuration = configuration; - this.configurationMap = MappingUtils.indexingParametersConfigurationToMap(configuration); return this; } @@ -197,29 +192,4 @@ public static IndexingParameters fromJson(JsonReader jsonReader) throws IOExcept 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/indexes/models/IndexingParametersConfiguration.java index 12b0c88e399e..d11c5a11804a 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/indexes/models/IndexingParametersConfiguration.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,6 +19,7 @@ */ @Fluent public final class IndexingParametersConfiguration implements JsonSerializable { + /* * Represents the parsing mode for indexing from an Azure blob data source. */ @@ -130,7 +128,7 @@ public final class IndexingParametersConfiguration implements JsonSerializable getAdditionalProperties() { /** * 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. - * + * * @param additionalProperties the additionalProperties value to set. * @return the IndexingParametersConfiguration object itself. */ @@ -668,7 +666,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexingParametersConfiguration from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexingParametersConfiguration if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -683,7 +681,6 @@ public static IndexingParametersConfiguration fromJson(JsonReader jsonReader) th while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("parsingMode".equals(fieldName)) { deserializedIndexingParametersConfiguration.parsingMode = BlobIndexerParsingMode.fromString(reader.getString()); @@ -726,7 +723,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()); @@ -736,12 +733,10 @@ public static IndexingParametersConfiguration fromJson(JsonReader jsonReader) th if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); } } deserializedIndexingParametersConfiguration.additionalProperties = additionalProperties; - return deserializedIndexingParametersConfiguration; }); } 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/indexes/models/IndexingSchedule.java index 2dc83895e0e6..6123a41df8e1 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/indexes/models/IndexingSchedule.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -23,6 +20,7 @@ */ @Fluent public final class IndexingSchedule implements JsonSerializable { + /* * The interval of time between indexer executions. */ @@ -37,7 +35,7 @@ public final class IndexingSchedule implements JsonSerializable { - boolean intervalFound = false; Duration interval = null; OffsetDateTime startTime = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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())); @@ -119,13 +114,9 @@ public static IndexingSchedule fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (intervalFound) { - IndexingSchedule deserializedIndexingSchedule = new IndexingSchedule(interval); - deserializedIndexingSchedule.startTime = startTime; - - return deserializedIndexingSchedule; - } - throw new IllegalStateException("Missing required property: interval"); + IndexingSchedule deserializedIndexingSchedule = new IndexingSchedule(interval); + deserializedIndexingSchedule.startTime = startTime; + 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/indexes/models/InputFieldMappingEntry.java index 7849882196c1..6570d7f7ffdc 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/indexes/models/InputFieldMappingEntry.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -119,6 +117,17 @@ 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. + */ + public InputFieldMappingEntry setInputs(InputFieldMappingEntry... inputs) { + this.inputs = (inputs == null) ? null : Arrays.asList(inputs); + return this; + } + /** * Set the inputs property: The recursive inputs used when creating a complex type. * @@ -157,7 +166,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -167,7 +175,6 @@ public static InputFieldMappingEntry fromJson(JsonReader jsonReader) throws IOEx reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("source".equals(fieldName)) { source = reader.getString(); } else if ("sourceContext".equals(fieldName)) { @@ -178,25 +185,11 @@ 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; + return deserializedInputFieldMappingEntry; }); } - - /** - * 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; - } } 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/indexes/models/KeepTokenFilter.java index 4b751167e32c..16a08a8558ac 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/indexes/models/KeepTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,7 +9,7 @@ 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; /** @@ -22,7 +20,7 @@ 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"; @@ -39,6 +37,17 @@ public final class KeepTokenFilter extends TokenFilter { @Generated private Boolean lowerCaseKeepWords; + /** + * Creates an instance of KeepTokenFilter class. + * + * @param name the name value to set. + * @param keepWords the keepWords value to set. + */ + public KeepTokenFilter(String name, String... keepWords) { + super(name); + this.keepWords = (keepWords == null) ? null : Arrays.asList(keepWords); + } + /** * Creates an instance of KeepTokenFilter class. * @@ -52,7 +61,7 @@ public KeepTokenFilter(String name, List 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. */ @@ -78,7 +87,7 @@ public List getKeepWords() { * @return the lowerCaseKeepWords value. */ @Generated - public Boolean areLowerCaseKeepWords() { + public Boolean isLowerCaseKeepWords() { return this.lowerCaseKeepWords; } @@ -120,9 +129,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -131,10 +138,8 @@ public static KeepTokenFilter fromJson(JsonReader jsonReader) throws IOException 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)) { @@ -143,21 +148,10 @@ 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/indexes/models/KeyPhraseExtractionSkill.java index 37a9e6324412..69ffe39a1a9d 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/indexes/models/KeyPhraseExtractionSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,8 +16,9 @@ */ @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"; @@ -47,7 +44,7 @@ public final class KeyPhraseExtractionSkill extends SearchIndexerSkill { /** * Creates an instance of KeyPhraseExtractionSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -57,8 +54,8 @@ public KeyPhraseExtractionSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -215,13 +210,10 @@ public static KeyPhraseExtractionSkill fromJson(JsonReader jsonReader) throws IO 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)) { @@ -240,29 +232,16 @@ 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/indexes/models/KeyPhraseExtractionSkillLanguage.java index 8ae43a286fa1..444d6b89f3d4 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/indexes/models/KeyPhraseExtractionSkillLanguage.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The language codes supported for input text by KeyPhraseExtractionSkill. */ public final class KeyPhraseExtractionSkillLanguage extends ExpandableStringEnum { + /** * Danish. */ @@ -112,7 +110,7 @@ public final class KeyPhraseExtractionSkillLanguage extends ExpandableStringEnum /** * Creates a new instance of KeyPhraseExtractionSkillLanguage value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -122,7 +120,7 @@ public KeyPhraseExtractionSkillLanguage() { /** * Creates or finds a KeyPhraseExtractionSkillLanguage from its string representation. - * + * * @param name a name to look for. * @return the corresponding KeyPhraseExtractionSkillLanguage. */ @@ -133,7 +131,7 @@ public static KeyPhraseExtractionSkillLanguage fromString(String name) { /** * Gets known KeyPhraseExtractionSkillLanguage values. - * + * * @return known KeyPhraseExtractionSkillLanguage values. */ @Generated 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/indexes/models/KeywordMarkerTokenFilter.java index e7aef0fc3869..5899b73b8497 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/indexes/models/KeywordMarkerTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -20,8 +17,9 @@ */ @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"; @@ -37,11 +35,22 @@ public final class KeywordMarkerTokenFilter extends TokenFilter { * false. */ @Generated - private Boolean caseIgnored; + private Boolean ignoreCase; + + /** + * Creates an instance of KeywordMarkerTokenFilter class. + * + * @param name the name value to set. + * @param keywords the keywords value to set. + */ + public KeywordMarkerTokenFilter(String name, String... keywords) { + super(name); + this.keywords = (keywords == null) ? null : Arrays.asList(keywords); + } /** * Creates an instance of KeywordMarkerTokenFilter class. - * + * * @param name the name value to set. * @param keywords the keywords value to set. */ @@ -52,8 +61,8 @@ public KeywordMarkerTokenFilter(String name, List 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 @@ -64,7 +73,7 @@ public String getOdataType() { /** * Get the keywords property: A list of words to mark as keywords. - * + * * @return the keywords value. */ @Generated @@ -73,26 +82,26 @@ public List getKeywords() { } /** - * Get the caseIgnored 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. + * 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 ignoreCase value. */ @Generated - public Boolean isCaseIgnored() { - return this.caseIgnored; + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored 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. + * 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 ignoreCase the ignoreCase value to set. * @return the KeywordMarkerTokenFilter object itself. */ @Generated - public KeywordMarkerTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + public KeywordMarkerTokenFilter setIgnoreCase(Boolean ignoreCase) { + this.ignoreCase = ignoreCase; return this; } @@ -106,13 +115,13 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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(); } /** * Reads an instance of KeywordMarkerTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeywordMarkerTokenFilter if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -122,48 +131,30 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KeywordMarkerTokenFilter deserializedKeywordMarkerTokenFilter + = new KeywordMarkerTokenFilter(name, keywords); + deserializedKeywordMarkerTokenFilter.odataType = odataType; + deserializedKeywordMarkerTokenFilter.ignoreCase = ignoreCase; + return deserializedKeywordMarkerTokenFilter; }); } } 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 index 71dddbe20485..8e0d371459a8 100644 --- 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 @@ -1,82 +1,121 @@ // 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.indexes.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.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. + * 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()); + /* + * The discriminator for derived types. + */ + @Generated + private String odataType = "#Microsoft.Azure.Search.KeywordTokenizer"; - this.v1Tokenizer = null; - this.v2Tokenizer = v2Tokenizer; - } + /* + * The read buffer size in bytes. Default is 256. + */ + @Generated + private Integer bufferSize; /** - * Constructor of {@link KeywordTokenizer}. + * Creates an instance of KeywordTokenizer class. * - * @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. + * @param name the name value to set. */ + @Generated public KeywordTokenizer(String name) { super(name); + } - this.v1Tokenizer = null; - this.v2Tokenizer = new KeywordTokenizerV2(name); + /** + * Get the odataType property: The discriminator for derived types. + * + * @return the odataType value. + */ + @Generated + @Override + public String getOdataType() { + return this.odataType; } /** - * 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. + * Get the bufferSize property: The read buffer size in bytes. Default is 256. * - * @return the maxTokenLength value. + * @return the bufferSize value. */ - public Integer getMaxTokenLength() { - return (v1Tokenizer != null) ? v1Tokenizer.getBufferSize() : v2Tokenizer.getMaxTokenLength(); + @Generated + public Integer getBufferSize() { + return this.bufferSize; } /** - * 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. + * Set the bufferSize property: The read buffer size in bytes. Default is 256. * - * @param maxTokenLength the maxTokenLength value to set. - * @return the KeywordTokenizerV2 object itself. + * @param bufferSize the bufferSize value to set. + * @return the KeywordTokenizer object itself. */ - public KeywordTokenizer setMaxTokenLength(Integer maxTokenLength) { - if (v1Tokenizer != null) { - v1Tokenizer.setBufferSize(maxTokenLength); - } else { - v2Tokenizer.setMaxTokenLength(maxTokenLength); - } + @Generated + public KeywordTokenizer setBufferSize(Integer bufferSize) { + this.bufferSize = bufferSize; return this; } + /** + * {@inheritDoc} + */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Tokenizer != null) ? v1Tokenizer.toJson(jsonWriter) : v2Tokenizer.toJson(jsonWriter); + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeStringField("@odata.type", this.odataType); + jsonWriter.writeNumberField("bufferSize", this.bufferSize); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of KeywordTokenizer from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of KeywordTokenizer 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 KeywordTokenizer. + */ + @Generated + public static KeywordTokenizer fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + 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(); + } else if ("@odata.type".equals(fieldName)) { + odataType = reader.getString(); + } else if ("bufferSize".equals(fieldName)) { + bufferSize = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + KeywordTokenizer deserializedKeywordTokenizer = new KeywordTokenizer(name); + deserializedKeywordTokenizer.odataType = odataType; + deserializedKeywordTokenizer.bufferSize = bufferSize; + return deserializedKeywordTokenizer; + }); } } 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/indexes/models/KeywordTokenizerV2.java similarity index 80% 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/indexes/models/KeywordTokenizerV2.java index 3e845b8fbb86..58694a7ef779 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/indexes/models/KeywordTokenizerV2.java @@ -1,17 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.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; /** @@ -19,8 +15,9 @@ */ @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"; @@ -34,7 +31,7 @@ public final class KeywordTokenizerV2 extends LexicalTokenizer { /** * Creates an instance of KeywordTokenizerV2 class. - * + * * @param name the name value to set. */ @Generated @@ -43,8 +40,8 @@ public KeywordTokenizerV2(String 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 @@ -56,7 +53,7 @@ public String getOdataType() { /** * 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. */ @Generated @@ -67,7 +64,7 @@ public Integer 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. */ @@ -92,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KeywordTokenizerV2 from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KeywordTokenizerV2 if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -102,17 +99,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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)) { @@ -121,14 +115,10 @@ public static KeywordTokenizerV2 fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - KeywordTokenizerV2 deserializedKeywordTokenizerV2 = new KeywordTokenizerV2(name); - deserializedKeywordTokenizerV2.odataType = odataType; - deserializedKeywordTokenizerV2.maxTokenLength = maxTokenLength; - - return deserializedKeywordTokenizerV2; - } - throw new IllegalStateException("Missing required property: name"); + KeywordTokenizerV2 deserializedKeywordTokenizerV2 = new KeywordTokenizerV2(name); + deserializedKeywordTokenizerV2.odataType = odataType; + deserializedKeywordTokenizerV2.maxTokenLength = maxTokenLength; + return deserializedKeywordTokenizerV2; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBase.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBase.java index 6a2f52a93ec8..ef6bb07185a9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBase.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBase.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,23 +9,26 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode; +import com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort; import java.io.IOException; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; /** - * The KnowledgeBase model. + * Represents a knowledge base definition. */ @Fluent public final class KnowledgeBase implements JsonSerializable { + /* - * The name of the knowledge knowledge base. + * The name of the knowledge base. */ @Generated private final String name; /* - * The knowledgeSources property. + * Knowledge sources referenced by this knowledge base. */ @Generated private final List knowledgeSources; @@ -40,13 +40,13 @@ public final class KnowledgeBase implements JsonSerializable { private List models; /* - * The retrievalReasoningEffort property. + * The retrieval reasoning effort configuration. */ @Generated private KnowledgeRetrievalReasoningEffort retrievalReasoningEffort; /* - * The output configuration for this retrieval. + * The output mode for the knowledge base. */ @Generated private KnowledgeRetrievalOutputMode outputMode; @@ -58,13 +58,7 @@ public final class KnowledgeBase implements JsonSerializable { 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 knowledge base definition when you want full assurance that no one, not even - * Microsoft, can decrypt them. Once you have encrypted your knowledge base definition, it will always remain - * encrypted. The search service will ignore attempts to set this property to null. You can change this property as - * needed if you want to rotate your encryption key; Your knowledge base 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. */ @Generated private SearchResourceEncryptionKey encryptionKey; @@ -76,20 +70,31 @@ public final class KnowledgeBase implements JsonSerializable { private String description; /* - * Instructions considered by the knowledge knowledge base when developing query plan. + * Instructions considered by the knowledge base when developing query plan. */ @Generated private String retrievalInstructions; /* - * Instructions considered by the knowledge knowledge base when generating answers. + * Instructions considered by the knowledge base when generating answers. */ @Generated private String answerInstructions; /** * Creates an instance of KnowledgeBase class. - * + * + * @param name the name value to set. + * @param knowledgeSources the knowledgeSources value to set. + */ + public KnowledgeBase(String name, KnowledgeSourceReference... knowledgeSources) { + this.name = name; + this.knowledgeSources = (knowledgeSources == null) ? null : Arrays.asList(knowledgeSources); + } + + /** + * Creates an instance of KnowledgeBase class. + * * @param name the name value to set. * @param knowledgeSources the knowledgeSources value to set. */ @@ -100,8 +105,8 @@ public KnowledgeBase(String name, List knowledgeSource } /** - * Get the name property: The name of the knowledge knowledge base. - * + * Get the name property: The name of the knowledge base. + * * @return the name value. */ @Generated @@ -110,8 +115,8 @@ public String getName() { } /** - * Get the knowledgeSources property: The knowledgeSources property. - * + * Get the knowledgeSources property: Knowledge sources referenced by this knowledge base. + * * @return the knowledgeSources value. */ @Generated @@ -121,7 +126,7 @@ public List getKnowledgeSources() { /** * Get the models property: Contains configuration options on how to connect to AI models. - * + * * @return the models value. */ @Generated @@ -131,7 +136,18 @@ public List getModels() { /** * Set the models property: Contains configuration options on how to connect to AI models. - * + * + * @param models the models value to set. + * @return the KnowledgeBase object itself. + */ + public KnowledgeBase setModels(KnowledgeBaseModel... models) { + this.models = (models == null) ? null : Arrays.asList(models); + return this; + } + + /** + * Set the models property: Contains configuration options on how to connect to AI models. + * * @param models the models value to set. * @return the KnowledgeBase object itself. */ @@ -142,8 +158,8 @@ public KnowledgeBase setModels(List models) { } /** - * Get the retrievalReasoningEffort property: The retrievalReasoningEffort property. - * + * Get the retrievalReasoningEffort property: The retrieval reasoning effort configuration. + * * @return the retrievalReasoningEffort value. */ @Generated @@ -152,8 +168,8 @@ public KnowledgeRetrievalReasoningEffort getRetrievalReasoningEffort() { } /** - * Set the retrievalReasoningEffort property: The retrievalReasoningEffort property. - * + * Set the retrievalReasoningEffort property: The retrieval reasoning effort configuration. + * * @param retrievalReasoningEffort the retrievalReasoningEffort value to set. * @return the KnowledgeBase object itself. */ @@ -164,8 +180,8 @@ public KnowledgeBase setRetrievalReasoningEffort(KnowledgeRetrievalReasoningEffo } /** - * Get the outputMode property: The output configuration for this retrieval. - * + * Get the outputMode property: The output mode for the knowledge base. + * * @return the outputMode value. */ @Generated @@ -174,8 +190,8 @@ public KnowledgeRetrievalOutputMode getOutputMode() { } /** - * Set the outputMode property: The output configuration for this retrieval. - * + * Set the outputMode property: The output mode for the knowledge base. + * * @param outputMode the outputMode value to set. * @return the KnowledgeBase object itself. */ @@ -187,7 +203,7 @@ public KnowledgeBase setOutputMode(KnowledgeRetrievalOutputMode outputMode) { /** * Get the eTag property: The ETag of the knowledge base. - * + * * @return the eTag value. */ @Generated @@ -197,7 +213,7 @@ public String getETag() { /** * Set the eTag property: The ETag of the knowledge base. - * + * * @param eTag the eTag value to set. * @return the KnowledgeBase object itself. */ @@ -208,14 +224,8 @@ public KnowledgeBase 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 knowledge base definition when you want - * full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your knowledge base - * definition, it will always remain encrypted. The search service will ignore attempts to set this property to - * null. You can change this property as needed if you want to rotate your encryption key; Your knowledge base - * 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. - * + * Get the encryptionKey property: A description of an encryption key that you create in Azure Key Vault. + * * @return the encryptionKey value. */ @Generated @@ -224,14 +234,8 @@ public SearchResourceEncryptionKey getEncryptionKey() { } /** - * 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 knowledge base definition when you want - * full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your knowledge base - * definition, it will always remain encrypted. The search service will ignore attempts to set this property to - * null. You can change this property as needed if you want to rotate your encryption key; Your knowledge base - * 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. - * + * Set the encryptionKey property: A description of an encryption key that you create in Azure Key Vault. + * * @param encryptionKey the encryptionKey value to set. * @return the KnowledgeBase object itself. */ @@ -243,7 +247,7 @@ public KnowledgeBase setEncryptionKey(SearchResourceEncryptionKey encryptionKey) /** * Get the description property: The description of the knowledge base. - * + * * @return the description value. */ @Generated @@ -253,7 +257,7 @@ public String getDescription() { /** * Set the description property: The description of the knowledge base. - * + * * @param description the description value to set. * @return the KnowledgeBase object itself. */ @@ -264,9 +268,8 @@ public KnowledgeBase setDescription(String description) { } /** - * Get the retrievalInstructions property: Instructions considered by the knowledge knowledge base when developing - * query plan. - * + * Get the retrievalInstructions property: Instructions considered by the knowledge base when developing query plan. + * * @return the retrievalInstructions value. */ @Generated @@ -275,9 +278,8 @@ public String getRetrievalInstructions() { } /** - * Set the retrievalInstructions property: Instructions considered by the knowledge knowledge base when developing - * query plan. - * + * Set the retrievalInstructions property: Instructions considered by the knowledge base when developing query plan. + * * @param retrievalInstructions the retrievalInstructions value to set. * @return the KnowledgeBase object itself. */ @@ -288,9 +290,8 @@ public KnowledgeBase setRetrievalInstructions(String retrievalInstructions) { } /** - * Get the answerInstructions property: Instructions considered by the knowledge knowledge base when generating - * answers. - * + * Get the answerInstructions property: Instructions considered by the knowledge base when generating answers. + * * @return the answerInstructions value. */ @Generated @@ -299,9 +300,8 @@ public String getAnswerInstructions() { } /** - * Set the answerInstructions property: Instructions considered by the knowledge knowledge base when generating - * answers. - * + * Set the answerInstructions property: Instructions considered by the knowledge base when generating answers. + * * @param answerInstructions the answerInstructions value to set. * @return the KnowledgeBase object itself. */ @@ -334,7 +334,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBase from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBase if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -344,9 +344,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBase fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - boolean knowledgeSourcesFound = false; List knowledgeSources = null; List models = null; KnowledgeRetrievalReasoningEffort retrievalReasoningEffort = null; @@ -359,13 +357,10 @@ public static KnowledgeBase 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 ("knowledgeSources".equals(fieldName)) { knowledgeSources = reader.readArray(reader1 -> KnowledgeSourceReference.fromJson(reader1)); - knowledgeSourcesFound = true; } else if ("models".equals(fieldName)) { models = reader.readArray(reader1 -> KnowledgeBaseModel.fromJson(reader1)); } else if ("retrievalReasoningEffort".equals(fieldName)) { @@ -386,29 +381,16 @@ public static KnowledgeBase fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (nameFound && knowledgeSourcesFound) { - KnowledgeBase deserializedKnowledgeBase = new KnowledgeBase(name, knowledgeSources); - deserializedKnowledgeBase.models = models; - deserializedKnowledgeBase.retrievalReasoningEffort = retrievalReasoningEffort; - deserializedKnowledgeBase.outputMode = outputMode; - deserializedKnowledgeBase.eTag = eTag; - deserializedKnowledgeBase.encryptionKey = encryptionKey; - deserializedKnowledgeBase.description = description; - deserializedKnowledgeBase.retrievalInstructions = retrievalInstructions; - deserializedKnowledgeBase.answerInstructions = answerInstructions; - - return deserializedKnowledgeBase; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!knowledgeSourcesFound) { - missingProperties.add("knowledgeSources"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBase deserializedKnowledgeBase = new KnowledgeBase(name, knowledgeSources); + deserializedKnowledgeBase.models = models; + deserializedKnowledgeBase.retrievalReasoningEffort = retrievalReasoningEffort; + deserializedKnowledgeBase.outputMode = outputMode; + deserializedKnowledgeBase.eTag = eTag; + deserializedKnowledgeBase.encryptionKey = encryptionKey; + deserializedKnowledgeBase.description = description; + deserializedKnowledgeBase.retrievalInstructions = retrievalInstructions; + deserializedKnowledgeBase.answerInstructions = answerInstructions; + return deserializedKnowledgeBase; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseAzureOpenAIModel.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseAzureOpenAIModel.java index 09040f865f29..ad99663321e5 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseAzureOpenAIModel.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseAzureOpenAIModel.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -18,21 +15,22 @@ */ @Immutable public final class KnowledgeBaseAzureOpenAIModel extends KnowledgeBaseModel { + /* - * The type of AI model. + * The AI model to be used for query planning. */ @Generated private KnowledgeBaseModelKind kind = KnowledgeBaseModelKind.AZURE_OPEN_AI; /* - * Contains the parameters specific to Azure OpenAI model endpoint. + * Azure OpenAI parameters. */ @Generated private final AzureOpenAIVectorizerParameters azureOpenAIParameters; /** * Creates an instance of KnowledgeBaseAzureOpenAIModel class. - * + * * @param azureOpenAIParameters the azureOpenAIParameters value to set. */ @Generated @@ -41,8 +39,8 @@ public KnowledgeBaseAzureOpenAIModel(AzureOpenAIVectorizerParameters azureOpenAI } /** - * Get the kind property: The type of AI model. - * + * Get the kind property: The AI model to be used for query planning. + * * @return the kind value. */ @Generated @@ -52,8 +50,8 @@ public KnowledgeBaseModelKind getKind() { } /** - * Get the azureOpenAIParameters property: Contains the parameters specific to Azure OpenAI model endpoint. - * + * Get the azureOpenAIParameters property: Azure OpenAI parameters. + * * @return the azureOpenAIParameters value. */ @Generated @@ -75,7 +73,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseAzureOpenAIModel from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseAzureOpenAIModel if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -85,30 +83,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseAzureOpenAIModel fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean azureOpenAIParametersFound = false; AzureOpenAIVectorizerParameters azureOpenAIParameters = null; KnowledgeBaseModelKind kind = KnowledgeBaseModelKind.AZURE_OPEN_AI; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("azureOpenAIParameters".equals(fieldName)) { azureOpenAIParameters = AzureOpenAIVectorizerParameters.fromJson(reader); - azureOpenAIParametersFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeBaseModelKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (azureOpenAIParametersFound) { - KnowledgeBaseAzureOpenAIModel deserializedKnowledgeBaseAzureOpenAIModel - = new KnowledgeBaseAzureOpenAIModel(azureOpenAIParameters); - deserializedKnowledgeBaseAzureOpenAIModel.kind = kind; - - return deserializedKnowledgeBaseAzureOpenAIModel; - } - throw new IllegalStateException("Missing required property: azureOpenAIParameters"); + KnowledgeBaseAzureOpenAIModel deserializedKnowledgeBaseAzureOpenAIModel + = new KnowledgeBaseAzureOpenAIModel(azureOpenAIParameters); + deserializedKnowledgeBaseAzureOpenAIModel.kind = kind; + return deserializedKnowledgeBaseAzureOpenAIModel; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModel.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModel.java index a6c72c6f434d..433fda62327f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModel.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModel.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @Immutable public class KnowledgeBaseModel implements JsonSerializable { + /* - * The type of AI model. + * The AI model to be used for query planning. */ @Generated private KnowledgeBaseModelKind kind = KnowledgeBaseModelKind.fromString("KnowledgeBaseModel"); @@ -33,8 +31,8 @@ public KnowledgeBaseModel() { } /** - * Get the kind property: The type of AI model. - * + * Get the kind property: The AI model to be used for query planning. + * * @return the kind value. */ @Generated @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseModel from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseModel if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -66,7 +64,8 @@ public static KnowledgeBaseModel fromJson(JsonReader jsonReader) throws IOExcept return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -94,14 +93,12 @@ static KnowledgeBaseModel fromJsonKnownDiscriminator(JsonReader jsonReader) thro while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kind".equals(fieldName)) { deserializedKnowledgeBaseModel.kind = KnowledgeBaseModelKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedKnowledgeBaseModel; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModelKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModelKind.java index d573f41d6a7c..c47446a0b205 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModelKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModelKind.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The AI model to be used for query planning. */ public final class KnowledgeBaseModelKind extends ExpandableStringEnum { + /** * Use Azure Open AI models for query planning. */ @@ -22,7 +20,7 @@ public final class KnowledgeBaseModelKind extends ExpandableStringEnum { - KnowledgeRetrievalLowReasoningEffort deserializedKnowledgeRetrievalLowReasoningEffort - = new KnowledgeRetrievalLowReasoningEffort(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kind".equals(fieldName)) { - deserializedKnowledgeRetrievalLowReasoningEffort.kind - = KnowledgeRetrievalReasoningEffortKind.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeRetrievalLowReasoningEffort; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalMediumReasoningEffort.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalMediumReasoningEffort.java deleted file mode 100644 index 6b9de6e81dca..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalMediumReasoningEffort.java +++ /dev/null @@ -1,84 +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.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; - -/** - * Run knowledge retrieval with medium reasoning effort. - */ -@Immutable -public final class KnowledgeRetrievalMediumReasoningEffort extends KnowledgeRetrievalReasoningEffort { - /* - * The kind of reasoning effort. - */ - @Generated - private KnowledgeRetrievalReasoningEffortKind kind = KnowledgeRetrievalReasoningEffortKind.MEDIUM; - - /** - * Creates an instance of KnowledgeRetrievalMediumReasoningEffort class. - */ - @Generated - public KnowledgeRetrievalMediumReasoningEffort() { - } - - /** - * Get the kind property: The kind of reasoning effort. - * - * @return the kind value. - */ - @Generated - @Override - public KnowledgeRetrievalReasoningEffortKind getKind() { - return this.kind; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeRetrievalMediumReasoningEffort from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeRetrievalMediumReasoningEffort 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 KnowledgeRetrievalMediumReasoningEffort. - */ - @Generated - public static KnowledgeRetrievalMediumReasoningEffort fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeRetrievalMediumReasoningEffort deserializedKnowledgeRetrievalMediumReasoningEffort - = new KnowledgeRetrievalMediumReasoningEffort(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kind".equals(fieldName)) { - deserializedKnowledgeRetrievalMediumReasoningEffort.kind - = KnowledgeRetrievalReasoningEffortKind.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeRetrievalMediumReasoningEffort; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalMinimalReasoningEffort.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalMinimalReasoningEffort.java deleted file mode 100644 index b4c7f2d44666..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalMinimalReasoningEffort.java +++ /dev/null @@ -1,84 +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.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; - -/** - * Run knowledge retrieval with minimal reasoning effort. - */ -@Immutable -public final class KnowledgeRetrievalMinimalReasoningEffort extends KnowledgeRetrievalReasoningEffort { - /* - * The kind of reasoning effort. - */ - @Generated - private KnowledgeRetrievalReasoningEffortKind kind = KnowledgeRetrievalReasoningEffortKind.MINIMAL; - - /** - * Creates an instance of KnowledgeRetrievalMinimalReasoningEffort class. - */ - @Generated - public KnowledgeRetrievalMinimalReasoningEffort() { - } - - /** - * Get the kind property: The kind of reasoning effort. - * - * @return the kind value. - */ - @Generated - @Override - public KnowledgeRetrievalReasoningEffortKind getKind() { - return this.kind; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeRetrievalMinimalReasoningEffort from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeRetrievalMinimalReasoningEffort 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 KnowledgeRetrievalMinimalReasoningEffort. - */ - @Generated - public static KnowledgeRetrievalMinimalReasoningEffort fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeRetrievalMinimalReasoningEffort deserializedKnowledgeRetrievalMinimalReasoningEffort - = new KnowledgeRetrievalMinimalReasoningEffort(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kind".equals(fieldName)) { - deserializedKnowledgeRetrievalMinimalReasoningEffort.kind - = KnowledgeRetrievalReasoningEffortKind.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeRetrievalMinimalReasoningEffort; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalOutputMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalOutputMode.java deleted file mode 100644 index e18194cdcf30..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalOutputMode.java +++ /dev/null @@ -1,59 +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.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The output configuration for this retrieval. - */ -public final class KnowledgeRetrievalOutputMode extends ExpandableStringEnum { - /** - * Return data from the knowledge sources directly without generative alteration. - */ - @Generated - public static final KnowledgeRetrievalOutputMode EXTRACTIVE_DATA = fromString("extractiveData"); - - /** - * Synthesize an answer for the response payload. - */ - @Generated - public static final KnowledgeRetrievalOutputMode ANSWER_SYNTHESIS = fromString("answerSynthesis"); - - /** - * Creates a new instance of KnowledgeRetrievalOutputMode value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KnowledgeRetrievalOutputMode() { - } - - /** - * Creates or finds a KnowledgeRetrievalOutputMode from its string representation. - * - * @param name a name to look for. - * @return the corresponding KnowledgeRetrievalOutputMode. - */ - @Generated - public static KnowledgeRetrievalOutputMode fromString(String name) { - return fromString(name, KnowledgeRetrievalOutputMode.class); - } - - /** - * Gets known KnowledgeRetrievalOutputMode values. - * - * @return known KnowledgeRetrievalOutputMode values. - */ - @Generated - public static Collection values() { - return values(KnowledgeRetrievalOutputMode.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalReasoningEffort.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalReasoningEffort.java deleted file mode 100644 index 7f0a6af4cc29..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalReasoningEffort.java +++ /dev/null @@ -1,115 +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.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; - -/** - * The KnowledgeRetrievalReasoningEffort model. - */ -@Immutable -public class KnowledgeRetrievalReasoningEffort implements JsonSerializable { - /* - * The kind of reasoning effort. - */ - @Generated - private KnowledgeRetrievalReasoningEffortKind kind - = KnowledgeRetrievalReasoningEffortKind.fromString("KnowledgeRetrievalReasoningEffort"); - - /** - * Creates an instance of KnowledgeRetrievalReasoningEffort class. - */ - @Generated - public KnowledgeRetrievalReasoningEffort() { - } - - /** - * Get the kind property: The kind of reasoning effort. - * - * @return the kind value. - */ - @Generated - public KnowledgeRetrievalReasoningEffortKind getKind() { - return this.kind; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeRetrievalReasoningEffort from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeRetrievalReasoningEffort 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 KnowledgeRetrievalReasoningEffort. - */ - @Generated - public static KnowledgeRetrievalReasoningEffort fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String discriminatorValue = null; - try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading - while (readerToUse.nextToken() != JsonToken.END_OBJECT) { - String fieldName = readerToUse.getFieldName(); - readerToUse.nextToken(); - if ("kind".equals(fieldName)) { - discriminatorValue = readerToUse.getString(); - break; - } else { - readerToUse.skipChildren(); - } - } - // Use the discriminator value to determine which subtype should be deserialized. - if ("minimal".equals(discriminatorValue)) { - return KnowledgeRetrievalMinimalReasoningEffort.fromJson(readerToUse.reset()); - } else if ("low".equals(discriminatorValue)) { - return KnowledgeRetrievalLowReasoningEffort.fromJson(readerToUse.reset()); - } else if ("medium".equals(discriminatorValue)) { - return KnowledgeRetrievalMediumReasoningEffort.fromJson(readerToUse.reset()); - } else { - return fromJsonKnownDiscriminator(readerToUse.reset()); - } - } - }); - } - - @Generated - static KnowledgeRetrievalReasoningEffort fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeRetrievalReasoningEffort deserializedKnowledgeRetrievalReasoningEffort - = new KnowledgeRetrievalReasoningEffort(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("kind".equals(fieldName)) { - deserializedKnowledgeRetrievalReasoningEffort.kind - = KnowledgeRetrievalReasoningEffortKind.fromString(reader.getString()); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeRetrievalReasoningEffort; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalReasoningEffortKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalReasoningEffortKind.java deleted file mode 100644 index ec62878bf8ae..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeRetrievalReasoningEffortKind.java +++ /dev/null @@ -1,66 +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.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The amount of effort to use during retrieval. - */ -public final class KnowledgeRetrievalReasoningEffortKind - extends ExpandableStringEnum { - /** - * Does not perform any source selections, query planning, or iterative search. - */ - @Generated - public static final KnowledgeRetrievalReasoningEffortKind MINIMAL = fromString("minimal"); - - /** - * Use low reasoning during retrieval. - */ - @Generated - public static final KnowledgeRetrievalReasoningEffortKind LOW = fromString("low"); - - /** - * Use a moderate amount of reasoning during retrieval. - */ - @Generated - public static final KnowledgeRetrievalReasoningEffortKind MEDIUM = fromString("medium"); - - /** - * Creates a new instance of KnowledgeRetrievalReasoningEffortKind value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KnowledgeRetrievalReasoningEffortKind() { - } - - /** - * Creates or finds a KnowledgeRetrievalReasoningEffortKind from its string representation. - * - * @param name a name to look for. - * @return the corresponding KnowledgeRetrievalReasoningEffortKind. - */ - @Generated - public static KnowledgeRetrievalReasoningEffortKind fromString(String name) { - return fromString(name, KnowledgeRetrievalReasoningEffortKind.class); - } - - /** - * Gets known KnowledgeRetrievalReasoningEffortKind values. - * - * @return known KnowledgeRetrievalReasoningEffortKind values. - */ - @Generated - public static Collection values() { - return values(KnowledgeRetrievalReasoningEffortKind.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSource.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSource.java index 8019a7e90870..64a83f4c6fec 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSource.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSource.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public class KnowledgeSource implements JsonSerializable { + /* * The type of the knowledge source. */ @@ -38,17 +36,17 @@ public class KnowledgeSource implements JsonSerializable { private String description; /* - * The ETag of the knowledge base. + * The ETag of the knowledge 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 knowledge base definition when you want full assurance that no one, not even - * Microsoft, can decrypt them. Once you have encrypted your knowledge base definition, it will always remain + * level of encryption-at-rest for your knowledge source definition when you want full assurance that no one, not + * even Microsoft, can decrypt them. Once you have encrypted your knowledge source definition, it will always remain * encrypted. The search service will ignore attempts to set this property to null. You can change this property as - * needed if you want to rotate your encryption key; Your knowledge base definition will be unaffected. Encryption + * needed if you want to rotate your encryption key; Your knowledge source definition will be unaffected. Encryption * with customer-managed keys is not available for free search services, and is only available for paid services * created on or after January 1, 2019. */ @@ -57,7 +55,7 @@ public class KnowledgeSource implements JsonSerializable { /** * Creates an instance of KnowledgeSource class. - * + * * @param name the name value to set. */ @Generated @@ -67,7 +65,7 @@ public KnowledgeSource(String name) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -77,7 +75,7 @@ public KnowledgeSourceKind getKind() { /** * Get the name property: The name of the knowledge source. - * + * * @return the name value. */ @Generated @@ -87,7 +85,7 @@ public String getName() { /** * Get the description property: Optional user-defined description. - * + * * @return the description value. */ @Generated @@ -97,7 +95,7 @@ public String getDescription() { /** * Set the description property: Optional user-defined description. - * + * * @param description the description value to set. * @return the KnowledgeSource object itself. */ @@ -108,8 +106,8 @@ public KnowledgeSource setDescription(String description) { } /** - * Get the eTag property: The ETag of the knowledge base. - * + * Get the eTag property: The ETag of the knowledge source. + * * @return the eTag value. */ @Generated @@ -118,8 +116,8 @@ public String getETag() { } /** - * Set the eTag property: The ETag of the knowledge base. - * + * Set the eTag property: The ETag of the knowledge source. + * * @param eTag the eTag value to set. * @return the KnowledgeSource object itself. */ @@ -131,13 +129,13 @@ public KnowledgeSource 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 knowledge base definition when you want - * full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your knowledge base + * is used to provide an additional level of encryption-at-rest for your knowledge source definition when you want + * full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your knowledge source * definition, it will always remain encrypted. The search service will ignore attempts to set this property to - * null. You can change this property as needed if you want to rotate your encryption key; Your knowledge base + * null. You can change this property as needed if you want to rotate your encryption key; Your knowledge source * definition will be unaffected. Encryption with customer-managed keys is not available for free search services, * and is only available for paid services created on or after January 1, 2019. - * + * * @return the encryptionKey value. */ @Generated @@ -147,13 +145,13 @@ public SearchResourceEncryptionKey getEncryptionKey() { /** * 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 knowledge base definition when you want - * full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your knowledge base + * is used to provide an additional level of encryption-at-rest for your knowledge source definition when you want + * full assurance that no one, not even Microsoft, can decrypt them. Once you have encrypted your knowledge source * definition, it will always remain encrypted. The search service will ignore attempts to set this property to - * null. You can change this property as needed if you want to rotate your encryption key; Your knowledge base + * null. You can change this property as needed if you want to rotate your encryption key; Your knowledge source * definition will be unaffected. Encryption with customer-managed keys is not available for free search services, * and is only available for paid services created on or after January 1, 2019. - * + * * @param encryptionKey the encryptionKey value to set. * @return the KnowledgeSource object itself. */ @@ -180,7 +178,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeSource from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeSource if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -192,7 +190,8 @@ public static KnowledgeSource fromJson(JsonReader jsonReader) throws IOException return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -226,7 +225,6 @@ public static KnowledgeSource fromJson(JsonReader jsonReader) throws IOException @Generated static KnowledgeSource fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; KnowledgeSourceKind kind = null; String description = null; @@ -235,10 +233,8 @@ static KnowledgeSource fromJsonKnownDiscriminator(JsonReader jsonReader) throws while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeSourceKind.fromString(reader.getString()); } else if ("description".equals(fieldName)) { @@ -251,16 +247,12 @@ static KnowledgeSource fromJsonKnownDiscriminator(JsonReader jsonReader) throws reader.skipChildren(); } } - if (nameFound) { - KnowledgeSource deserializedKnowledgeSource = new KnowledgeSource(name); - deserializedKnowledgeSource.kind = kind; - deserializedKnowledgeSource.description = description; - deserializedKnowledgeSource.eTag = eTag; - deserializedKnowledgeSource.encryptionKey = encryptionKey; - - return deserializedKnowledgeSource; - } - throw new IllegalStateException("Missing required property: name"); + KnowledgeSource deserializedKnowledgeSource = new KnowledgeSource(name); + deserializedKnowledgeSource.kind = kind; + deserializedKnowledgeSource.description = description; + deserializedKnowledgeSource.eTag = eTag; + deserializedKnowledgeSource.encryptionKey = encryptionKey; + return deserializedKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceContentExtractionMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceContentExtractionMode.java index c38de7f7804b..dc286fddb76e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceContentExtractionMode.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceContentExtractionMode.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class KnowledgeSourceContentExtractionMode extends ExpandableStringEnum { + /** * Extracts only essential metadata while deferring most content processing. */ @@ -29,7 +27,7 @@ public final class KnowledgeSourceContentExtractionMode /** * Creates a new instance of KnowledgeSourceContentExtractionMode value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -39,7 +37,7 @@ public KnowledgeSourceContentExtractionMode() { /** * Creates or finds a KnowledgeSourceContentExtractionMode from its string representation. - * + * * @param name a name to look for. * @return the corresponding KnowledgeSourceContentExtractionMode. */ @@ -50,7 +48,7 @@ public static KnowledgeSourceContentExtractionMode fromString(String name) { /** * Gets known KnowledgeSourceContentExtractionMode values. - * + * * @return known KnowledgeSourceContentExtractionMode values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionPermissionOption.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionPermissionOption.java index d46d5c3c2e5f..9ae769dcebbc 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionPermissionOption.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionPermissionOption.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -11,10 +8,11 @@ import java.util.Collection; /** - * Defines values for KnowledgeSourceIngestionPermissionOption. + * Permission types to ingest together with document content. */ public final class KnowledgeSourceIngestionPermissionOption extends ExpandableStringEnum { + /** * Ingest explicit user identifiers alongside document content. */ @@ -35,7 +33,7 @@ public final class KnowledgeSourceIngestionPermissionOption /** * Creates a new instance of KnowledgeSourceIngestionPermissionOption value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -45,7 +43,7 @@ public KnowledgeSourceIngestionPermissionOption() { /** * Creates or finds a KnowledgeSourceIngestionPermissionOption from its string representation. - * + * * @param name a name to look for. * @return the corresponding KnowledgeSourceIngestionPermissionOption. */ @@ -56,7 +54,7 @@ public static KnowledgeSourceIngestionPermissionOption fromString(String name) { /** * Gets known KnowledgeSourceIngestionPermissionOption values. - * + * * @return known KnowledgeSourceIngestionPermissionOption values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceKind.java index 6dd717869397..a6c94423e227 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceKind.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,45 +11,46 @@ * The kind of the knowledge source. */ public final class KnowledgeSourceKind extends ExpandableStringEnum { + /** - * A knowledge source that retrieves data from a Search Index. + * A knowledge source that reads data from a Search Index. */ @Generated public static final KnowledgeSourceKind SEARCH_INDEX = fromString("searchIndex"); /** - * A knowledge source that retrieves and ingests data from Azure Blob Storage to a Search Index. + * A knowledge source that read and ingest data from Azure Blob Storage to a Search Index. */ @Generated public static final KnowledgeSourceKind AZURE_BLOB = fromString("azureBlob"); /** - * A knowledge source that retrieves data from the web. + * A knowledge source that reads data from indexed SharePoint. */ @Generated - public static final KnowledgeSourceKind WEB = fromString("web"); + public static final KnowledgeSourceKind INDEXED_SHARE_POINT = fromString("indexedSharePoint"); /** - * A knowledge source that retrieves data from a remote SharePoint endpoint. + * A knowledge source that reads data from indexed OneLake. */ @Generated - public static final KnowledgeSourceKind REMOTE_SHARE_POINT = fromString("remoteSharePoint"); + public static final KnowledgeSourceKind INDEXED_ONE_LAKE = fromString("indexedOneLake"); /** - * A knowledge source that retrieves and ingests data from SharePoint to a Search Index. + * A knowledge source that reads data from the web. */ @Generated - public static final KnowledgeSourceKind INDEXED_SHARE_POINT = fromString("indexedSharePoint"); + public static final KnowledgeSourceKind WEB = fromString("web"); /** - * A knowledge source that retrieves and ingests data from OneLake to a Search Index. + * A knowledge source that reads data from remote SharePoint. */ @Generated - public static final KnowledgeSourceKind INDEXED_ONE_LAKE = fromString("indexedOneLake"); + public static final KnowledgeSourceKind REMOTE_SHARE_POINT = fromString("remoteSharePoint"); /** * Creates a new instance of KnowledgeSourceKind value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -62,7 +60,7 @@ public KnowledgeSourceKind() { /** * Creates or finds a KnowledgeSourceKind from its string representation. - * + * * @param name a name to look for. * @return the corresponding KnowledgeSourceKind. */ @@ -73,7 +71,7 @@ public static KnowledgeSourceKind fromString(String name) { /** * Gets known KnowledgeSourceKind values. - * + * * @return known KnowledgeSourceKind values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceReference.java index 352b5ca9a6e3..77496d74439e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceReference.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,10 +12,11 @@ import java.io.IOException; /** - * The KnowledgeSourceReference model. + * Reference to a knowledge source. */ @Immutable public final class KnowledgeSourceReference implements JsonSerializable { + /* * The name of the knowledge source. */ @@ -27,7 +25,7 @@ public final class KnowledgeSourceReference implements JsonSerializable { - boolean nameFound = false; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else { reader.skipChildren(); } } - if (nameFound) { - return new KnowledgeSourceReference(name); - } - throw new IllegalStateException("Missing required property: name"); + return new KnowledgeSourceReference(name); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceSynchronizationStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceSynchronizationStatus.java index f104dcf102bd..77a46e030031 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceSynchronizationStatus.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceSynchronizationStatus.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class KnowledgeSourceSynchronizationStatus extends ExpandableStringEnum { + /** * The knowledge source is being provisioned. */ @@ -35,7 +33,7 @@ public final class KnowledgeSourceSynchronizationStatus /** * Creates a new instance of KnowledgeSourceSynchronizationStatus value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -45,7 +43,7 @@ public KnowledgeSourceSynchronizationStatus() { /** * Creates or finds a KnowledgeSourceSynchronizationStatus from its string representation. - * + * * @param name a name to look for. * @return the corresponding KnowledgeSourceSynchronizationStatus. */ @@ -56,7 +54,7 @@ public static KnowledgeSourceSynchronizationStatus fromString(String name) { /** * Gets known KnowledgeSourceSynchronizationStatus values. - * + * * @return known KnowledgeSourceSynchronizationStatus values. */ @Generated 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/indexes/models/LanguageDetectionSkill.java index 11e4a6b87741..5d7656af0015 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/indexes/models/LanguageDetectionSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -21,8 +17,9 @@ */ @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"; @@ -42,7 +39,7 @@ public final class LanguageDetectionSkill extends SearchIndexerSkill { /** * Creates an instance of LanguageDetectionSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -52,8 +49,8 @@ public LanguageDetectionSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -185,13 +180,10 @@ public static LanguageDetectionSkill fromJson(JsonReader jsonReader) throws IOEx 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)) { @@ -208,27 +200,14 @@ 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/indexes/models/LengthTokenFilter.java index fef88729a404..78c9c3d3f218 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/indexes/models/LengthTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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"; @@ -38,7 +36,7 @@ public final class LengthTokenFilter extends TokenFilter { /** * Creates an instance of LengthTokenFilter class. - * + * * @param name the name value to set. */ @Generated @@ -47,8 +45,8 @@ public LengthTokenFilter(String 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 @@ -60,7 +58,7 @@ public String getOdataType() { /** * 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 @@ -71,7 +69,7 @@ public Integer getMinLength() { /** * 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. */ @@ -83,7 +81,7 @@ public LengthTokenFilter setMinLength(Integer minLength) { /** * Get the maxLength property: The maximum length in characters. Default and maximum is 300. - * + * * @return the maxLength value. */ @Generated @@ -93,7 +91,7 @@ public Integer getMaxLength() { /** * Set the maxLength property: The maximum length in characters. Default and maximum is 300. - * + * * @param maxLength the maxLength value to set. * @return the LengthTokenFilter object itself. */ @@ -119,7 +117,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LengthTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LengthTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -129,7 +127,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -137,10 +134,8 @@ public static LengthTokenFilter fromJson(JsonReader jsonReader) throws IOExcepti 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 ("min".equals(fieldName)) { @@ -151,15 +146,11 @@ 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; - - return deserializedLengthTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + LengthTokenFilter deserializedLengthTokenFilter = new LengthTokenFilter(name); + deserializedLengthTokenFilter.odataType = odataType; + deserializedLengthTokenFilter.minLength = minLength; + deserializedLengthTokenFilter.maxLength = maxLength; + 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/indexes/models/LexicalAnalyzer.java index 81d46740f3b2..fe218462729d 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/indexes/models/LexicalAnalyzer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @Immutable public class LexicalAnalyzer implements JsonSerializable { + /* - * A URI fragment specifying the type of analyzer. + * The discriminator for derived types. */ @Generated private String odataType = "LexicalAnalyzer"; @@ -34,7 +32,7 @@ public class LexicalAnalyzer implements JsonSerializable { /** * Creates an instance of LexicalAnalyzer class. - * + * * @param name the name value to set. */ @Generated @@ -43,8 +41,8 @@ public LexicalAnalyzer(String 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 @@ -55,7 +53,7 @@ public String getOdataType() { /** * 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 @@ -77,7 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LexicalAnalyzer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LexicalAnalyzer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -89,7 +87,8 @@ public static LexicalAnalyzer fromJson(JsonReader jsonReader) throws IOException return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -119,29 +118,22 @@ 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) { 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 { reader.skipChildren(); } } - if (nameFound) { - LexicalAnalyzer deserializedLexicalAnalyzer = new LexicalAnalyzer(name); - deserializedLexicalAnalyzer.odataType = odataType; - - return deserializedLexicalAnalyzer; - } - throw new IllegalStateException("Missing required property: name"); + LexicalAnalyzer deserializedLexicalAnalyzer = new LexicalAnalyzer(name); + deserializedLexicalAnalyzer.odataType = odataType; + 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/indexes/models/LexicalAnalyzerName.java index 2c23d6417cfc..b3e2dc7f4d32 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/indexes/models/LexicalAnalyzerName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Defines the names of all text analyzers supported by the search engine. */ public final class LexicalAnalyzerName extends ExpandableStringEnum { + /** * Microsoft analyzer for Arabic. */ @@ -345,7 +343,7 @@ public final class LexicalAnalyzerName extends ExpandableStringEnum { + /* - * 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; /** * Creates an instance of LexicalNormalizer class. - * + * * @param name the name value to set. */ @Generated @@ -44,8 +41,8 @@ public LexicalNormalizer(String 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 @@ -54,10 +51,9 @@ public String getOdataType() { } /** - * 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 @@ -79,7 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LexicalNormalizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LexicalNormalizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -91,7 +87,8 @@ public static LexicalNormalizer fromJson(JsonReader jsonReader) throws IOExcepti return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -115,29 +112,22 @@ 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) { 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 { reader.skipChildren(); } } - if (nameFound) { - LexicalNormalizer deserializedLexicalNormalizer = new LexicalNormalizer(name); - deserializedLexicalNormalizer.odataType = odataType; - - return deserializedLexicalNormalizer; - } - throw new IllegalStateException("Missing required property: name"); + LexicalNormalizer deserializedLexicalNormalizer = new LexicalNormalizer(name); + deserializedLexicalNormalizer.odataType = odataType; + 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/indexes/models/LexicalNormalizerName.java index 1ed7a558b1ec..f561c4d2da5c 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/indexes/models/LexicalNormalizerName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Defines the names of all text normalizers supported by the search engine. */ 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 @@ -52,7 +50,7 @@ public final class LexicalNormalizerName extends ExpandableStringEnum { + /* - * A URI fragment specifying the type of tokenizer. + * The discriminator for derived types. */ @Generated private String odataType = "LexicalTokenizer"; @@ -38,7 +32,7 @@ public class LexicalTokenizer implements JsonSerializable { /** * Creates an instance of LexicalTokenizer class. - * + * * @param name the name value to set. */ @Generated @@ -47,8 +41,8 @@ public LexicalTokenizer(String 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 @@ -59,7 +53,7 @@ public String getOdataType() { /** * 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 @@ -81,7 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LexicalTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LexicalTokenizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -93,7 +87,8 @@ public static LexicalTokenizer fromJson(JsonReader jsonReader) throws IOExceptio return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -109,6 +104,8 @@ public static LexicalTokenizer fromJson(JsonReader jsonReader) throws IOExceptio return ClassicTokenizer.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.EdgeNGramTokenizer".equals(discriminatorValue)) { return EdgeNGramTokenizer.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Azure.Search.KeywordTokenizer".equals(discriminatorValue)) { + return KeywordTokenizer.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.KeywordTokenizerV2".equals(discriminatorValue)) { return KeywordTokenizerV2.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.MicrosoftLanguageTokenizer".equals(discriminatorValue)) { @@ -117,18 +114,16 @@ 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.StandardTokenizer".equals(discriminatorValue)) { + return LuceneStandardTokenizer.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()); } @@ -139,29 +134,22 @@ 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) { 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 { reader.skipChildren(); } } - if (nameFound) { - LexicalTokenizer deserializedLexicalTokenizer = new LexicalTokenizer(name); - deserializedLexicalTokenizer.odataType = odataType; - - return deserializedLexicalTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + LexicalTokenizer deserializedLexicalTokenizer = new LexicalTokenizer(name); + deserializedLexicalTokenizer.odataType = odataType; + 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/indexes/models/LexicalTokenizerName.java index 4314453c16c8..5f49fc2afa5d 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/indexes/models/LexicalTokenizerName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Defines the names of all tokenizers supported by the search engine. */ public final class LexicalTokenizerName extends ExpandableStringEnum { + /** * 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. @@ -106,7 +104,7 @@ public final class LexicalTokenizerName extends ExpandableStringEnum { - 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/indexes/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/indexes/models/ListDataSourcesResult.java index 8bdd3b16a3bd..d06dcf6e5e6d 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/indexes/models/ListDataSourcesResult.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -12,7 +9,6 @@ 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; @@ -21,25 +17,23 @@ */ @Immutable public final class ListDataSourcesResult implements JsonSerializable { + /* * The datasources in the Search service. */ @Generated - private final List dataSources; + private List dataSources; /** * Creates an instance of ListDataSourcesResult class. - * - * @param dataSources the dataSources value to set. */ @Generated - public ListDataSourcesResult(List dataSources) { - this.dataSources = dataSources; + private ListDataSourcesResult() { } /** * Get the dataSources property: The datasources in the Search service. - * + * * @return the dataSources value. */ @Generated @@ -59,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ListDataSourcesResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ListDataSourcesResult if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -69,23 +63,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ListDataSourcesResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean dataSourcesFound = false; - List dataSources = null; + ListDataSourcesResult deserializedListDataSourcesResult = new ListDataSourcesResult(); 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; + List dataSources + = reader.readArray(reader1 -> SearchIndexerDataSourceConnection.fromJson(reader1)); + deserializedListDataSourcesResult.dataSources = dataSources; } else { reader.skipChildren(); } } - if (dataSourcesFound) { - return new ListDataSourcesResult(dataSources); - } - throw new IllegalStateException("Missing required property: value"); + return deserializedListDataSourcesResult; }); } } 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/indexes/models/ListIndexersResult.java similarity index 70% 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/indexes/models/ListIndexersResult.java index c368b5422617..2e86377be6a9 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/indexes/models/ListIndexersResult.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -12,7 +9,6 @@ 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; @@ -21,25 +17,23 @@ */ @Immutable public final class ListIndexersResult implements JsonSerializable { + /* * The indexers in the Search service. */ @Generated - private final List indexers; + private List indexers; /** * Creates an instance of ListIndexersResult class. - * - * @param indexers the indexers value to set. */ @Generated - public ListIndexersResult(List indexers) { - this.indexers = indexers; + private ListIndexersResult() { } /** * Get the indexers property: The indexers in the Search service. - * + * * @return the indexers value. */ @Generated @@ -59,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ListIndexersResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ListIndexersResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -69,23 +63,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ListIndexersResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean indexersFound = false; - List indexers = null; + ListIndexersResult deserializedListIndexersResult = new ListIndexersResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - indexers = reader.readArray(reader1 -> SearchIndexer.fromJson(reader1)); - indexersFound = true; + List indexers = reader.readArray(reader1 -> SearchIndexer.fromJson(reader1)); + deserializedListIndexersResult.indexers = indexers; } else { reader.skipChildren(); } } - if (indexersFound) { - return new ListIndexersResult(indexers); - } - throw new IllegalStateException("Missing required property: value"); + return deserializedListIndexersResult; }); } } 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/indexes/models/ListSkillsetsResult.java similarity index 69% 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/indexes/models/ListSkillsetsResult.java index a24fc44758cc..5d90ad0a0c50 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/indexes/models/ListSkillsetsResult.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -12,7 +9,6 @@ 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; @@ -21,25 +17,23 @@ */ @Immutable public final class ListSkillsetsResult implements JsonSerializable { + /* * The skillsets defined in the Search service. */ @Generated - private final List skillsets; + private List skillsets; /** * Creates an instance of ListSkillsetsResult class. - * - * @param skillsets the skillsets value to set. */ @Generated - public ListSkillsetsResult(List skillsets) { - this.skillsets = skillsets; + private ListSkillsetsResult() { } /** * Get the skillsets property: The skillsets defined in the Search service. - * + * * @return the skillsets value. */ @Generated @@ -59,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ListSkillsetsResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ListSkillsetsResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -69,23 +63,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ListSkillsetsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean skillsetsFound = false; - List skillsets = null; + ListSkillsetsResult deserializedListSkillsetsResult = new ListSkillsetsResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - skillsets = reader.readArray(reader1 -> SearchIndexerSkillset.fromJson(reader1)); - skillsetsFound = true; + List skillsets + = reader.readArray(reader1 -> SearchIndexerSkillset.fromJson(reader1)); + deserializedListSkillsetsResult.skillsets = skillsets; } else { reader.skipChildren(); } } - if (skillsetsFound) { - return new ListSkillsetsResult(skillsets); - } - throw new IllegalStateException("Missing required property: value"); + return deserializedListSkillsetsResult; }); } } 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/indexes/models/ListSynonymMapsResult.java similarity index 70% 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/indexes/models/ListSynonymMapsResult.java index bd75d6171330..e8b4b7981fa3 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/indexes/models/ListSynonymMapsResult.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -12,7 +9,6 @@ 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; @@ -21,25 +17,23 @@ */ @Immutable public final class ListSynonymMapsResult implements JsonSerializable { + /* * The synonym maps in the Search service. */ @Generated - private final List synonymMaps; + private List synonymMaps; /** * Creates an instance of ListSynonymMapsResult class. - * - * @param synonymMaps the synonymMaps value to set. */ @Generated - public ListSynonymMapsResult(List synonymMaps) { - this.synonymMaps = synonymMaps; + private ListSynonymMapsResult() { } /** * Get the synonymMaps property: The synonym maps in the Search service. - * + * * @return the synonymMaps value. */ @Generated @@ -59,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ListSynonymMapsResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ListSynonymMapsResult if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -69,23 +63,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static ListSynonymMapsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean synonymMapsFound = false; - List synonymMaps = null; + ListSynonymMapsResult deserializedListSynonymMapsResult = new ListSynonymMapsResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - synonymMaps = reader.readArray(reader1 -> SynonymMap.fromJson(reader1)); - synonymMapsFound = true; + List synonymMaps = reader.readArray(reader1 -> SynonymMap.fromJson(reader1)); + deserializedListSynonymMapsResult.synonymMaps = synonymMaps; } else { reader.skipChildren(); } } - if (synonymMapsFound) { - return new ListSynonymMapsResult(synonymMaps); - } - throw new IllegalStateException("Missing required property: value"); + return deserializedListSynonymMapsResult; }); } } 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/indexes/models/LuceneStandardAnalyzer.java index edc8d61ee0e8..d079f7eb3b1d 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/indexes/models/LuceneStandardAnalyzer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -21,7 +19,7 @@ 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"; @@ -50,7 +48,7 @@ public LuceneStandardAnalyzer(String 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. */ @@ -94,6 +92,17 @@ 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. + */ + public LuceneStandardAnalyzer setStopwords(String... stopwords) { + this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); + return this; + } + /** * Set the stopwords property: A list of stopwords. * @@ -132,7 +141,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -142,7 +150,6 @@ public static LuceneStandardAnalyzer fromJson(JsonReader jsonReader) throws IOEx 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)) { @@ -153,25 +160,11 @@ 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; + return deserializedLuceneStandardAnalyzer; }); } - - /** - * 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; - } } 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 index dffb6e91ca4f..fe7908e18c06 100644 --- 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 @@ -1,80 +1,123 @@ // 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.indexes.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.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. + * 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()); + /* + * The discriminator for derived types. + */ + @Generated + private String odataType = "#Microsoft.Azure.Search.StandardTokenizer"; - this.v1Tokenizer = null; - this.v2tokenizer = v2tokenizer; - } + /* + * The maximum token length. Default is 255. Tokens longer than the maximum length are split. + */ + @Generated + private Integer maxTokenLength; /** - * Constructor of {@link LuceneStandardTokenizer}. + * Creates an instance of LuceneStandardTokenizer class. * - * @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. + * @param name the name value to set. */ + @Generated public LuceneStandardTokenizer(String name) { super(name); + } - this.v1Tokenizer = null; - this.v2tokenizer = new LuceneStandardTokenizerV2(name); + /** + * Get the odataType property: The discriminator for derived types. + * + * @return the odataType value. + */ + @Generated + @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. + * Get the maxTokenLength property: The maximum token length. Default is 255. Tokens longer than the maximum length + * are split. * * @return the maxTokenLength value. */ + @Generated public Integer getMaxTokenLength() { - return (v1Tokenizer != null) ? v1Tokenizer.getMaxTokenLength() : v2tokenizer.getMaxTokenLength(); + return this.maxTokenLength; } /** - * Set the maxTokenLength property: The maximum token length. Default is - * 255. Tokens longer than the maximum length are split. + * 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. */ + @Generated public LuceneStandardTokenizer setMaxTokenLength(Integer maxTokenLength) { - if (v1Tokenizer != null) { - v1Tokenizer.setMaxTokenLength(maxTokenLength); - } else { - v2tokenizer.setMaxTokenLength(maxTokenLength); - } + this.maxTokenLength = maxTokenLength; return this; } + /** + * {@inheritDoc} + */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Tokenizer != null) ? v1Tokenizer.toJson(jsonWriter) : v2tokenizer.toJson(jsonWriter); + jsonWriter.writeStartObject(); + jsonWriter.writeStringField("name", getName()); + jsonWriter.writeStringField("@odata.type", this.odataType); + jsonWriter.writeNumberField("maxTokenLength", this.maxTokenLength); + return jsonWriter.writeEndObject(); + } + + /** + * Reads an instance of LuceneStandardTokenizer from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of LuceneStandardTokenizer 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 LuceneStandardTokenizer. + */ + @Generated + public static LuceneStandardTokenizer fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + 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(); + } else if ("@odata.type".equals(fieldName)) { + odataType = reader.getString(); + } else if ("maxTokenLength".equals(fieldName)) { + maxTokenLength = reader.getNullable(JsonReader::getInt); + } else { + reader.skipChildren(); + } + } + LuceneStandardTokenizer deserializedLuceneStandardTokenizer = new LuceneStandardTokenizer(name); + deserializedLuceneStandardTokenizer.odataType = odataType; + deserializedLuceneStandardTokenizer.maxTokenLength = maxTokenLength; + return deserializedLuceneStandardTokenizer; + }); } } 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/indexes/models/LuceneStandardTokenizerV2.java similarity index 79% 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/indexes/models/LuceneStandardTokenizerV2.java index 4f30c7b0ab6b..2f8aa2a68bb0 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/indexes/models/LuceneStandardTokenizerV2.java @@ -1,17 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.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; /** @@ -19,8 +15,9 @@ */ @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"; @@ -34,7 +31,7 @@ public final class LuceneStandardTokenizerV2 extends LexicalTokenizer { /** * Creates an instance of LuceneStandardTokenizerV2 class. - * + * * @param name the name value to set. */ @Generated @@ -43,8 +40,8 @@ public LuceneStandardTokenizerV2(String 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 @@ -56,7 +53,7 @@ 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 @@ -67,7 +64,7 @@ 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 LuceneStandardTokenizerV2 object itself. */ @@ -92,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of LuceneStandardTokenizerV2 from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of LuceneStandardTokenizerV2 if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -102,17 +99,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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)) { @@ -121,14 +115,10 @@ public static LuceneStandardTokenizerV2 fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (nameFound) { - LuceneStandardTokenizerV2 deserializedLuceneStandardTokenizerV2 = new LuceneStandardTokenizerV2(name); - deserializedLuceneStandardTokenizerV2.odataType = odataType; - deserializedLuceneStandardTokenizerV2.maxTokenLength = maxTokenLength; - - return deserializedLuceneStandardTokenizerV2; - } - throw new IllegalStateException("Missing required property: name"); + LuceneStandardTokenizerV2 deserializedLuceneStandardTokenizerV2 = new LuceneStandardTokenizerV2(name); + deserializedLuceneStandardTokenizerV2.odataType = odataType; + deserializedLuceneStandardTokenizerV2.maxTokenLength = maxTokenLength; + 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/indexes/models/MagnitudeScoringFunction.java index 679949094c7c..cfef95eaa0ee 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/indexes/models/MagnitudeScoringFunction.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,17 +9,15 @@ 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. */ @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"; @@ -35,7 +30,7 @@ public final class MagnitudeScoringFunction extends ScoringFunction { /** * Creates an instance of MagnitudeScoringFunction class. - * + * * @param fieldName the fieldName value to set. * @param boost the boost value to set. * @param parameters the parameters value to set. @@ -47,9 +42,8 @@ public MagnitudeScoringFunction(String fieldName, double boost, MagnitudeScoring } /** - * 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 @@ -60,7 +54,7 @@ public String getType() { /** * Get the parameters property: Parameter values for the magnitude scoring function. - * + * * @return the parameters value. */ @Generated @@ -95,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of MagnitudeScoringFunction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MagnitudeScoringFunction if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -105,56 +99,33 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String jsonFieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + MagnitudeScoringFunction deserializedMagnitudeScoringFunction + = new MagnitudeScoringFunction(fieldName, boost, parameters); + deserializedMagnitudeScoringFunction.setInterpolation(interpolation); + deserializedMagnitudeScoringFunction.type = type; + 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/indexes/models/MagnitudeScoringParameters.java index 78300f5137ab..2afac00be90d 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/indexes/models/MagnitudeScoringParameters.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,8 +10,6 @@ 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. @@ -79,7 +75,7 @@ public double getBoostingRangeEnd() { * @return the shouldBoostBeyondRangeByConstant value. */ @Generated - public Boolean shouldBoostBeyondRangeByConstant() { + public Boolean isShouldBoostBeyondRangeByConstant() { return this.shouldBoostBeyondRangeByConstant; } @@ -121,9 +117,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { @@ -131,32 +125,18 @@ public static MagnitudeScoringParameters fromJson(JsonReader jsonReader) throws 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/indexes/models/MappingCharFilter.java index 7168aff000f7..c26a24c2ee0f 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/indexes/models/MappingCharFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,7 +9,7 @@ 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; /** @@ -22,8 +19,9 @@ */ @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"; @@ -37,7 +35,18 @@ public final class MappingCharFilter extends CharFilter { /** * Creates an instance of MappingCharFilter class. - * + * + * @param name the name value to set. + * @param mappings the mappings value to set. + */ + public MappingCharFilter(String name, String... mappings) { + super(name); + this.mappings = (mappings == null) ? null : Arrays.asList(mappings); + } + + /** + * Creates an instance of MappingCharFilter class. + * * @param name the name value to set. * @param mappings the mappings value to set. */ @@ -48,8 +57,8 @@ public MappingCharFilter(String name, List 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 @@ -61,7 +70,7 @@ public String getOdataType() { /** * Get the mappings property: A list of mappings of the following format: "a=>b" (all occurrences of the * character "a" will be replaced with character "b"). - * + * * @return the mappings value. */ @Generated @@ -84,7 +93,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of MappingCharFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MappingCharFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -94,43 +103,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + MappingCharFilter deserializedMappingCharFilter = new MappingCharFilter(name, mappings); + deserializedMappingCharFilter.odataType = odataType; + 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/indexes/models/MarkdownHeaderDepth.java index eb500b8923bd..2a68abfcd234 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/indexes/models/MarkdownHeaderDepth.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * 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. */ @@ -53,7 +51,7 @@ public final class MarkdownHeaderDepth 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 @@ -31,7 +29,7 @@ public final class MarkdownParsingSubmode extends ExpandableStringEnum inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -182,13 +177,10 @@ public static MergeSkill 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)) { @@ -205,27 +197,14 @@ 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/indexes/models/MicrosoftLanguageStemmingTokenizer.java index b672e95afd38..cf67a0ed1a0e 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/indexes/models/MicrosoftLanguageStemmingTokenizer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,7 +17,7 @@ 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"; @@ -37,7 +35,7 @@ public final class MicrosoftLanguageStemmingTokenizer extends LexicalTokenizer { * as the indexing tokenizer. Default is false. */ @Generated - private Boolean isSearchTokenizerUsed; + private Boolean isSearchTokenizer; /* * The language to use. The default is English. @@ -56,7 +54,7 @@ public MicrosoftLanguageStemmingTokenizer(String 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. */ @@ -93,26 +91,26 @@ public MicrosoftLanguageStemmingTokenizer setMaxTokenLength(Integer maxTokenLeng } /** - * Get the isSearchTokenizerUsed property: A value indicating how the tokenizer is used. Set to true if used as the + * 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 isSearchTokenizerUsed value. + * @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 + * 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 isSearchTokenizerUsed the isSearchTokenizerUsed value to set. + * @param isSearchTokenizer the isSearchTokenizer value to set. * @return the MicrosoftLanguageStemmingTokenizer object itself. */ @Generated - public MicrosoftLanguageStemmingTokenizer setIsSearchTokenizerUsed(Boolean isSearchTokenizerUsed) { - this.isSearchTokenizerUsed = isSearchTokenizerUsed; + public MicrosoftLanguageStemmingTokenizer setIsSearchTokenizer(Boolean isSearchTokenizer) { + this.isSearchTokenizer = isSearchTokenizer; return this; } @@ -148,7 +146,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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(); } @@ -165,40 +163,35 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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/indexes/models/MicrosoftLanguageTokenizer.java index 233373ef5aaa..99bf2b717e6d 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/indexes/models/MicrosoftLanguageTokenizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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"; @@ -47,7 +45,7 @@ public final class MicrosoftLanguageTokenizer extends LexicalTokenizer { /** * Creates an instance of MicrosoftLanguageTokenizer class. - * + * * @param name the name value to set. */ @Generated @@ -56,8 +54,8 @@ public MicrosoftLanguageTokenizer(String 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 @@ -70,7 +68,7 @@ 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. - * + * * @return the maxTokenLength value. */ @Generated @@ -82,7 +80,7 @@ public Integer getMaxTokenLength() { * 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. - * + * * @param maxTokenLength the maxTokenLength value to set. * @return the MicrosoftLanguageTokenizer object itself. */ @@ -95,7 +93,7 @@ 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. - * + * * @return the isSearchTokenizer value. */ @Generated @@ -106,7 +104,7 @@ public Boolean 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. - * + * * @param isSearchTokenizer the isSearchTokenizer value to set. * @return the MicrosoftLanguageTokenizer object itself. */ @@ -118,7 +116,7 @@ public MicrosoftLanguageTokenizer setIsSearchTokenizer(Boolean isSearchTokenizer /** * Get the language property: The language to use. The default is English. - * + * * @return the language value. */ @Generated @@ -128,7 +126,7 @@ public MicrosoftTokenizerLanguage getLanguage() { /** * Set the language property: The language to use. The default is English. - * + * * @param language the language value to set. * @return the MicrosoftLanguageTokenizer object itself. */ @@ -155,7 +153,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of MicrosoftLanguageTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of MicrosoftLanguageTokenizer if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -165,7 +163,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -174,10 +171,8 @@ public static MicrosoftLanguageTokenizer fromJson(JsonReader jsonReader) throws 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)) { @@ -190,17 +185,12 @@ 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/indexes/models/MicrosoftStemmingTokenizerLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/MicrosoftStemmingTokenizerLanguage.java index 50b95588c34f..5c98aa8b053b 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -146,7 +144,7 @@ public enum MicrosoftStemmingTokenizerLanguage { MARATHI("marathi"), /** - * Selects the Microsoft stemming tokenizer for Norwegian (Bokmål). + * Selects the Microsoft stemming tokenizer for Norwegian (BokmÃ¥l). */ NORWEGIAN_BOKMAAL("norwegianBokmaal"), 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 index b422b07118f4..e60c5aa7fa4c 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -131,7 +129,7 @@ public enum MicrosoftTokenizerLanguage { MARATHI("marathi"), /** - * Selects the Microsoft tokenizer for Norwegian (Bokmål). + * Selects the Microsoft tokenizer for Norwegian (BokmÃ¥l). */ NORWEGIAN_BOKMAAL("norwegianBokmaal"), 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 index 79adc471c6e1..e005d123f684 100644 --- 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 @@ -1,75 +1,79 @@ // 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.indexes.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.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. + * 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; - } + /* + * The discriminator for derived types. + */ + @Generated + private String odataType = "#Microsoft.Azure.Search.NGramTokenFilter"; - NGramTokenFilter(NGramTokenFilterV2 v2Filter) { - super(v2Filter.getName()); + /* + * The minimum n-gram length. Default is 1. Must be less than the value of maxGram. + */ + @Generated + private Integer minGram; - this.v1Filter = null; - this.v2Filter = v2Filter; - } + /* + * The maximum n-gram length. Default is 2. + */ + @Generated + private Integer maxGram; /** - * Constructor of {@link NGramTokenFilter}. + * Creates an instance of NGramTokenFilter class. * - * @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. + * @param name the name value to set. */ + @Generated public NGramTokenFilter(String name) { super(name); + } - this.v1Filter = null; - this.v2Filter = new NGramTokenFilterV2(name); + /** + * 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. Must - * be less than the value of maxGram. + * Get the minGram property: The minimum n-gram length. Default is 1. Must be less than the value of maxGram. * * @return the minGram value. */ + @Generated public Integer getMinGram() { - return (v1Filter != null) ? v1Filter.getMinGram() : v2Filter.getMinGram(); + return this.minGram; } /** - * Set the minGram property: The minimum n-gram length. Default is 1. Must - * be less than the value of maxGram. + * 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. */ + @Generated public NGramTokenFilter setMinGram(Integer minGram) { - if (v1Filter != null) { - v1Filter.setMinGram(minGram); - } else { - v2Filter.setMinGram(minGram); - } + this.minGram = minGram; return this; } @@ -78,8 +82,9 @@ public NGramTokenFilter setMinGram(Integer minGram) { * * @return the maxGram value. */ + @Generated public Integer getMaxGram() { - return (v1Filter != null) ? v1Filter.getMaxGram() : v2Filter.getMaxGram(); + return this.maxGram; } /** @@ -88,17 +93,62 @@ public Integer getMaxGram() { * @param maxGram the maxGram value to set. * @return the NGramTokenFilter object itself. */ + @Generated public NGramTokenFilter setMaxGram(Integer maxGram) { - if (v1Filter != null) { - v1Filter.setMaxGram(maxGram); - } else { - v2Filter.setMaxGram(maxGram); - } + this.maxGram = maxGram; return this; } + /** + * {@inheritDoc} + */ + @Generated @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - return (v1Filter != null) ? v1Filter.toJson(jsonWriter) : v2Filter.toJson(jsonWriter); + 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 NGramTokenFilter from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of NGramTokenFilter 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 NGramTokenFilter. + */ + @Generated + public static NGramTokenFilter fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + 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(); + } 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(); + } + } + NGramTokenFilter deserializedNGramTokenFilter = new NGramTokenFilter(name); + deserializedNGramTokenFilter.odataType = odataType; + deserializedNGramTokenFilter.minGram = minGram; + deserializedNGramTokenFilter.maxGram = maxGram; + return deserializedNGramTokenFilter; + }); } } 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/indexes/models/NGramTokenFilterV2.java similarity index 81% 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/indexes/models/NGramTokenFilterV2.java index 433207bffe9d..9bf48699fb5a 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/indexes/models/NGramTokenFilterV2.java @@ -1,17 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.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; /** @@ -19,8 +15,9 @@ */ @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"; @@ -39,7 +36,7 @@ public final class NGramTokenFilterV2 extends TokenFilter { /** * Creates an instance of NGramTokenFilterV2 class. - * + * * @param name the name value to set. */ @Generated @@ -48,8 +45,8 @@ public NGramTokenFilterV2(String 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 @@ -61,7 +58,7 @@ public String getOdataType() { /** * 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 @@ -72,7 +69,7 @@ public Integer getMinGram() { /** * 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. */ @@ -84,7 +81,7 @@ public NGramTokenFilterV2 setMinGram(Integer minGram) { /** * Get the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @return the maxGram value. */ @Generated @@ -94,7 +91,7 @@ public Integer getMaxGram() { /** * Set the maxGram property: The maximum n-gram length. Default is 2. Maximum is 300. - * + * * @param maxGram the maxGram value to set. * @return the NGramTokenFilterV2 object itself. */ @@ -120,7 +117,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of NGramTokenFilterV2 from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of NGramTokenFilterV2 if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -130,7 +127,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -138,10 +134,8 @@ public static NGramTokenFilterV2 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)) { @@ -152,15 +146,11 @@ 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; - - return deserializedNGramTokenFilterV2; - } - throw new IllegalStateException("Missing required property: name"); + NGramTokenFilterV2 deserializedNGramTokenFilterV2 = new NGramTokenFilterV2(name); + deserializedNGramTokenFilterV2.odataType = odataType; + deserializedNGramTokenFilterV2.minGram = minGram; + deserializedNGramTokenFilterV2.maxGram = maxGram; + 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/indexes/models/NGramTokenizer.java index 1c27ab644101..926bc834fc7e 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/indexes/models/NGramTokenizer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -21,7 +19,7 @@ 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"; @@ -55,7 +53,7 @@ public NGramTokenizer(String 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. */ @@ -121,6 +119,17 @@ 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. + */ + public NGramTokenizer setTokenChars(TokenCharacterKind... tokenChars) { + this.tokenChars = (tokenChars == null) ? null : Arrays.asList(tokenChars); + return this; + } + /** * Set the tokenChars property: Character classes to keep in the tokens. * @@ -161,7 +170,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -172,7 +180,6 @@ public static NGramTokenizer fromJson(JsonReader jsonReader) throws IOException 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)) { @@ -185,26 +192,12 @@ 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; + return deserializedNGramTokenizer; }); } - - /** - * 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; - } } 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/indexes/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java index 8dbda77ff2e1..67cd07fb8d28 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/indexes/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @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"; @@ -33,8 +31,8 @@ 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 @@ -56,7 +54,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of NativeBlobSoftDeleteDeletionDetectionPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of NativeBlobSoftDeleteDeletionDetectionPolicy if the JsonReader was pointing to an instance * of it, or null if it was pointing to JSON null. @@ -70,14 +68,12 @@ public static NativeBlobSoftDeleteDeletionDetectionPolicy fromJson(JsonReader js while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedNativeBlobSoftDeleteDeletionDetectionPolicy.odataType = reader.getString(); } else { reader.skipChildren(); } } - return 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/indexes/models/OcrLineEnding.java index 63a153057adc..6f8a7191b189 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/indexes/models/OcrLineEnding.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ * "space". */ public final class OcrLineEnding extends ExpandableStringEnum { + /** * Lines are separated by a single space character. */ @@ -41,7 +39,7 @@ public final class OcrLineEnding extends ExpandableStringEnum { /** * Creates a new instance of OcrLineEnding value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -51,7 +49,7 @@ public OcrLineEnding() { /** * Creates or finds a OcrLineEnding from its string representation. - * + * * @param name a name to look for. * @return the corresponding OcrLineEnding. */ @@ -62,7 +60,7 @@ public static OcrLineEnding fromString(String name) { /** * Gets known OcrLineEnding values. - * + * * @return known OcrLineEnding values. */ @Generated 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/indexes/models/OcrSkill.java index dc40c78bdf41..2f7b7101bee0 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/indexes/models/OcrSkill.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -21,7 +18,7 @@ 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"; @@ -57,7 +54,7 @@ public OcrSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -215,10 +210,8 @@ public static OcrSkill fromJson(JsonReader jsonReader) throws IOException { 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)) { @@ -237,38 +230,15 @@ 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/indexes/models/OcrSkillLanguage.java index e231e0791220..f9736987f5df 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/indexes/models/OcrSkillLanguage.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The language codes supported for input by OcrSkill. */ public final class OcrSkillLanguage extends ExpandableStringEnum { + /** * Afrikaans. */ @@ -1036,7 +1034,7 @@ public final class OcrSkillLanguage extends ExpandableStringEnum { + /* * The name of the output defined by the skill. */ @@ -33,7 +31,7 @@ public final class OutputFieldMappingEntry implements JsonSerializable { - boolean nameFound = false; String name = null; String targetName = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedOutputFieldMappingEntry; - } - throw new IllegalStateException("Missing required property: name"); + OutputFieldMappingEntry deserializedOutputFieldMappingEntry = new OutputFieldMappingEntry(name); + deserializedOutputFieldMappingEntry.targetName = targetName; + 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/indexes/models/PIIDetectionSkill.java similarity index 76% 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/indexes/models/PIIDetectionSkill.java index 2224861b6baa..df6188415abd 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/indexes/models/PIIDetectionSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -20,9 +17,10 @@ * 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"; @@ -45,7 +43,7 @@ public final class PiiDetectionSkill extends SearchIndexerSkill { * 'none'. */ @Generated - private PiiDetectionSkillMaskingMode maskingMode; + private PIIDetectionSkillMaskingMode maskingMode; /* * The character used to mask the text if the maskingMode parameter is set to replace. Default is '*'. @@ -74,19 +72,19 @@ public final class PiiDetectionSkill extends SearchIndexerSkill { 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. */ @Generated - public PiiDetectionSkill(List inputs, List outputs) { + 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 @@ -97,7 +95,7 @@ public String getOdataType() { /** * Get the defaultLanguageCode property: A value indicating which language code to use. Default is `en`. - * + * * @return the defaultLanguageCode value. */ @Generated @@ -107,12 +105,12 @@ 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. */ @Generated - public PiiDetectionSkill setDefaultLanguageCode(String defaultLanguageCode) { + public PIIDetectionSkill setDefaultLanguageCode(String defaultLanguageCode) { this.defaultLanguageCode = defaultLanguageCode; return this; } @@ -121,7 +119,7 @@ public PiiDetectionSkill 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. - * + * * @return the minimumPrecision value. */ @Generated @@ -133,12 +131,12 @@ public Double 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 PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ @Generated - public PiiDetectionSkill setMinimumPrecision(Double minimumPrecision) { + public PIIDetectionSkill setMinimumPrecision(Double minimumPrecision) { this.minimumPrecision = minimumPrecision; return this; } @@ -146,23 +144,23 @@ public PiiDetectionSkill setMinimumPrecision(Double minimumPrecision) { /** * 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. */ @Generated - public PiiDetectionSkillMaskingMode getMaskingMode() { + 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'. - * + * * @param maskingMode the maskingMode value to set. - * @return the PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ @Generated - public PiiDetectionSkill setMaskingMode(PiiDetectionSkillMaskingMode maskingMode) { + public PIIDetectionSkill setMaskingMode(PIIDetectionSkillMaskingMode maskingMode) { this.maskingMode = maskingMode; return this; } @@ -170,7 +168,7 @@ public PiiDetectionSkill setMaskingMode(PiiDetectionSkillMaskingMode maskingMode /** * 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 @@ -181,12 +179,12 @@ public String getMask() { /** * 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. */ @Generated - public PiiDetectionSkill setMask(String mask) { + public PIIDetectionSkill setMask(String mask) { this.mask = mask; return this; } @@ -195,7 +193,7 @@ public PiiDetectionSkill setMask(String mask) { * 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 @@ -207,19 +205,19 @@ public String 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 PiiDetectionSkill object itself. + * @return the PIIDetectionSkill object itself. */ @Generated - public PiiDetectionSkill setModelVersion(String modelVersion) { + public PIIDetectionSkill setModelVersion(String modelVersion) { this.modelVersion = modelVersion; return this; } /** * Get the piiCategories property: A list of PII entity categories that should be extracted and masked. - * + * * @return the piiCategories value. */ @Generated @@ -229,12 +227,23 @@ 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. + */ + public PIIDetectionSkill setPiiCategories(String... piiCategories) { + this.piiCategories = (piiCategories == null) ? null : Arrays.asList(piiCategories); + return this; + } + + /** + * 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. */ @Generated - public PiiDetectionSkill setPiiCategories(List piiCategories) { + public PIIDetectionSkill setPiiCategories(List piiCategories) { this.piiCategories = piiCategories; return this; } @@ -242,7 +251,7 @@ public PiiDetectionSkill setPiiCategories(List piiCategories) { /** * 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 @@ -253,12 +262,12 @@ public String getDomain() { /** * 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. */ @Generated - public PiiDetectionSkill setDomain(String domain) { + public PIIDetectionSkill setDomain(String domain) { this.domain = domain; return this; } @@ -268,7 +277,7 @@ public PiiDetectionSkill setDomain(String domain) { */ @Generated @Override - public PiiDetectionSkill setName(String name) { + public PIIDetectionSkill setName(String name) { super.setName(name); return this; } @@ -278,7 +287,7 @@ public PiiDetectionSkill setName(String name) { */ @Generated @Override - public PiiDetectionSkill setDescription(String description) { + public PIIDetectionSkill setDescription(String description) { super.setDescription(description); return this; } @@ -288,7 +297,7 @@ public PiiDetectionSkill setDescription(String description) { */ @Generated @Override - public PiiDetectionSkill setContext(String context) { + public PIIDetectionSkill setContext(String context) { super.setContext(context); return this; } @@ -318,20 +327,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. */ @Generated - public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOException { + 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; @@ -339,7 +346,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; @@ -347,13 +354,10 @@ public static PiiDetectionSkill fromJson(JsonReader jsonReader) throws IOExcepti 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)) { @@ -367,7 +371,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)) { @@ -380,32 +384,19 @@ 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/indexes/models/PiiDetectionSkillMaskingMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PIIDetectionSkillMaskingMode.java similarity index 52% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PiiDetectionSkillMaskingMode.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PIIDetectionSkillMaskingMode.java index 98a1f1907c64..d3be7a7cf3ac 100644 --- 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 @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,12 +10,13 @@ /** * A string indicating what maskingMode to use to mask the personal information detected in the input text. */ -public final class PiiDetectionSkillMaskingMode extends ExpandableStringEnum { +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"); + public static final PIIDetectionSkillMaskingMode NONE = fromString("none"); /** * Replaces the detected entities with the character given in the maskingCharacter parameter. The character will be @@ -26,36 +24,36 @@ public final class PiiDetectionSkillMaskingMode extends ExpandableStringEnum values() { - return values(PiiDetectionSkillMaskingMode.class); + 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/indexes/models/PathHierarchyTokenizerV2.java similarity index 58% 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/indexes/models/PathHierarchyTokenizerV2.java index 18a26769be0a..cf437fd76e88 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/indexes/models/PathHierarchyTokenizerV2.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,15 +9,15 @@ 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. */ @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"; @@ -29,13 +26,13 @@ public final class PathHierarchyTokenizer extends LexicalTokenizer { * The delimiter character to use. Default is "/". */ @Generated - private Character delimiter; + private String delimiter; /* * A value that, if set, replaces the delimiter character. Default is "/". */ @Generated - private Character replacement; + private String replacement; /* * The maximum token length. Default and maximum is 300. @@ -47,7 +44,7 @@ public final class PathHierarchyTokenizer extends LexicalTokenizer { * A value indicating whether to generate tokens in reverse order. Default is false. */ @Generated - private Boolean tokenOrderReversed; + private Boolean reverseTokenOrder; /* * The number of initial tokens to skip. Default is 0. @@ -56,18 +53,18 @@ public final class PathHierarchyTokenizer extends LexicalTokenizer { private Integer numberOfTokensToSkip; /** - * Creates an instance of PathHierarchyTokenizer class. - * + * Creates an instance of PathHierarchyTokenizerV2 class. + * * @param name the name value to set. */ @Generated - public PathHierarchyTokenizer(String name) { + 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 @@ -78,51 +75,51 @@ public String getOdataType() { /** * Get the delimiter property: The delimiter character to use. Default is "/". - * + * * @return the delimiter value. */ @Generated - public Character getDelimiter() { + public String getDelimiter() { return this.delimiter; } /** * 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. */ @Generated - public PathHierarchyTokenizer setDelimiter(Character delimiter) { + public PathHierarchyTokenizerV2 setDelimiter(String delimiter) { this.delimiter = delimiter; return this; } /** * Get the replacement property: A value that, if set, replaces the delimiter character. Default is "/". - * + * * @return the replacement value. */ @Generated - public Character getReplacement() { + public String getReplacement() { return this.replacement; } /** * 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. */ @Generated - public PathHierarchyTokenizer setReplacement(Character replacement) { + public PathHierarchyTokenizerV2 setReplacement(String replacement) { this.replacement = replacement; return this; } /** * Get the maxTokenLength property: The maximum token length. Default and maximum is 300. - * + * * @return the maxTokenLength value. */ @Generated @@ -132,43 +129,43 @@ 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. */ @Generated - public PathHierarchyTokenizer setMaxTokenLength(Integer maxTokenLength) { + 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. */ @Generated - public Boolean isTokenOrderReversed() { - return this.tokenOrderReversed; + 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. */ @Generated - public PathHierarchyTokenizer setTokenOrderReversed(Boolean tokenOrderReversed) { - this.tokenOrderReversed = tokenOrderReversed; + public PathHierarchyTokenizerV2 setReverseTokenOrder(Boolean reverseTokenOrder) { + this.reverseTokenOrder = reverseTokenOrder; return this; } /** * Get the numberOfTokensToSkip property: The number of initial tokens to skip. Default is 0. - * + * * @return the numberOfTokensToSkip value. */ @Generated @@ -178,12 +175,12 @@ 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. */ @Generated - public PathHierarchyTokenizer setNumberOfTokensToSkip(Integer numberOfTokensToSkip) { + public PathHierarchyTokenizerV2 setNumberOfTokensToSkip(Integer numberOfTokensToSkip) { this.numberOfTokensToSkip = numberOfTokensToSkip; return this; } @@ -197,69 +194,62 @@ 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. */ @Generated - public static PathHierarchyTokenizer fromJson(JsonReader jsonReader) throws IOException { + 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(); reader.nextToken(); - 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/indexes/models/PatternAnalyzer.java index 9286c759ae39..6bebd2e95485 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/indexes/models/PatternAnalyzer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,6 +10,7 @@ import com.azure.json.JsonWriter; import java.io.IOException; import java.util.Arrays; +import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; @@ -23,7 +22,7 @@ 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"; @@ -42,10 +41,10 @@ public final class PatternAnalyzer extends LexicalAnalyzer { private String pattern; /* - * Regular expression flags. + * Regular expression flags, specified as a '|' separated string of RegexFlags values. */ @Generated - private RegexFlags flags; + private List flags; /* * A list of stopwords. @@ -64,7 +63,7 @@ public PatternAnalyzer(String 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. */ @@ -80,7 +79,7 @@ public String getOdataType() { * @return the lowerCaseTerms value. */ @Generated - public Boolean areLowerCaseTerms() { + public Boolean isLowerCaseTerms() { return this.lowerCaseTerms; } @@ -121,34 +120,35 @@ public PatternAnalyzer setPattern(String pattern) { } /** - * Get the flags property: Regular expression flags. + * Get the flags property: Regular expression flags, specified as a '|' separated string of RegexFlags values. * * @return the flags value. */ @Generated 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()); - } + return this.flags; } /** - * Set the flags property: Regular expression flags. + * Set the flags property: Regular expression flags, specified as a '|' separated string of RegexFlags values. + * + * @param flags the flags value to set. + * @return the PatternAnalyzer object itself. + */ + public PatternAnalyzer setFlags(RegexFlags... flags) { + this.flags = (flags == null) ? null : Arrays.asList(flags); + return this; + } + + /** + * Set the flags property: Regular expression flags, specified as a '|' separated string of RegexFlags values. * * @param flags the flags value to set. * @return the PatternAnalyzer object itself. */ @Generated 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); - } + this.flags = flags; return this; } @@ -162,6 +162,17 @@ 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. + */ + public PatternAnalyzer setStopwords(String... stopwords) { + this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); + return this; + } + /** * Set the stopwords property: A list of stopwords. * @@ -185,7 +196,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeBooleanField("lowercase", this.lowerCaseTerms); jsonWriter.writeStringField("pattern", this.pattern); - jsonWriter.writeStringField("flags", this.flags == null ? null : this.flags.toString()); + if (this.flags != null) { + jsonWriter.writeStringField("flags", + this.flags.stream() + .map(element -> element == null ? null : element.toString()) + .collect(Collectors.joining("|"))); + } jsonWriter.writeArrayField("stopwords", this.stopwords, (writer, element) -> writer.writeString(element)); return jsonWriter.writeEndObject(); } @@ -202,19 +218,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; String pattern = null; - RegexFlags flags = null; + List flags = null; 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 ("lowercase".equals(fieldName)) { @@ -222,49 +236,29 @@ public static PatternAnalyzer fromJson(JsonReader jsonReader) throws IOException } else if ("pattern".equals(fieldName)) { pattern = reader.getString(); } else if ("flags".equals(fieldName)) { - flags = RegexFlags.fromString(reader.getString()); + flags = reader.getNullable(nonNullReader -> { + String flagsEncodedAsString = nonNullReader.getString(); + return flagsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.stream(flagsEncodedAsString.split("\\|", -1)) + .map(valueAsString -> valueAsString == null + ? null + : RegexFlags.fromString(valueAsString)) + .collect(Collectors.toList())); + }); } else if ("stopwords".equals(fieldName)) { stopwords = reader.readArray(reader1 -> reader1.getString()); } else { 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/indexes/models/PatternCaptureTokenFilter.java index 0940e84719a7..5fdce8ad5373 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/indexes/models/PatternCaptureTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,7 @@ 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; /** @@ -21,8 +18,9 @@ */ @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"; @@ -41,7 +39,18 @@ public final class PatternCaptureTokenFilter extends TokenFilter { /** * Creates an instance of PatternCaptureTokenFilter class. - * + * + * @param name the name value to set. + * @param patterns the patterns value to set. + */ + public PatternCaptureTokenFilter(String name, String... patterns) { + super(name); + this.patterns = (patterns == null) ? null : Arrays.asList(patterns); + } + + /** + * Creates an instance of PatternCaptureTokenFilter class. + * * @param name the name value to set. * @param patterns the patterns value to set. */ @@ -52,8 +61,8 @@ public PatternCaptureTokenFilter(String name, List 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 @@ -64,7 +73,7 @@ public String getOdataType() { /** * Get the patterns property: A list of patterns to match against each token. - * + * * @return the patterns value. */ @Generated @@ -75,7 +84,7 @@ public List getPatterns() { /** * Get the preserveOriginal property: A value indicating whether to return the original token even if one of the * patterns matches. Default is true. - * + * * @return the preserveOriginal value. */ @Generated @@ -86,7 +95,7 @@ public Boolean isPreserveOriginal() { /** * Set the preserveOriginal property: A value indicating whether to return the original token even if one of the * patterns matches. Default is true. - * + * * @param preserveOriginal the preserveOriginal value to set. * @return the PatternCaptureTokenFilter object itself. */ @@ -112,7 +121,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PatternCaptureTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PatternCaptureTokenFilter if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -122,22 +131,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -146,24 +150,11 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + PatternCaptureTokenFilter deserializedPatternCaptureTokenFilter + = new PatternCaptureTokenFilter(name, patterns); + deserializedPatternCaptureTokenFilter.odataType = odataType; + deserializedPatternCaptureTokenFilter.preserveOriginal = preserveOriginal; + 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/indexes/models/PatternReplaceCharFilter.java index 40d39846ee18..83b62da9da71 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/indexes/models/PatternReplaceCharFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,19 +9,18 @@ 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 + * "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"; @@ -43,7 +39,7 @@ public final class PatternReplaceCharFilter extends CharFilter { /** * Creates an instance of PatternReplaceCharFilter class. - * + * * @param name the name value to set. * @param pattern the pattern value to set. * @param replacement the replacement value to set. @@ -56,8 +52,8 @@ 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 @@ -68,7 +64,7 @@ public String getOdataType() { /** * Get the pattern property: A regular expression pattern. - * + * * @return the pattern value. */ @Generated @@ -78,7 +74,7 @@ public String getPattern() { /** * Get the replacement property: The replacement text. - * + * * @return the replacement value. */ @Generated @@ -102,7 +98,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PatternReplaceCharFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PatternReplaceCharFilter if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -112,52 +108,29 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + PatternReplaceCharFilter deserializedPatternReplaceCharFilter + = new PatternReplaceCharFilter(name, pattern, replacement); + deserializedPatternReplaceCharFilter.odataType = odataType; + 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/indexes/models/PatternReplaceTokenFilter.java index ac170d02cd6f..9137b94c84fd 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/indexes/models/PatternReplaceTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,19 +9,18 @@ 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 + * "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"; @@ -43,7 +39,7 @@ public final class PatternReplaceTokenFilter extends TokenFilter { /** * Creates an instance of PatternReplaceTokenFilter class. - * + * * @param name the name value to set. * @param pattern the pattern value to set. * @param replacement the replacement value to set. @@ -56,8 +52,8 @@ 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 @@ -68,7 +64,7 @@ public String getOdataType() { /** * Get the pattern property: A regular expression pattern. - * + * * @return the pattern value. */ @Generated @@ -78,7 +74,7 @@ public String getPattern() { /** * Get the replacement property: The replacement text. - * + * * @return the replacement value. */ @Generated @@ -102,7 +98,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of PatternReplaceTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of PatternReplaceTokenFilter if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -112,52 +108,29 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + PatternReplaceTokenFilter deserializedPatternReplaceTokenFilter + = new PatternReplaceTokenFilter(name, pattern, replacement); + deserializedPatternReplaceTokenFilter.odataType = odataType; + 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/indexes/models/PatternTokenizer.java index bd1cea7ba77c..43c775caf420 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/indexes/models/PatternTokenizer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,6 +10,7 @@ import com.azure.json.JsonWriter; import java.io.IOException; import java.util.Arrays; +import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; @@ -23,7 +22,7 @@ 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"; @@ -36,10 +35,10 @@ public final class PatternTokenizer extends LexicalTokenizer { private String pattern; /* - * Regular expression flags. + * Regular expression flags, specified as a '|' separated string of RegexFlags values. */ @Generated - private RegexFlags flags; + private List flags; /* * The zero-based ordinal of the matching group in the regular expression pattern to extract into tokens. Use -1 if @@ -60,7 +59,7 @@ public PatternTokenizer(String 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. */ @@ -95,34 +94,35 @@ public PatternTokenizer setPattern(String pattern) { } /** - * Get the flags property: Regular expression flags. + * Get the flags property: Regular expression flags, specified as a '|' separated string of RegexFlags values. * * @return the flags value. */ @Generated 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()); - } + return this.flags; } /** - * Set the flags property: Regular expression flags. + * Set the flags property: Regular expression flags, specified as a '|' separated string of RegexFlags values. + * + * @param flags the flags value to set. + * @return the PatternTokenizer object itself. + */ + public PatternTokenizer setFlags(RegexFlags... flags) { + this.flags = (flags == null) ? null : Arrays.asList(flags); + return this; + } + + /** + * Set the flags property: Regular expression flags, specified as a '|' separated string of RegexFlags values. * * @param flags the flags value to set. * @return the PatternTokenizer object itself. */ @Generated 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); - } + this.flags = flags; return this; } @@ -162,7 +162,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("name", getName()); jsonWriter.writeStringField("@odata.type", this.odataType); jsonWriter.writeStringField("pattern", this.pattern); - jsonWriter.writeStringField("flags", this.flags == null ? null : this.flags.toString()); + if (this.flags != null) { + jsonWriter.writeStringField("flags", + this.flags.stream() + .map(element -> element == null ? null : element.toString()) + .collect(Collectors.joining("|"))); + } jsonWriter.writeNumberField("group", this.group); return jsonWriter.writeEndObject(); } @@ -179,54 +184,43 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; - RegexFlags flags = null; + List flags = null; Integer group = 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 ("pattern".equals(fieldName)) { pattern = reader.getString(); } else if ("flags".equals(fieldName)) { - flags = RegexFlags.fromString(reader.getString()); + flags = reader.getNullable(nonNullReader -> { + String flagsEncodedAsString = nonNullReader.getString(); + return flagsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.stream(flagsEncodedAsString.split("\\|", -1)) + .map(valueAsString -> valueAsString == null + ? null + : RegexFlags.fromString(valueAsString)) + .collect(Collectors.toList())); + }); } else if ("group".equals(fieldName)) { group = reader.getNullable(JsonReader::getInt); } else { 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; + return deserializedPatternTokenizer; }); } - - /** - * 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)); - } - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java index bd224bb85331..01483dcea834 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * A value indicating whether the field should be used as a permission filter. */ public final class PermissionFilter extends ExpandableStringEnum { + /** * Field represents user IDs that should be used to filter document access on queries. */ @@ -34,7 +32,7 @@ public final class PermissionFilter extends ExpandableStringEnum { - 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/indexes/models/RankingOrder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java index f3d1aa4491f2..972854a6968f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Represents score to use for sort order of documents. */ public final class RankingOrder extends ExpandableStringEnum { + /** * Sets sort order as BoostedRerankerScore. */ @@ -28,7 +26,7 @@ public final class RankingOrder extends ExpandableStringEnum { /** * Creates a new instance of RankingOrder value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -38,7 +36,7 @@ public RankingOrder() { /** * Creates or finds a RankingOrder from its string representation. - * + * * @param name a name to look for. * @return the corresponding RankingOrder. */ @@ -49,7 +47,7 @@ public static RankingOrder fromString(String name) { /** * Gets known RankingOrder values. - * + * * @return known RankingOrder values. */ @Generated 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/indexes/models/RegexFlags.java index 39438f5ee123..75e6ae3a8d37 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/indexes/models/RegexFlags.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -11,10 +8,10 @@ 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 a regular expression flag that can be used in the pattern analyzer and pattern tokenizer. */ public final class RegexFlags extends ExpandableStringEnum { + /** * Enables canonical equivalence. */ @@ -65,7 +62,7 @@ public final class RegexFlags extends ExpandableStringEnum { /** * Creates a new instance of RegexFlags value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -75,7 +72,7 @@ public RegexFlags() { /** * Creates or finds a RegexFlags from its string representation. - * + * * @param name a name to look for. * @return the corresponding RegexFlags. */ @@ -86,7 +83,7 @@ public static RegexFlags fromString(String name) { /** * Gets known RegexFlags values. - * + * * @return known RegexFlags values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSource.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSource.java index 7e3acb71851a..0f1f2eb1b445 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSource.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSource.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,6 +15,7 @@ */ @Fluent public final class RemoteSharePointKnowledgeSource extends KnowledgeSource { + /* * The type of the knowledge source. */ @@ -25,14 +23,14 @@ public final class RemoteSharePointKnowledgeSource extends KnowledgeSource { private KnowledgeSourceKind kind = KnowledgeSourceKind.REMOTE_SHARE_POINT; /* - * The parameters for the knowledge source. + * The parameters for the remote SharePoint knowledge source. */ @Generated private RemoteSharePointKnowledgeSourceParameters remoteSharePointParameters; /** * Creates an instance of RemoteSharePointKnowledgeSource class. - * + * * @param name the name value to set. */ @Generated @@ -42,7 +40,7 @@ public RemoteSharePointKnowledgeSource(String name) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -52,8 +50,8 @@ public KnowledgeSourceKind getKind() { } /** - * Get the remoteSharePointParameters property: The parameters for the knowledge source. - * + * Get the remoteSharePointParameters property: The parameters for the remote SharePoint knowledge source. + * * @return the remoteSharePointParameters value. */ @Generated @@ -62,8 +60,8 @@ public RemoteSharePointKnowledgeSourceParameters getRemoteSharePointParameters() } /** - * Set the remoteSharePointParameters property: The parameters for the knowledge source. - * + * Set the remoteSharePointParameters property: The parameters for the remote SharePoint knowledge source. + * * @param remoteSharePointParameters the remoteSharePointParameters value to set. * @return the RemoteSharePointKnowledgeSource object itself. */ @@ -122,7 +120,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RemoteSharePointKnowledgeSource from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RemoteSharePointKnowledgeSource if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -132,7 +130,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static RemoteSharePointKnowledgeSource fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String description = null; String eTag = null; @@ -142,10 +139,8 @@ public static RemoteSharePointKnowledgeSource fromJson(JsonReader jsonReader) th 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 ("@odata.etag".equals(fieldName)) { @@ -160,18 +155,14 @@ public static RemoteSharePointKnowledgeSource fromJson(JsonReader jsonReader) th reader.skipChildren(); } } - if (nameFound) { - RemoteSharePointKnowledgeSource deserializedRemoteSharePointKnowledgeSource - = new RemoteSharePointKnowledgeSource(name); - deserializedRemoteSharePointKnowledgeSource.setDescription(description); - deserializedRemoteSharePointKnowledgeSource.setETag(eTag); - deserializedRemoteSharePointKnowledgeSource.setEncryptionKey(encryptionKey); - deserializedRemoteSharePointKnowledgeSource.kind = kind; - deserializedRemoteSharePointKnowledgeSource.remoteSharePointParameters = remoteSharePointParameters; - - return deserializedRemoteSharePointKnowledgeSource; - } - throw new IllegalStateException("Missing required property: name"); + RemoteSharePointKnowledgeSource deserializedRemoteSharePointKnowledgeSource + = new RemoteSharePointKnowledgeSource(name); + deserializedRemoteSharePointKnowledgeSource.setDescription(description); + deserializedRemoteSharePointKnowledgeSource.setETag(eTag); + deserializedRemoteSharePointKnowledgeSource.setEncryptionKey(encryptionKey); + deserializedRemoteSharePointKnowledgeSource.kind = kind; + deserializedRemoteSharePointKnowledgeSource.remoteSharePointParameters = remoteSharePointParameters; + return deserializedRemoteSharePointKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSourceParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSourceParameters.java index 9890642630ed..47f39d4729d7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSourceParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSourceParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -21,17 +19,17 @@ @Fluent public final class RemoteSharePointKnowledgeSourceParameters implements JsonSerializable { + /* * Keyword Query Language (KQL) expression with queryable SharePoint properties and attributes to scope the - * retrieval before the query runs. See documentation: - * https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference + * retrieval before the query runs. */ @Generated private String filterExpression; /* * A list of metadata fields to be returned for each item in the response. Only retrievable metadata properties can - * be included in this list. By default, no metadata is returned. Optional. + * be included in this list. By default, no metadata is returned. */ @Generated private List resourceMetadata; @@ -51,9 +49,8 @@ public RemoteSharePointKnowledgeSourceParameters() { /** * Get the filterExpression property: Keyword Query Language (KQL) expression with queryable SharePoint properties - * and attributes to scope the retrieval before the query runs. See documentation: - * https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference. - * + * and attributes to scope the retrieval before the query runs. + * * @return the filterExpression value. */ @Generated @@ -63,9 +60,8 @@ public String getFilterExpression() { /** * Set the filterExpression property: Keyword Query Language (KQL) expression with queryable SharePoint properties - * and attributes to scope the retrieval before the query runs. See documentation: - * https://learn.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference. - * + * and attributes to scope the retrieval before the query runs. + * * @param filterExpression the filterExpression value to set. * @return the RemoteSharePointKnowledgeSourceParameters object itself. */ @@ -77,8 +73,8 @@ public RemoteSharePointKnowledgeSourceParameters setFilterExpression(String filt /** * Get the resourceMetadata property: A list of metadata fields to be returned for each item in the response. Only - * retrievable metadata properties can be included in this list. By default, no metadata is returned. Optional. - * + * retrievable metadata properties can be included in this list. By default, no metadata is returned. + * * @return the resourceMetadata value. */ @Generated @@ -88,8 +84,20 @@ public List getResourceMetadata() { /** * Set the resourceMetadata property: A list of metadata fields to be returned for each item in the response. Only - * retrievable metadata properties can be included in this list. By default, no metadata is returned. Optional. - * + * retrievable metadata properties can be included in this list. By default, no metadata is returned. + * + * @param resourceMetadata the resourceMetadata value to set. + * @return the RemoteSharePointKnowledgeSourceParameters object itself. + */ + public RemoteSharePointKnowledgeSourceParameters setResourceMetadata(String... resourceMetadata) { + this.resourceMetadata = (resourceMetadata == null) ? null : Arrays.asList(resourceMetadata); + return this; + } + + /** + * Set the resourceMetadata property: A list of metadata fields to be returned for each item in the response. Only + * retrievable metadata properties can be included in this list. By default, no metadata is returned. + * * @param resourceMetadata the resourceMetadata value to set. * @return the RemoteSharePointKnowledgeSourceParameters object itself. */ @@ -102,7 +110,7 @@ public RemoteSharePointKnowledgeSourceParameters setResourceMetadata(List { + /* * 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 rescoringEnabled; + private Boolean enableRescoring; /* * Default oversampling factor. Oversampling retrieves a greater set of potential documents to offset the resolution @@ -49,28 +47,28 @@ public RescoringOptions() { } /** - * Get the rescoringEnabled property: If set to true, after the initial search on the compressed vectors, the + * 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. - * - * @return the rescoringEnabled value. + * + * @return the enableRescoring value. */ @Generated - public Boolean isRescoringEnabled() { - return this.rescoringEnabled; + public Boolean isEnableRescoring() { + return this.enableRescoring; } /** - * Set the rescoringEnabled property: If set to true, after the initial search on the compressed vectors, the + * 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. - * - * @param rescoringEnabled the rescoringEnabled value to set. + * + * @param enableRescoring the enableRescoring value to set. * @return the RescoringOptions object itself. */ @Generated - public RescoringOptions setRescoringEnabled(Boolean rescoringEnabled) { - this.rescoringEnabled = rescoringEnabled; + public RescoringOptions setEnableRescoring(Boolean enableRescoring) { + this.enableRescoring = enableRescoring; return this; } @@ -79,7 +77,7 @@ public RescoringOptions setRescoringEnabled(Boolean rescoringEnabled) { * 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 @@ -92,7 +90,7 @@ public Double getDefaultOversampling() { * 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. */ @@ -105,7 +103,7 @@ public RescoringOptions setDefaultOversampling(Double defaultOversampling) { /** * Get the rescoreStorageMethod property: Controls the storage method for original vectors. This setting is * immutable. - * + * * @return the rescoreStorageMethod value. */ @Generated @@ -116,7 +114,7 @@ public VectorSearchCompressionRescoreStorageMethod getRescoreStorageMethod() { /** * Set the rescoreStorageMethod property: Controls the storage method for original vectors. This setting is * immutable. - * + * * @param rescoreStorageMethod the rescoreStorageMethod value to set. * @return the RescoringOptions object itself. */ @@ -133,7 +131,7 @@ public RescoringOptions setRescoreStorageMethod(VectorSearchCompressionRescoreSt @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("enableRescoring", this.rescoringEnabled); + jsonWriter.writeBooleanField("enableRescoring", this.enableRescoring); jsonWriter.writeNumberField("defaultOversampling", this.defaultOversampling); jsonWriter.writeStringField("rescoreStorageMethod", this.rescoreStorageMethod == null ? null : this.rescoreStorageMethod.toString()); @@ -142,7 +140,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RescoringOptions from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RescoringOptions if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -155,9 +153,8 @@ public static RescoringOptions fromJson(JsonReader jsonReader) throws IOExceptio while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("enableRescoring".equals(fieldName)) { - deserializedRescoringOptions.rescoringEnabled = reader.getNullable(JsonReader::getBoolean); + deserializedRescoringOptions.enableRescoring = reader.getNullable(JsonReader::getBoolean); } else if ("defaultOversampling".equals(fieldName)) { deserializedRescoringOptions.defaultOversampling = reader.getNullable(JsonReader::getDouble); } else if ("rescoreStorageMethod".equals(fieldName)) { @@ -167,7 +164,6 @@ public static RescoringOptions fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - return deserializedRescoringOptions; }); } 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/indexes/models/ResourceCounter.java index 458f1b2bac92..d62f1b8e9308 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/indexes/models/ResourceCounter.java @@ -1,13 +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; -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; @@ -17,8 +14,9 @@ /** * Represents a resource's usage and quota. */ -@Fluent +@Immutable public final class ResourceCounter implements JsonSerializable { + /* * The resource usage amount. */ @@ -33,17 +31,17 @@ public final class ResourceCounter implements JsonSerializable /** * Creates an instance of ResourceCounter class. - * + * * @param usage the usage value to set. */ @Generated - public ResourceCounter(long usage) { + private ResourceCounter(long usage) { this.usage = usage; } /** * Get the usage property: The resource usage amount. - * + * * @return the usage value. */ @Generated @@ -53,7 +51,7 @@ public long getUsage() { /** * Get the quota property: The resource amount quota. - * + * * @return the quota value. */ @Generated @@ -61,18 +59,6 @@ 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. - */ - @Generated - public ResourceCounter setQuota(Long quota) { - this.quota = quota; - return this; - } - /** * {@inheritDoc} */ @@ -87,7 +73,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ResourceCounter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ResourceCounter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -97,29 +83,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedResourceCounter; - } - throw new IllegalStateException("Missing required property: usage"); + ResourceCounter deserializedResourceCounter = new ResourceCounter(usage); + deserializedResourceCounter.quota = quota; + 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/indexes/models/ScalarQuantizationCompression.java index 688e2615b655..e0802447ca48 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/indexes/models/ScalarQuantizationCompression.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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; @@ -33,7 +31,7 @@ public final class ScalarQuantizationCompression extends VectorSearchCompression /** * Creates an instance of ScalarQuantizationCompression class. - * + * * @param compressionName the compressionName value to set. */ @Generated @@ -42,8 +40,8 @@ public ScalarQuantizationCompression(String 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 @@ -54,7 +52,7 @@ public VectorSearchCompressionKind getKind() { /** * Get the parameters property: Contains the parameters specific to Scalar Quantization. - * + * * @return the parameters value. */ @Generated @@ -64,7 +62,7 @@ public ScalarQuantizationParameters getParameters() { /** * Set the parameters property: Contains the parameters specific to Scalar Quantization. - * + * * @param parameters the parameters value to set. * @return the ScalarQuantizationCompression object itself. */ @@ -74,26 +72,6 @@ public ScalarQuantizationCompression setParameters(ScalarQuantizationParameters return this; } - /** - * {@inheritDoc} - */ - @Generated - @Override - public ScalarQuantizationCompression setRerankWithOriginalVectors(Boolean rerankWithOriginalVectors) { - super.setRerankWithOriginalVectors(rerankWithOriginalVectors); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public ScalarQuantizationCompression setDefaultOversampling(Double defaultOversampling) { - super.setDefaultOversampling(defaultOversampling); - return this; - } - /** * {@inheritDoc} */ @@ -122,8 +100,6 @@ public ScalarQuantizationCompression setTruncationDimension(Integer truncationDi public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", getCompressionName()); - jsonWriter.writeBooleanField("rerankWithOriginalVectors", isRerankWithOriginalVectors()); - jsonWriter.writeNumberField("defaultOversampling", getDefaultOversampling()); jsonWriter.writeJsonField("rescoringOptions", getRescoringOptions()); jsonWriter.writeNumberField("truncationDimension", getTruncationDimension()); jsonWriter.writeStringField("kind", this.kind == null ? null : this.kind.toString()); @@ -133,7 +109,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ScalarQuantizationCompression from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ScalarQuantizationCompression if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -143,10 +119,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; RescoringOptions rescoringOptions = null; Integer truncationDimension = null; VectorSearchCompressionKind kind = VectorSearchCompressionKind.SCALAR_QUANTIZATION; @@ -154,14 +127,8 @@ public static ScalarQuantizationCompression fromJson(JsonReader jsonReader) thro while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { compressionName = reader.getString(); - compressionNameFound = true; - } else if ("rerankWithOriginalVectors".equals(fieldName)) { - rerankWithOriginalVectors = reader.getNullable(JsonReader::getBoolean); - } else if ("defaultOversampling".equals(fieldName)) { - defaultOversampling = reader.getNullable(JsonReader::getDouble); } else if ("rescoringOptions".equals(fieldName)) { rescoringOptions = RescoringOptions.fromJson(reader); } else if ("truncationDimension".equals(fieldName)) { @@ -174,19 +141,13 @@ 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.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/indexes/models/ScalarQuantizationParameters.java index c9794351a436..c5f9e3c30790 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/indexes/models/ScalarQuantizationParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public final class ScalarQuantizationParameters implements JsonSerializable { + /* * The quantized data type of compressed vector values. */ @@ -34,7 +32,7 @@ public ScalarQuantizationParameters() { /** * Get the quantizedDataType property: The quantized data type of compressed vector values. - * + * * @return the quantizedDataType value. */ @Generated @@ -44,7 +42,7 @@ public VectorSearchCompressionTarget getQuantizedDataType() { /** * Set the quantizedDataType property: The quantized data type of compressed vector values. - * + * * @param quantizedDataType the quantizedDataType value to set. * @return the ScalarQuantizationParameters object itself. */ @@ -68,7 +66,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ScalarQuantizationParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ScalarQuantizationParameters if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -81,7 +79,6 @@ public static ScalarQuantizationParameters fromJson(JsonReader jsonReader) throw while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("quantizedDataType".equals(fieldName)) { deserializedScalarQuantizationParameters.quantizedDataType = VectorSearchCompressionTarget.fromString(reader.getString()); @@ -89,7 +86,6 @@ public static ScalarQuantizationParameters fromJson(JsonReader jsonReader) throw reader.skipChildren(); } } - return deserializedScalarQuantizationParameters; }); } 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/indexes/models/ScoringFunction.java index 543a08dd4aa9..53bf0191005a 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/indexes/models/ScoringFunction.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,17 +10,15 @@ 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. */ @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"; @@ -48,7 +43,7 @@ public class ScoringFunction implements JsonSerializable { /** * Creates an instance of ScoringFunction class. - * + * * @param fieldName the fieldName value to set. * @param boost the boost value to set. */ @@ -59,9 +54,8 @@ public ScoringFunction(String fieldName, double 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 @@ -71,7 +65,7 @@ public String getType() { /** * Get the fieldName property: The name of the field used as input to the scoring function. - * + * * @return the fieldName value. */ @Generated @@ -81,7 +75,7 @@ public String getFieldName() { /** * Get the boost property: A multiplier for the raw score. Must be a positive number not equal to 1.0. - * + * * @return the boost value. */ @Generated @@ -92,7 +86,7 @@ public double getBoost() { /** * Get the interpolation property: A value indicating how boosting will be interpolated across document scores; * defaults to "Linear". - * + * * @return the interpolation value. */ @Generated @@ -103,7 +97,7 @@ public ScoringFunctionInterpolation getInterpolation() { /** * Set the interpolation property: A value indicating how boosting will be interpolated across document scores; * defaults to "Linear". - * + * * @param interpolation the interpolation value to set. * @return the ScoringFunction object itself. */ @@ -129,7 +123,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of ScoringFunction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of ScoringFunction if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -141,7 +135,8 @@ public static ScoringFunction fromJson(JsonReader jsonReader) throws IOException return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String jsonFieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -171,22 +166,17 @@ 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; while (reader.nextToken() != JsonToken.END_OBJECT) { String jsonFieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -195,23 +185,10 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + ScoringFunction deserializedScoringFunction = new ScoringFunction(fieldName, boost); + deserializedScoringFunction.type = type; + deserializedScoringFunction.interpolation = interpolation; + return deserializedScoringFunction; }); } } 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 index fe48f64d1424..e42b9b49f237 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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 index 43d05697f845..0072d1e25387 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/ScoringProfile.java index a50dacc7b0d4..03edd550e810 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/indexes/models/ScoringProfile.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -98,6 +96,17 @@ 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. + */ + public ScoringProfile setFunctions(ScoringFunction... functions) { + this.functions = (functions == null) ? null : Arrays.asList(functions); + return this; + } + /** * Set the functions property: The collection of functions that influence the scoring of documents. * @@ -161,7 +170,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -171,7 +179,6 @@ public static ScoringProfile fromJson(JsonReader jsonReader) throws IOException 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)) { @@ -182,25 +189,11 @@ 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; + return deserializedScoringProfile; }); } - - /** - * 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; - } } 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/indexes/models/SearchAlias.java index b6e28e67e775..99cbf6599117 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/indexes/models/SearchAlias.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,7 +10,7 @@ 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; /** @@ -22,6 +19,7 @@ */ @Fluent public final class SearchAlias implements JsonSerializable { + /* * The name of the alias. */ @@ -42,7 +40,18 @@ public final class SearchAlias implements JsonSerializable { /** * Creates an instance of SearchAlias class. - * + * + * @param name the name value to set. + * @param indexes the indexes value to set. + */ + public SearchAlias(String name, String... indexes) { + this.name = name; + this.indexes = (indexes == null) ? null : Arrays.asList(indexes); + } + + /** + * Creates an instance of SearchAlias class. + * * @param name the name value to set. * @param indexes the indexes value to set. */ @@ -54,7 +63,7 @@ public SearchAlias(String name, List indexes) { /** * Get the name property: The name of the alias. - * + * * @return the name value. */ @Generated @@ -64,7 +73,7 @@ public String getName() { /** * Get the indexes property: The name of the index this alias maps to. Only one index name may be specified. - * + * * @return the indexes value. */ @Generated @@ -74,7 +83,7 @@ public List getIndexes() { /** * Get the eTag property: The ETag of the alias. - * + * * @return the eTag value. */ @Generated @@ -84,7 +93,7 @@ public String getETag() { /** * Set the eTag property: The ETag of the alias. - * + * * @param eTag the eTag value to set. * @return the SearchAlias object itself. */ @@ -109,7 +118,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchAlias from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchAlias if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -119,43 +128,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + SearchAlias deserializedSearchAlias = new SearchAlias(name, indexes); + deserializedSearchAlias.eTag = eTag; + return deserializedSearchAlias; }); } } 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 index d43596ad068b..a3aedd230ac4 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +10,6 @@ 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; @@ -44,13 +41,14 @@ public final class SearchField implements JsonSerializable { 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. + * 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 hidden; + private Boolean retrievable; /* * An immutable value indicating whether the field will be persisted separately on disk to be returned in a search @@ -117,8 +115,7 @@ public final class SearchField implements JsonSerializable { private PermissionFilter permissionFilter; /* - * A value indicating whether the field should be used for sensitivity label filtering. This enables document-level - * filtering based on Microsoft Purview sensitivity labels. + * A value indicating whether the field contains sensitivity label information. */ @Generated private Boolean sensitivityLabel; @@ -254,31 +251,67 @@ public SearchField setKey(Boolean 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 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. + * fields and enabling it does not cause an increase in index storage requirements. Default is false for simple + * fields, true for vector fields, and null for complex fields. * * @return the hidden value. + * @deprecated Use {@link #isRetrievable()} instead and flip the boolean value. */ - @Generated + @Deprecated public Boolean isHidden() { - return (this.hidden == null) ? null : !this.hidden; + return (this.retrievable == null) ? null : !this.retrievable; } /** * 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. + * fields and enabling it does not cause an increase in index storage requirements. Default is false for simple + * fields, true for vector fields, and null for complex fields. * * @param hidden the hidden value to set. * @return the SearchField object itself. + * @deprecated Use {@link #setRetrievable(Boolean)} instead and flip the boolean value. */ - @Generated + @Deprecated public SearchField setHidden(Boolean hidden) { - this.hidden = (hidden == null) ? null : !hidden; + this.retrievable = (hidden == null) ? null : !hidden; return this; } @@ -473,8 +506,7 @@ public SearchField setPermissionFilter(PermissionFilter permissionFilter) { } /** - * Get the sensitivityLabel property: A value indicating whether the field should be used for sensitivity label - * filtering. This enables document-level filtering based on Microsoft Purview sensitivity labels. + * Get the sensitivityLabel property: A value indicating whether the field contains sensitivity label information. * * @return the sensitivityLabel value. */ @@ -484,8 +516,7 @@ public Boolean isSensitivityLabel() { } /** - * Set the sensitivityLabel property: A value indicating whether the field should be used for sensitivity label - * filtering. This enables document-level filtering based on Microsoft Purview sensitivity labels. + * Set the sensitivityLabel property: A value indicating whether the field contains sensitivity label information. * * @param sensitivityLabel the sensitivityLabel value to set. * @return the SearchField object itself. @@ -690,6 +721,21 @@ 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(String... synonymMapNames) { + this.synonymMapNames = (synonymMapNames == null) ? null : Arrays.asList(synonymMapNames); + 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 @@ -717,6 +763,18 @@ 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(SearchField... fields) { + this.fields = (fields == null) ? null : Arrays.asList(fields); + return this; + } + /** * 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. @@ -740,7 +798,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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("retrievable", this.retrievable); jsonWriter.writeBooleanField("stored", this.stored); jsonWriter.writeBooleanField("searchable", this.searchable); jsonWriter.writeBooleanField("filterable", this.filterable); @@ -777,12 +835,10 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated 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 retrievable = null; Boolean stored = null; Boolean searchable = null; Boolean filterable = null; @@ -804,14 +860,12 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { 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); + retrievable = reader.getNullable(JsonReader::getBoolean); } else if ("stored".equals(fieldName)) { stored = reader.getNullable(JsonReader::getBoolean); } else if ("searchable".equals(fieldName)) { @@ -848,64 +902,26 @@ public static SearchField fromJson(JsonReader jsonReader) throws IOException { 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.permissionFilter = permissionFilter; - deserializedSearchField.sensitivityLabel = sensitivityLabel; - deserializedSearchField.analyzerName = analyzerName; - deserializedSearchField.searchAnalyzerName = searchAnalyzerName; - deserializedSearchField.indexAnalyzerName = indexAnalyzerName; - deserializedSearchField.normalizerName = normalizerName; - 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)); + 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.permissionFilter = permissionFilter; + deserializedSearchField.sensitivityLabel = sensitivityLabel; + deserializedSearchField.analyzerName = analyzerName; + deserializedSearchField.searchAnalyzerName = searchAnalyzerName; + deserializedSearchField.indexAnalyzerName = indexAnalyzerName; + deserializedSearchField.normalizerName = normalizerName; + deserializedSearchField.vectorSearchDimensions = vectorSearchDimensions; + deserializedSearchField.vectorSearchProfileName = vectorSearchProfileName; + deserializedSearchField.vectorEncodingFormat = vectorEncodingFormat; + deserializedSearchField.synonymMapNames = synonymMapNames; + deserializedSearchField.fields = fields; + return deserializedSearchField; }); } - - /** - * 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/SearchFieldDataType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java index f0faeab53ebf..13bb466993c1 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/indexes/models/SearchFieldDataType.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; 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/indexes/models/SearchIndex.java index dad4f876910d..b3ea3da10556 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/indexes/models/SearchIndex.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -37,7 +35,7 @@ public final class SearchIndex implements JsonSerializable { * The fields of the index. */ @Generated - private List fields; + private final List fields; /* * The scoring profiles for the index. @@ -132,8 +130,7 @@ public final class SearchIndex implements JsonSerializable { private SearchIndexPermissionFilterOption permissionFilterOption; /* - * A value indicating whether the index is leveraging Purview-specific features. This property defaults to false and - * cannot be changed after index creation. + * A value indicating whether Purview is enabled for the index. */ @Generated private Boolean purviewEnabled; @@ -148,10 +145,23 @@ public final class SearchIndex implements JsonSerializable { * Creates an instance of SearchIndex class. * * @param name the name value to set. + * @param fields the fields value to set. + */ + public SearchIndex(String name, SearchField... fields) { + this.name = name; + this.fields = (fields == null) ? null : Arrays.asList(fields); + } + + /** + * Creates an instance of SearchIndex class. + * + * @param name the name value to set. + * @param fields the fields value to set. */ @Generated - public SearchIndex(String name) { + public SearchIndex(String name, List fields) { this.name = name; + this.fields = fields; } /** @@ -197,25 +207,24 @@ public List getFields() { } /** - * Set the fields property: The fields of the index. + * Get the scoringProfiles property: The scoring profiles for the index. * - * @param fields the fields value to set. - * @return the SearchIndex object itself. + * @return the scoringProfiles value. */ @Generated - public SearchIndex setFields(List fields) { - this.fields = fields; - return this; + public List getScoringProfiles() { + return this.scoringProfiles; } /** - * Get the scoringProfiles property: The scoring profiles for the index. + * Set the scoringProfiles property: The scoring profiles for the index. * - * @return the scoringProfiles value. + * @param scoringProfiles the scoringProfiles value to set. + * @return the SearchIndex object itself. */ - @Generated - public List getScoringProfiles() { - return this.scoringProfiles; + public SearchIndex setScoringProfiles(ScoringProfile... scoringProfiles) { + this.scoringProfiles = (scoringProfiles == null) ? null : Arrays.asList(scoringProfiles); + return this; } /** @@ -288,6 +297,17 @@ 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. + */ + public SearchIndex setSuggesters(SearchSuggester... suggesters) { + this.suggesters = (suggesters == null) ? null : Arrays.asList(suggesters); + return this; + } + /** * Set the suggesters property: The suggesters for the index. * @@ -310,6 +330,17 @@ 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. + */ + public SearchIndex setAnalyzers(LexicalAnalyzer... analyzers) { + this.analyzers = (analyzers == null) ? null : Arrays.asList(analyzers); + return this; + } + /** * Set the analyzers property: The analyzers for the index. * @@ -332,6 +363,17 @@ 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. + */ + public SearchIndex setTokenizers(LexicalTokenizer... tokenizers) { + this.tokenizers = (tokenizers == null) ? null : Arrays.asList(tokenizers); + return this; + } + /** * Set the tokenizers property: The tokenizers for the index. * @@ -354,6 +396,17 @@ 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. + */ + public SearchIndex setTokenFilters(TokenFilter... tokenFilters) { + this.tokenFilters = (tokenFilters == null) ? null : Arrays.asList(tokenFilters); + return this; + } + /** * Set the tokenFilters property: The token filters for the index. * @@ -376,6 +429,17 @@ 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. + */ + public SearchIndex setCharFilters(CharFilter... charFilters) { + this.charFilters = (charFilters == null) ? null : Arrays.asList(charFilters); + return this; + } + /** * Set the charFilters property: The character filters for the index. * @@ -398,6 +462,17 @@ 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. + */ + public SearchIndex setNormalizers(LexicalNormalizer... normalizers) { + this.normalizers = (normalizers == null) ? null : Arrays.asList(normalizers); + return this; + } + /** * Set the normalizers property: The normalizers for the index. * @@ -539,8 +614,7 @@ public SearchIndex setPermissionFilterOption(SearchIndexPermissionFilterOption p } /** - * Get the purviewEnabled property: A value indicating whether the index is leveraging Purview-specific features. - * This property defaults to false and cannot be changed after index creation. + * Get the purviewEnabled property: A value indicating whether Purview is enabled for the index. * * @return the purviewEnabled value. */ @@ -550,8 +624,7 @@ public Boolean isPurviewEnabled() { } /** - * Set the purviewEnabled property: A value indicating whether the index is leveraging Purview-specific features. - * This property defaults to false and cannot be changed after index creation. + * Set the purviewEnabled property: A value indicating whether Purview is enabled for the index. * * @param purviewEnabled the purviewEnabled value to set. * @return the SearchIndex object itself. @@ -592,8 +665,8 @@ public SearchIndex setETag(String eTag) { public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); - jsonWriter.writeStringField("description", this.description); jsonWriter.writeArrayField("fields", this.fields, (writer, element) -> writer.writeJson(element)); + jsonWriter.writeStringField("description", this.description); jsonWriter.writeArrayField("scoringProfiles", this.scoringProfiles, (writer, element) -> writer.writeJson(element)); jsonWriter.writeStringField("defaultScoringProfile", this.defaultScoringProfile); @@ -627,10 +700,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - String description = null; List fields = null; + String description = null; List scoringProfiles = null; String defaultScoringProfile = null; CorsOptions corsOptions = null; @@ -652,11 +724,10 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { reader.nextToken(); if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; - } else if ("description".equals(fieldName)) { - description = reader.getString(); } else if ("fields".equals(fieldName)) { fields = reader.readArray(reader1 -> SearchField.fromJson(reader1)); + } else if ("description".equals(fieldName)) { + description = reader.getString(); } else if ("scoringProfiles".equals(fieldName)) { scoringProfiles = reader.readArray(reader1 -> ScoringProfile.fromJson(reader1)); } else if ("defaultScoringProfile".equals(fieldName)) { @@ -693,117 +764,25 @@ public static SearchIndex fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - if (nameFound) { - SearchIndex deserializedSearchIndex = new SearchIndex(name); - deserializedSearchIndex.description = description; - 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.permissionFilterOption = permissionFilterOption; - deserializedSearchIndex.purviewEnabled = purviewEnabled; - deserializedSearchIndex.eTag = eTag; - return deserializedSearchIndex; - } - throw new IllegalStateException("Missing required property: name"); + SearchIndex deserializedSearchIndex = new SearchIndex(name, fields); + deserializedSearchIndex.description = description; + 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.permissionFilterOption = permissionFilterOption; + deserializedSearchIndex.purviewEnabled = purviewEnabled; + 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/SearchIndexFieldReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexFieldReference.java index 26159fd8908c..63d93701d68d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexFieldReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexFieldReference.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -15,19 +12,20 @@ import java.io.IOException; /** - * The SearchIndexFieldReference model. + * Field reference for a search index. */ @Immutable public final class SearchIndexFieldReference implements JsonSerializable { + /* - * The name property. + * The name of the field. */ @Generated private final String name; /** * Creates an instance of SearchIndexFieldReference class. - * + * * @param name the name value to set. */ @Generated @@ -36,8 +34,8 @@ public SearchIndexFieldReference(String name) { } /** - * Get the name property: The name property. - * + * Get the name property: The name of the field. + * * @return the name value. */ @Generated @@ -58,7 +56,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexFieldReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexFieldReference if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -68,23 +66,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SearchIndexFieldReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { name = reader.getString(); - nameFound = true; } else { reader.skipChildren(); } } - if (nameFound) { - return new SearchIndexFieldReference(name); - } - throw new IllegalStateException("Missing required property: name"); + return new SearchIndexFieldReference(name); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSource.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSource.java index 27c7f01462d5..b471220fbd93 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSource.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSource.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,14 +9,13 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Knowledge Source targeting a search index. */ @Fluent public final class SearchIndexKnowledgeSource extends KnowledgeSource { + /* * The type of the knowledge source. */ @@ -34,7 +30,7 @@ public final class SearchIndexKnowledgeSource extends KnowledgeSource { /** * Creates an instance of SearchIndexKnowledgeSource class. - * + * * @param name the name value to set. * @param searchIndexParameters the searchIndexParameters value to set. */ @@ -46,7 +42,7 @@ public SearchIndexKnowledgeSource(String name, SearchIndexKnowledgeSourceParamet /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -57,7 +53,7 @@ public KnowledgeSourceKind getKind() { /** * Get the searchIndexParameters property: The parameters for the knowledge source. - * + * * @return the searchIndexParameters value. */ @Generated @@ -113,7 +109,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexKnowledgeSource from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexKnowledgeSource if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -123,21 +119,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SearchIndexKnowledgeSource fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String description = null; String eTag = null; SearchResourceEncryptionKey encryptionKey = null; - boolean searchIndexParametersFound = false; SearchIndexKnowledgeSourceParameters searchIndexParameters = null; KnowledgeSourceKind kind = KnowledgeSourceKind.SEARCH_INDEX; 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 ("@odata.etag".equals(fieldName)) { @@ -146,33 +138,19 @@ public static SearchIndexKnowledgeSource fromJson(JsonReader jsonReader) throws encryptionKey = SearchResourceEncryptionKey.fromJson(reader); } else if ("searchIndexParameters".equals(fieldName)) { searchIndexParameters = SearchIndexKnowledgeSourceParameters.fromJson(reader); - searchIndexParametersFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeSourceKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (nameFound && searchIndexParametersFound) { - SearchIndexKnowledgeSource deserializedSearchIndexKnowledgeSource - = new SearchIndexKnowledgeSource(name, searchIndexParameters); - deserializedSearchIndexKnowledgeSource.setDescription(description); - deserializedSearchIndexKnowledgeSource.setETag(eTag); - deserializedSearchIndexKnowledgeSource.setEncryptionKey(encryptionKey); - deserializedSearchIndexKnowledgeSource.kind = kind; - - return deserializedSearchIndexKnowledgeSource; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!searchIndexParametersFound) { - missingProperties.add("searchIndexParameters"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SearchIndexKnowledgeSource deserializedSearchIndexKnowledgeSource + = new SearchIndexKnowledgeSource(name, searchIndexParameters); + deserializedSearchIndexKnowledgeSource.setDescription(description); + deserializedSearchIndexKnowledgeSource.setETag(eTag); + deserializedSearchIndexKnowledgeSource.setEncryptionKey(encryptionKey); + deserializedSearchIndexKnowledgeSource.kind = kind; + return deserializedSearchIndexKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSourceParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSourceParameters.java index 2cf11752e6b2..4041c8e0bed1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSourceParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSourceParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -21,6 +19,7 @@ @Fluent public final class SearchIndexKnowledgeSourceParameters implements JsonSerializable { + /* * The name of the Search index. */ @@ -47,7 +46,7 @@ public final class SearchIndexKnowledgeSourceParameters /** * Creates an instance of SearchIndexKnowledgeSourceParameters class. - * + * * @param searchIndexName the searchIndexName value to set. */ @Generated @@ -57,7 +56,7 @@ public SearchIndexKnowledgeSourceParameters(String searchIndexName) { /** * Get the searchIndexName property: The name of the Search index. - * + * * @return the searchIndexName value. */ @Generated @@ -67,7 +66,7 @@ public String getSearchIndexName() { /** * Get the sourceDataFields property: Used to request additional fields for referenced source data. - * + * * @return the sourceDataFields value. */ @Generated @@ -77,7 +76,18 @@ public List getSourceDataFields() { /** * Set the sourceDataFields property: Used to request additional fields for referenced source data. - * + * + * @param sourceDataFields the sourceDataFields value to set. + * @return the SearchIndexKnowledgeSourceParameters object itself. + */ + public SearchIndexKnowledgeSourceParameters setSourceDataFields(SearchIndexFieldReference... sourceDataFields) { + this.sourceDataFields = (sourceDataFields == null) ? null : Arrays.asList(sourceDataFields); + return this; + } + + /** + * Set the sourceDataFields property: Used to request additional fields for referenced source data. + * * @param sourceDataFields the sourceDataFields value to set. * @return the SearchIndexKnowledgeSourceParameters object itself. */ @@ -89,7 +99,7 @@ public SearchIndexKnowledgeSourceParameters setSourceDataFields(List getSearchFields() { /** * Set the searchFields property: Used to restrict which fields to search on the search index. - * + * + * @param searchFields the searchFields value to set. + * @return the SearchIndexKnowledgeSourceParameters object itself. + */ + public SearchIndexKnowledgeSourceParameters setSearchFields(SearchIndexFieldReference... searchFields) { + this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); + return this; + } + + /** + * Set the searchFields property: Used to restrict which fields to search on the search index. + * * @param searchFields the searchFields value to set. * @return the SearchIndexKnowledgeSourceParameters object itself. */ @@ -112,7 +133,7 @@ public SearchIndexKnowledgeSourceParameters setSearchFields(List { - boolean searchIndexNameFound = false; String searchIndexName = null; List sourceDataFields = null; List searchFields = null; @@ -168,10 +188,8 @@ public static SearchIndexKnowledgeSourceParameters fromJson(JsonReader jsonReade while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("searchIndexName".equals(fieldName)) { searchIndexName = reader.getString(); - searchIndexNameFound = true; } else if ("sourceDataFields".equals(fieldName)) { sourceDataFields = reader.readArray(reader1 -> SearchIndexFieldReference.fromJson(reader1)); } else if ("searchFields".equals(fieldName)) { @@ -182,16 +200,12 @@ public static SearchIndexKnowledgeSourceParameters fromJson(JsonReader jsonReade reader.skipChildren(); } } - if (searchIndexNameFound) { - SearchIndexKnowledgeSourceParameters deserializedSearchIndexKnowledgeSourceParameters - = new SearchIndexKnowledgeSourceParameters(searchIndexName); - deserializedSearchIndexKnowledgeSourceParameters.sourceDataFields = sourceDataFields; - deserializedSearchIndexKnowledgeSourceParameters.searchFields = searchFields; - deserializedSearchIndexKnowledgeSourceParameters.semanticConfigurationName = semanticConfigurationName; - - return deserializedSearchIndexKnowledgeSourceParameters; - } - throw new IllegalStateException("Missing required property: searchIndexName"); + SearchIndexKnowledgeSourceParameters deserializedSearchIndexKnowledgeSourceParameters + = new SearchIndexKnowledgeSourceParameters(searchIndexName); + deserializedSearchIndexKnowledgeSourceParameters.sourceDataFields = sourceDataFields; + deserializedSearchIndexKnowledgeSourceParameters.searchFields = searchFields; + deserializedSearchIndexKnowledgeSourceParameters.semanticConfigurationName = semanticConfigurationName; + return deserializedSearchIndexKnowledgeSourceParameters; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java index 983be2755ed1..ccd3ead50ee1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,21 +11,22 @@ * A value indicating whether permission filtering is enabled for the index. */ public final class SearchIndexPermissionFilterOption extends ExpandableStringEnum { + /** - * Static value enabled for SearchIndexPermissionFilterOption. + * enabled. */ @Generated public static final SearchIndexPermissionFilterOption ENABLED = fromString("enabled"); /** - * Static value disabled for SearchIndexPermissionFilterOption. + * disabled. */ @Generated public static final SearchIndexPermissionFilterOption DISABLED = fromString("disabled"); /** * Creates a new instance of SearchIndexPermissionFilterOption value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -38,7 +36,7 @@ public SearchIndexPermissionFilterOption() { /** * Creates or finds a SearchIndexPermissionFilterOption from its string representation. - * + * * @param name a name to look for. * @return the corresponding SearchIndexPermissionFilterOption. */ @@ -49,7 +47,7 @@ public static SearchIndexPermissionFilterOption fromString(String name) { /** * Gets known SearchIndexPermissionFilterOption values. - * + * * @return known SearchIndexPermissionFilterOption values. */ @Generated 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/indexes/models/SearchIndexer.java index 85e2c1cf3a52..aefd8050ef23 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/indexes/models/SearchIndexer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -37,7 +35,7 @@ public final class SearchIndexer implements JsonSerializable { * The name of the datasource from which this indexer reads data. */ @Generated - private String dataSourceName; + private final String dataSourceName; /* * The name of the skillset executing with this indexer. @@ -49,7 +47,7 @@ public final class SearchIndexer implements JsonSerializable { * The name of the index to which this indexer writes data. */ @Generated - private String targetIndexName; + private final String targetIndexName; /* * The schedule for this indexer. @@ -110,10 +108,14 @@ public final class SearchIndexer implements JsonSerializable { * 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. */ @Generated - public SearchIndexer(String name) { + public SearchIndexer(String name, String dataSourceName, String targetIndexName) { this.name = name; + this.dataSourceName = dataSourceName; + this.targetIndexName = targetIndexName; } /** @@ -158,18 +160,6 @@ 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. - */ - @Generated - public SearchIndexer setDataSourceName(String dataSourceName) { - this.dataSourceName = dataSourceName; - return this; - } - /** * Get the skillsetName property: The name of the skillset executing with this indexer. * @@ -202,18 +192,6 @@ 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. - */ - @Generated - public SearchIndexer setTargetIndexName(String targetIndexName) { - this.targetIndexName = targetIndexName; - return this; - } - /** * Get the schedule property: The schedule for this indexer. * @@ -269,6 +247,18 @@ public List getFieldMappings() { return this.fieldMappings; } + /** + * 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 fieldMappings property: Defines mappings between fields in the data source and corresponding target * fields in the index. @@ -293,6 +283,18 @@ public List getOutputFieldMappings() { return this.outputFieldMappings; } + /** + * 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; + } + /** * Set the outputFieldMappings property: Output field mappings are applied after enrichment and immediately before * indexing. @@ -418,10 +420,10 @@ public SearchIndexer setCache(SearchIndexerCache cache) { 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)); @@ -446,12 +448,11 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -465,15 +466,14 @@ public static SearchIndexer fromJson(JsonReader jsonReader) throws IOException { 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)) { @@ -494,60 +494,18 @@ 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/indexes/models/SearchIndexerCache.java index cfcddc5b65af..67fde88b85de 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/indexes/models/SearchIndexerCache.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -15,10 +12,11 @@ import java.io.IOException; /** - * The SearchIndexerCache model. + * The type of the cache. */ @Fluent public final class SearchIndexerCache implements JsonSerializable { + /* * A guid for the SearchIndexerCache. */ @@ -55,7 +53,7 @@ public SearchIndexerCache() { /** * Get the id property: A guid for the SearchIndexerCache. - * + * * @return the id value. */ @Generated @@ -65,7 +63,7 @@ public String getId() { /** * Set the id property: A guid for the SearchIndexerCache. - * + * * @param id the id value to set. * @return the SearchIndexerCache object itself. */ @@ -78,7 +76,7 @@ public SearchIndexerCache setId(String id) { /** * Get the storageConnectionString property: The connection string to the storage account where the cache data will * be persisted. - * + * * @return the storageConnectionString value. */ @Generated @@ -89,7 +87,7 @@ public String getStorageConnectionString() { /** * Set the storageConnectionString property: The connection string to the storage account where the cache data will * be persisted. - * + * * @param storageConnectionString the storageConnectionString value to set. * @return the SearchIndexerCache object itself. */ @@ -101,7 +99,7 @@ public SearchIndexerCache setStorageConnectionString(String storageConnectionStr /** * Get the enableReprocessing property: Specifies whether incremental reprocessing is enabled. - * + * * @return the enableReprocessing value. */ @Generated @@ -111,7 +109,7 @@ public Boolean isEnableReprocessing() { /** * Set the enableReprocessing property: Specifies whether incremental reprocessing is enabled. - * + * * @param enableReprocessing the enableReprocessing value to set. * @return the SearchIndexerCache object itself. */ @@ -126,7 +124,7 @@ public SearchIndexerCache setEnableReprocessing(Boolean enableReprocessing) { * 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 @@ -139,7 +137,7 @@ public SearchIndexerDataIdentity getIdentity() { * 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. */ @@ -165,7 +163,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerCache from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerCache if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -178,7 +176,6 @@ public static SearchIndexerCache fromJson(JsonReader jsonReader) throws IOExcept while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { deserializedSearchIndexerCache.id = reader.getString(); } else if ("storageConnectionString".equals(fieldName)) { @@ -191,7 +188,6 @@ public static SearchIndexerCache fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - return deserializedSearchIndexerCache; }); } 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/indexes/models/SearchIndexerDataContainer.java index 63c75d7920a6..77866a200080 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/indexes/models/SearchIndexerDataContainer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @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. @@ -35,7 +33,7 @@ public final class SearchIndexerDataContainer implements JsonSerializable { - boolean nameFound = false; String name = null; String query = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedSearchIndexerDataContainer; - } - throw new IllegalStateException("Missing required property: name"); + SearchIndexerDataContainer deserializedSearchIndexerDataContainer = new SearchIndexerDataContainer(name); + deserializedSearchIndexerDataContainer.query = query; + 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/indexes/models/SearchIndexerDataIdentity.java index 75b6a2ff5619..0de5f0adf7af 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/indexes/models/SearchIndexerDataIdentity.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,6 +16,7 @@ */ @Immutable public class SearchIndexerDataIdentity implements JsonSerializable { + /* * A URI fragment specifying the type of identity. */ @@ -34,7 +32,7 @@ public SearchIndexerDataIdentity() { /** * Get the odataType property: A URI fragment specifying the type of identity. - * + * * @return the odataType value. */ @Generated @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerDataIdentity from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerDataIdentity if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -66,7 +64,8 @@ public static SearchIndexerDataIdentity fromJson(JsonReader jsonReader) throws I return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -96,14 +95,12 @@ static SearchIndexerDataIdentity fromJsonKnownDiscriminator(JsonReader jsonReade while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedSearchIndexerDataIdentity.odataType = reader.getString(); } else { reader.skipChildren(); } } - return deserializedSearchIndexerDataIdentity; }); } 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/indexes/models/SearchIndexerDataNoneIdentity.java index f4e37556d087..6d66a63b9c74 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/indexes/models/SearchIndexerDataNoneIdentity.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -18,6 +15,7 @@ */ @Immutable public final class SearchIndexerDataNoneIdentity extends SearchIndexerDataIdentity { + /* * A URI fragment specifying the type of identity. */ @@ -33,7 +31,7 @@ public SearchIndexerDataNoneIdentity() { /** * Get the odataType property: A URI fragment specifying the type of identity. - * + * * @return the odataType value. */ @Generated @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerDataNoneIdentity from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerDataNoneIdentity if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -69,14 +67,12 @@ public static SearchIndexerDataNoneIdentity fromJson(JsonReader jsonReader) thro while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedSearchIndexerDataNoneIdentity.odataType = reader.getString(); } else { reader.skipChildren(); } } - return 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/indexes/models/SearchIndexerDataSourceConnection.java index c502a9fe7343..3f23a0fa1fbc 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/indexes/models/SearchIndexerDataSourceConnection.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,8 +9,8 @@ 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; +import java.util.Arrays; import java.util.List; /** @@ -37,7 +35,7 @@ public final class SearchIndexerDataSourceConnection implements JsonSerializable * The type of the datasource. */ @Generated - private SearchIndexerDataSourceType type; + private final SearchIndexerDataSourceType type; /* * A specific type of the data source, in case the resource is capable of different modalities. For example, @@ -50,13 +48,13 @@ public final class SearchIndexerDataSourceConnection implements JsonSerializable * Credentials for the datasource. */ @Generated - private DataSourceCredentials credentials; + private final DataSourceCredentials credentials; /* * The data container for the datasource. */ @Generated - private SearchIndexerDataContainer container; + private final SearchIndexerDataContainer container; /* * An explicit managed identity to use for this datasource. If not specified and the connection string is a managed @@ -106,10 +104,17 @@ public final class SearchIndexerDataSourceConnection implements JsonSerializable * Creates an instance of SearchIndexerDataSourceConnection 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. */ @Generated - public SearchIndexerDataSourceConnection(String name) { + public SearchIndexerDataSourceConnection(String name, SearchIndexerDataSourceType type, + DataSourceCredentials credentials, SearchIndexerDataContainer container) { this.name = name; + this.type = type; + this.credentials = credentials; + this.container = container; } /** @@ -154,18 +159,6 @@ 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. - */ - @Generated - public SearchIndexerDataSourceConnection setType(SearchIndexerDataSourceType type) { - this.type = type; - return this; - } - /** * Get the subType property: A specific type of the data source, in case the resource is capable of different * modalities. For example, 'MongoDb' for certain 'cosmosDb' accounts. @@ -178,25 +171,23 @@ public String getSubType() { } /** - * Get the container property: The data container for the datasource. + * Get the credentials property: Credentials for the datasource. * - * @return the container value. + * @return the credentials value. */ @Generated - public SearchIndexerDataContainer getContainer() { - return this.container; + public DataSourceCredentials getCredentials() { + return this.credentials; } /** - * Set the container property: The data container for the datasource. + * Get the container property: The data container for the datasource. * - * @param container the container value to set. - * @return the SearchIndexerDataSourceConnection object itself. + * @return the container value. */ @Generated - public SearchIndexerDataSourceConnection setContainer(SearchIndexerDataContainer container) { - this.container = container; - return this; + public SearchIndexerDataContainer getContainer() { + return this.container; } /** @@ -235,6 +226,19 @@ public List getIndexerPermissionOptions() { return this.indexerPermissionOptions; } + /** + * Set the indexerPermissionOptions property: Ingestion options with various types of permission data. + * + * @param indexerPermissionOptions the indexerPermissionOptions value to set. + * @return the SearchIndexerDataSourceConnection object itself. + */ + public SearchIndexerDataSourceConnection + setIndexerPermissionOptions(IndexerPermissionOption... indexerPermissionOptions) { + this.indexerPermissionOptions + = (indexerPermissionOptions == null) ? null : Arrays.asList(indexerPermissionOptions); + return this; + } + /** * Set the indexerPermissionOptions property: Ingestion options with various types of permission data. * @@ -358,10 +362,10 @@ public SearchIndexerDataSourceConnection setEncryptionKey(SearchResourceEncrypti 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.writeArrayField("indexerPermissionOptions", this.indexerPermissionOptions, (writer, element) -> writer.writeString(element == null ? null : element.toString())); @@ -384,13 +388,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; - String description = null; SearchIndexerDataSourceType type = null; - String subType = null; DataSourceCredentials credentials = null; SearchIndexerDataContainer container = null; + String description = null; + String subType = null; SearchIndexerDataIdentity identity = null; List indexerPermissionOptions = null; DataChangeDetectionPolicy dataChangeDetectionPolicy = null; @@ -402,17 +405,16 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) 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 ("subType".equals(fieldName)) { - subType = 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 ("subType".equals(fieldName)) { + subType = reader.getString(); } else if ("identity".equals(fieldName)) { identity = SearchIndexerDataIdentity.fromJson(reader); } else if ("indexerPermissionOptions".equals(fieldName)) { @@ -430,66 +432,17 @@ public static SearchIndexerDataSourceConnection fromJson(JsonReader jsonReader) reader.skipChildren(); } } - if (nameFound) { - SearchIndexerDataSourceConnection deserializedSearchIndexerDataSourceConnection - = new SearchIndexerDataSourceConnection(name); - deserializedSearchIndexerDataSourceConnection.description = description; - deserializedSearchIndexerDataSourceConnection.type = type; - deserializedSearchIndexerDataSourceConnection.subType = subType; - deserializedSearchIndexerDataSourceConnection.credentials = credentials; - deserializedSearchIndexerDataSourceConnection.container = container; - deserializedSearchIndexerDataSourceConnection.identity = identity; - deserializedSearchIndexerDataSourceConnection.indexerPermissionOptions = indexerPermissionOptions; - deserializedSearchIndexerDataSourceConnection.dataChangeDetectionPolicy = dataChangeDetectionPolicy; - deserializedSearchIndexerDataSourceConnection.dataDeletionDetectionPolicy = dataDeletionDetectionPolicy; - deserializedSearchIndexerDataSourceConnection.eTag = eTag; - deserializedSearchIndexerDataSourceConnection.encryptionKey = encryptionKey; - return deserializedSearchIndexerDataSourceConnection; - } - throw new IllegalStateException("Missing required property: name"); + SearchIndexerDataSourceConnection deserializedSearchIndexerDataSourceConnection + = new SearchIndexerDataSourceConnection(name, type, credentials, container); + deserializedSearchIndexerDataSourceConnection.description = description; + deserializedSearchIndexerDataSourceConnection.subType = subType; + deserializedSearchIndexerDataSourceConnection.identity = identity; + deserializedSearchIndexerDataSourceConnection.indexerPermissionOptions = indexerPermissionOptions; + deserializedSearchIndexerDataSourceConnection.dataChangeDetectionPolicy = dataChangeDetectionPolicy; + deserializedSearchIndexerDataSourceConnection.dataDeletionDetectionPolicy = dataDeletionDetectionPolicy; + deserializedSearchIndexerDataSourceConnection.eTag = eTag; + deserializedSearchIndexerDataSourceConnection.encryptionKey = encryptionKey; + return deserializedSearchIndexerDataSourceConnection; }); } - - /** - * 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/indexes/models/SearchIndexerDataSourceType.java index ba00efa60a74..105499ecd04a 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/indexes/models/SearchIndexerDataSourceType.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Defines the type of a datasource. */ public final class SearchIndexerDataSourceType extends ExpandableStringEnum { + /** * Indicates an Azure SQL datasource. */ @@ -64,7 +62,7 @@ public final class SearchIndexerDataSourceType extends ExpandableStringEnum { - boolean resourceIdFound = false; String resourceId = null; String odataType = "#Microsoft.Azure.Search.DataUserAssignedIdentity"; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedSearchIndexerDataUserAssignedIdentity; - } - throw new IllegalStateException("Missing required property: userAssignedIdentity"); + SearchIndexerDataUserAssignedIdentity deserializedSearchIndexerDataUserAssignedIdentity + = new SearchIndexerDataUserAssignedIdentity(resourceId); + deserializedSearchIndexerDataUserAssignedIdentity.odataType = odataType; + 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/indexes/models/SearchIndexerError.java index bbc6902e6843..6709eda33a99 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/indexes/models/SearchIndexerError.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,14 +10,13 @@ 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. */ @Immutable public final class SearchIndexerError implements JsonSerializable { + /* * The key of the item for which indexing failed. */ @@ -31,7 +27,7 @@ public final class SearchIndexerError implements JsonSerializable { - boolean errorMessageFound = false; - String errorMessage = null; - boolean statusCodeFound = false; - int statusCode = 0; - String key = null; - String name = null; - String details = null; - String documentationLink = null; + SearchIndexerError deserializedSearchIndexerError = new SearchIndexerError(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("errorMessage".equals(fieldName)) { - errorMessage = reader.getString(); - errorMessageFound = true; + deserializedSearchIndexerError.errorMessage = reader.getString(); } else if ("statusCode".equals(fieldName)) { - statusCode = reader.getInt(); - statusCodeFound = true; + deserializedSearchIndexerError.statusCode = reader.getInt(); } else if ("key".equals(fieldName)) { - key = reader.getString(); + deserializedSearchIndexerError.key = reader.getString(); } else if ("name".equals(fieldName)) { - name = reader.getString(); + deserializedSearchIndexerError.name = reader.getString(); } else if ("details".equals(fieldName)) { - details = reader.getString(); + deserializedSearchIndexerError.details = reader.getString(); } else if ("documentationLink".equals(fieldName)) { - documentationLink = reader.getString(); + deserializedSearchIndexerError.documentationLink = reader.getString(); } else { 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"); - } - - 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/indexes/models/SearchIndexerIndexProjection.java index 6b16ee454681..3ebb43f56033 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/indexes/models/SearchIndexerIndexProjection.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @Fluent public final class SearchIndexerIndexProjection implements JsonSerializable { + /* * A list of projections to be performed to secondary search indexes. */ @@ -35,7 +34,16 @@ public final class SearchIndexerIndexProjection implements JsonSerializable s /** * Get the selectors property: A list of projections to be performed to secondary search indexes. - * + * * @return the selectors value. */ @Generated @@ -56,7 +64,7 @@ public List getSelectors() { /** * 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 @@ -67,7 +75,7 @@ public SearchIndexerIndexProjectionsParameters getParameters() { /** * 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. */ @@ -91,7 +99,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerIndexProjection from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerIndexProjection if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -101,30 +109,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedSearchIndexerIndexProjection; - } - throw new IllegalStateException("Missing required property: selectors"); + SearchIndexerIndexProjection deserializedSearchIndexerIndexProjection + = new SearchIndexerIndexProjection(selectors); + deserializedSearchIndexerIndexProjection.parameters = parameters; + 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/indexes/models/SearchIndexerIndexProjectionSelector.java index 63c38e7b3661..ba9f03de8100 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/indexes/models/SearchIndexerIndexProjectionSelector.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,7 +10,7 @@ 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; /** @@ -22,6 +19,7 @@ @Immutable public final class SearchIndexerIndexProjectionSelector implements JsonSerializable { + /* * Name of the search index to project to. Must have a key field with the 'keyword' analyzer set. */ @@ -50,7 +48,23 @@ public final class SearchIndexerIndexProjectionSelector /** * Creates an instance of SearchIndexerIndexProjectionSelector class. - * + * + * @param targetIndexName the targetIndexName value to set. + * @param parentKeyFieldName the parentKeyFieldName value to set. + * @param sourceContext the sourceContext value to set. + * @param mappings the mappings value to set. + */ + public SearchIndexerIndexProjectionSelector(String targetIndexName, String parentKeyFieldName, String sourceContext, + InputFieldMappingEntry... mappings) { + this.targetIndexName = targetIndexName; + this.parentKeyFieldName = parentKeyFieldName; + this.sourceContext = sourceContext; + this.mappings = (mappings == null) ? null : Arrays.asList(mappings); + } + + /** + * Creates an instance of SearchIndexerIndexProjectionSelector class. + * * @param targetIndexName the targetIndexName value to set. * @param parentKeyFieldName the parentKeyFieldName value to set. * @param sourceContext the sourceContext value to set. @@ -68,7 +82,7 @@ public SearchIndexerIndexProjectionSelector(String targetIndexName, String paren /** * Get the targetIndexName property: Name of the search index to project to. Must have a key field with the * 'keyword' analyzer set. - * + * * @return the targetIndexName value. */ @Generated @@ -79,7 +93,7 @@ public String getTargetIndexName() { /** * Get the parentKeyFieldName property: 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. - * + * * @return the parentKeyFieldName value. */ @Generated @@ -90,7 +104,7 @@ public String getParentKeyFieldName() { /** * Get the sourceContext property: Source context for the projections. Represents the cardinality at which the * document will be split into multiple sub documents. - * + * * @return the sourceContext value. */ @Generated @@ -101,7 +115,7 @@ public String getSourceContext() { /** * 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 @@ -125,7 +139,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerIndexProjectionSelector from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerIndexProjectionSelector if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -135,54 +149,27 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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(); reader.nextToken(); - 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/indexes/models/SearchIndexerIndexProjectionsParameters.java index b505afa137ae..73e0c50f2b52 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/indexes/models/SearchIndexerIndexProjectionsParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -23,6 +20,7 @@ @Fluent public final class SearchIndexerIndexProjectionsParameters implements JsonSerializable { + /* * Defines behavior of the index projections in relation to the rest of the indexer. */ @@ -46,7 +44,7 @@ public SearchIndexerIndexProjectionsParameters() { /** * Get the projectionMode property: Defines behavior of the index projections in relation to the rest of the * indexer. - * + * * @return the projectionMode value. */ @Generated @@ -57,7 +55,7 @@ public IndexProjectionMode getProjectionMode() { /** * Set the projectionMode property: Defines behavior of the index projections in relation to the rest of the * indexer. - * + * * @param projectionMode the projectionMode value to set. * @return the SearchIndexerIndexProjectionsParameters object itself. */ @@ -70,7 +68,7 @@ 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. - * + * * @return the additionalProperties value. */ @Generated @@ -81,7 +79,7 @@ public Map getAdditionalProperties() { /** * 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. - * + * * @param additionalProperties the additionalProperties value to set. * @return the SearchIndexerIndexProjectionsParameters object itself. */ @@ -110,7 +108,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerIndexProjectionsParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerIndexProjectionsParameters if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -125,7 +123,6 @@ public static SearchIndexerIndexProjectionsParameters fromJson(JsonReader jsonRe while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("projectionMode".equals(fieldName)) { deserializedSearchIndexerIndexProjectionsParameters.projectionMode = IndexProjectionMode.fromString(reader.getString()); @@ -133,12 +130,10 @@ public static SearchIndexerIndexProjectionsParameters fromJson(JsonReader jsonRe if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); } } deserializedSearchIndexerIndexProjectionsParameters.additionalProperties = additionalProperties; - return deserializedSearchIndexerIndexProjectionsParameters; }); } 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/indexes/models/SearchIndexerKnowledgeStore.java index 6586cf906a1b..2f8095ef4773 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/indexes/models/SearchIndexerKnowledgeStore.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,7 +10,7 @@ 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; /** @@ -21,6 +18,7 @@ */ @Fluent public final class SearchIndexerKnowledgeStore implements JsonSerializable { + /* * The connection string to the storage account projections will be stored in. */ @@ -51,7 +49,19 @@ public final class SearchIndexerKnowledgeStore implements JsonSerializable getProjections() { * 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 @@ -101,7 +111,7 @@ public SearchIndexerDataIdentity getIdentity() { * 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. */ @@ -114,7 +124,7 @@ public SearchIndexerKnowledgeStore setIdentity(SearchIndexerDataIdentity identit /** * 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 @@ -125,7 +135,7 @@ public SearchIndexerKnowledgeStoreParameters getParameters() { /** * 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. */ @@ -151,7 +161,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerKnowledgeStore from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerKnowledgeStore if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -161,22 +171,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -185,24 +190,11 @@ public static SearchIndexerKnowledgeStore fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (storageConnectionStringFound && projectionsFound) { - 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)); + SearchIndexerKnowledgeStore deserializedSearchIndexerKnowledgeStore + = new SearchIndexerKnowledgeStore(storageConnectionString, projections); + deserializedSearchIndexerKnowledgeStore.identity = identity; + deserializedSearchIndexerKnowledgeStore.parameters = parameters; + return deserializedSearchIndexerKnowledgeStore; }); } } 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 index 989443b05df3..9d23a4d59714 100644 --- 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 @@ -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; 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; @@ -83,6 +83,15 @@ public SearchIndexerKnowledgeStoreBlobProjectionSelector setSourceContext(String return this; } + /** + * {@inheritDoc} + */ + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setInputs(InputFieldMappingEntry... inputs) { + super.setInputs(inputs); + return this; + } + /** * {@inheritDoc} */ @@ -108,4 +117,52 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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/indexes/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java index c460854ecc7d..b4054839d61a 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/indexes/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,9 +17,10 @@ @Fluent public final class SearchIndexerKnowledgeStoreFileProjectionSelector extends SearchIndexerKnowledgeStoreBlobProjectionSelector { + /** * Creates an instance of SearchIndexerKnowledgeStoreFileProjectionSelector class. - * + * * @param storageContainer the storageContainer value to set. */ @Generated @@ -70,6 +68,15 @@ public SearchIndexerKnowledgeStoreFileProjectionSelector setSourceContext(String return this; } + /** + * {@inheritDoc} + */ + @Override + public SearchIndexerKnowledgeStoreFileProjectionSelector setInputs(InputFieldMappingEntry... inputs) { + super.setInputs(inputs); + return this; + } + /** * {@inheritDoc} */ @@ -98,7 +105,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerKnowledgeStoreFileProjectionSelector from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerKnowledgeStoreFileProjectionSelector if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -108,7 +115,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SearchIndexerKnowledgeStoreFileProjectionSelector fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean storageContainerFound = false; String storageContainer = null; String referenceKeyName = null; String generatedKeyName = null; @@ -118,10 +124,8 @@ public static SearchIndexerKnowledgeStoreFileProjectionSelector fromJson(JsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("storageContainer".equals(fieldName)) { storageContainer = reader.getString(); - storageContainerFound = true; } else if ("referenceKeyName".equals(fieldName)) { referenceKeyName = reader.getString(); } else if ("generatedKeyName".equals(fieldName)) { @@ -136,18 +140,14 @@ 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); - - return deserializedSearchIndexerKnowledgeStoreFileProjectionSelector; - } - throw new IllegalStateException("Missing required property: storageContainer"); + SearchIndexerKnowledgeStoreFileProjectionSelector deserializedSearchIndexerKnowledgeStoreFileProjectionSelector + = new SearchIndexerKnowledgeStoreFileProjectionSelector(storageContainer); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setGeneratedKeyName(generatedKeyName); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreFileProjectionSelector.setInputs(inputs); + 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/indexes/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java index 09b9f8156120..6b08eff2327a 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/indexes/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,9 +17,10 @@ @Fluent public final class SearchIndexerKnowledgeStoreObjectProjectionSelector extends SearchIndexerKnowledgeStoreBlobProjectionSelector { + /** * Creates an instance of SearchIndexerKnowledgeStoreObjectProjectionSelector class. - * + * * @param storageContainer the storageContainer value to set. */ @Generated @@ -70,6 +68,15 @@ public SearchIndexerKnowledgeStoreObjectProjectionSelector setSourceContext(Stri return this; } + /** + * {@inheritDoc} + */ + @Override + public SearchIndexerKnowledgeStoreBlobProjectionSelector setInputs(InputFieldMappingEntry... inputs) { + super.setInputs(inputs); + return this; + } + /** * {@inheritDoc} */ @@ -98,7 +105,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerKnowledgeStoreObjectProjectionSelector from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerKnowledgeStoreObjectProjectionSelector if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -109,7 +116,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { public static SearchIndexerKnowledgeStoreObjectProjectionSelector fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean storageContainerFound = false; String storageContainer = null; String referenceKeyName = null; String generatedKeyName = null; @@ -119,10 +125,8 @@ public static SearchIndexerKnowledgeStoreObjectProjectionSelector fromJson(JsonR while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("storageContainer".equals(fieldName)) { storageContainer = reader.getString(); - storageContainerFound = true; } else if ("referenceKeyName".equals(fieldName)) { referenceKeyName = reader.getString(); } else if ("generatedKeyName".equals(fieldName)) { @@ -137,18 +141,14 @@ 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); - - return deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector; - } - throw new IllegalStateException("Missing required property: storageContainer"); + SearchIndexerKnowledgeStoreObjectProjectionSelector deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector + = new SearchIndexerKnowledgeStoreObjectProjectionSelector(storageContainer); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setGeneratedKeyName(generatedKeyName); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreObjectProjectionSelector.setInputs(inputs); + 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/indexes/models/SearchIndexerKnowledgeStoreParameters.java index 174bea05614e..2092b614c63f 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/indexes/models/SearchIndexerKnowledgeStoreParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -23,6 +20,7 @@ @Fluent public final class SearchIndexerKnowledgeStoreParameters implements JsonSerializable { + /* * Whether or not projections should synthesize a generated key name if one isn't already present. */ @@ -46,7 +44,7 @@ public SearchIndexerKnowledgeStoreParameters() { /** * Get the synthesizeGeneratedKeyName property: Whether or not projections should synthesize a generated key name if * one isn't already present. - * + * * @return the synthesizeGeneratedKeyName value. */ @Generated @@ -57,7 +55,7 @@ public Boolean isSynthesizeGeneratedKeyName() { /** * Set the synthesizeGeneratedKeyName property: Whether or not projections should synthesize a generated key name if * one isn't already present. - * + * * @param synthesizeGeneratedKeyName the synthesizeGeneratedKeyName value to set. * @return the SearchIndexerKnowledgeStoreParameters object itself. */ @@ -70,7 +68,7 @@ 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. - * + * * @return the additionalProperties value. */ @Generated @@ -81,7 +79,7 @@ public Map getAdditionalProperties() { /** * 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. - * + * * @param additionalProperties the additionalProperties value to set. * @return the SearchIndexerKnowledgeStoreParameters object itself. */ @@ -109,7 +107,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerKnowledgeStoreParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerKnowledgeStoreParameters if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -124,7 +122,6 @@ public static SearchIndexerKnowledgeStoreParameters fromJson(JsonReader jsonRead while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("synthesizeGeneratedKeyName".equals(fieldName)) { deserializedSearchIndexerKnowledgeStoreParameters.synthesizeGeneratedKeyName = reader.getNullable(JsonReader::getBoolean); @@ -132,12 +129,10 @@ public static SearchIndexerKnowledgeStoreParameters fromJson(JsonReader jsonRead if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); } } deserializedSearchIndexerKnowledgeStoreParameters.additionalProperties = additionalProperties; - return deserializedSearchIndexerKnowledgeStoreParameters; }); } 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/indexes/models/SearchIndexerKnowledgeStoreProjection.java index 29b2b0ea8e1f..8df0a8aa63fc 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/indexes/models/SearchIndexerKnowledgeStoreProjection.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -21,6 +19,7 @@ @Fluent public final class SearchIndexerKnowledgeStoreProjection implements JsonSerializable { + /* * Projections to Azure Table storage. */ @@ -48,7 +47,7 @@ public SearchIndexerKnowledgeStoreProjection() { /** * Get the tables property: Projections to Azure Table storage. - * + * * @return the tables value. */ @Generated @@ -58,7 +57,19 @@ public List getTables() { /** * Set the tables property: Projections to Azure Table storage. - * + * + * @param tables the tables value to set. + * @return the SearchIndexerKnowledgeStoreProjection object itself. + */ + public SearchIndexerKnowledgeStoreProjection + setTables(SearchIndexerKnowledgeStoreTableProjectionSelector... tables) { + this.tables = (tables == null) ? null : Arrays.asList(tables); + return this; + } + + /** + * Set the tables property: Projections to Azure Table storage. + * * @param tables the tables value to set. * @return the SearchIndexerKnowledgeStoreProjection object itself. */ @@ -71,7 +82,7 @@ public List getTables() { /** * Get the objects property: Projections to Azure Blob storage. - * + * * @return the objects value. */ @Generated @@ -81,7 +92,19 @@ public List getObjects() { /** * Set the objects property: Projections to Azure Blob storage. - * + * + * @param objects the objects value to set. + * @return the SearchIndexerKnowledgeStoreProjection object itself. + */ + public SearchIndexerKnowledgeStoreProjection + setObjects(SearchIndexerKnowledgeStoreObjectProjectionSelector... objects) { + this.objects = (objects == null) ? null : Arrays.asList(objects); + return this; + } + + /** + * Set the objects property: Projections to Azure Blob storage. + * * @param objects the objects value to set. * @return the SearchIndexerKnowledgeStoreProjection object itself. */ @@ -94,7 +117,7 @@ public List getObjects() { /** * Get the files property: Projections to Azure File storage. - * + * * @return the files value. */ @Generated @@ -104,7 +127,18 @@ public List getFiles() { /** * Set the files property: Projections to Azure File storage. - * + * + * @param files the files value to set. + * @return the SearchIndexerKnowledgeStoreProjection object itself. + */ + public SearchIndexerKnowledgeStoreProjection setFiles(SearchIndexerKnowledgeStoreFileProjectionSelector... files) { + this.files = (files == null) ? null : Arrays.asList(files); + return this; + } + + /** + * Set the files property: Projections to Azure File storage. + * * @param files the files value to set. * @return the SearchIndexerKnowledgeStoreProjection object itself. */ @@ -130,7 +164,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerKnowledgeStoreProjection from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerKnowledgeStoreProjection if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -144,7 +178,6 @@ public static SearchIndexerKnowledgeStoreProjection fromJson(JsonReader jsonRead while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("tables".equals(fieldName)) { List tables = reader .readArray(reader1 -> SearchIndexerKnowledgeStoreTableProjectionSelector.fromJson(reader1)); @@ -161,7 +194,6 @@ public static SearchIndexerKnowledgeStoreProjection fromJson(JsonReader jsonRead reader.skipChildren(); } } - return 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/indexes/models/SearchIndexerKnowledgeStoreProjectionSelector.java index 41f88f3a9b3c..b868878c9381 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/indexes/models/SearchIndexerKnowledgeStoreProjectionSelector.java @@ -1,15 +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; 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; /** @@ -154,6 +155,17 @@ public List getInputs() { return this.inputs; } + /** + * Set the inputs property: Nested inputs for complex projections. + * + * @param inputs the inputs value to set. + * @return the SearchIndexerKnowledgeStoreProjectionSelector object itself. + */ + public SearchIndexerKnowledgeStoreProjectionSelector setInputs(InputFieldMappingEntry... inputs) { + this.inputs = (inputs == null) ? null : Arrays.asList(inputs); + return this; + } + /** * Set the inputs property: Nested inputs for complex projections. * @@ -180,4 +192,40 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeArrayField("inputs", this.inputs, (writer, element) -> writer.writeJson(element)); return jsonWriter.writeEndObject(); } + + /** + * Reads an instance of SearchIndexerKnowledgeStoreProjectionSelector from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of SearchIndexerKnowledgeStoreProjectionSelector 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 SearchIndexerKnowledgeStoreProjectionSelector. + */ + @Generated + public static SearchIndexerKnowledgeStoreProjectionSelector fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + 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/indexes/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java index 2307acb2b64b..75aabe02d55e 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/indexes/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -20,6 +17,13 @@ @Fluent public final class SearchIndexerKnowledgeStoreTableProjectionSelector extends SearchIndexerKnowledgeStoreProjectionSelector { + + /* + * Name of generated key to store projection under. + */ + @Generated + private final String generatedKeyName; + /* * Name of the Azure table to store projected data in. */ @@ -28,17 +32,29 @@ public final class SearchIndexerKnowledgeStoreTableProjectionSelector /** * Creates an instance of SearchIndexerKnowledgeStoreTableProjectionSelector class. - * + * + * @param generatedKeyName the generatedKeyName value to set. * @param tableName the tableName value to set. */ @Generated - public SearchIndexerKnowledgeStoreTableProjectionSelector(String tableName) { + public SearchIndexerKnowledgeStoreTableProjectionSelector(String generatedKeyName, String tableName) { + this.generatedKeyName = generatedKeyName; this.tableName = tableName; } + /** + * Get the generatedKeyName property: Name of generated key to store projection under. + * + * @return the generatedKeyName value. + */ + @Generated + public String getGeneratedKeyName() { + return this.generatedKeyName; + } + /** * Get the tableName property: Name of the Azure table to store projected data in. - * + * * @return the tableName value. */ @Generated @@ -61,8 +77,8 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setReferenceKeyName(St */ @Generated @Override - public SearchIndexerKnowledgeStoreTableProjectionSelector setGeneratedKeyName(String generatedKeyName) { - super.setGeneratedKeyName(generatedKeyName); + public SearchIndexerKnowledgeStoreTableProjectionSelector setSource(String source) { + super.setSource(source); return this; } @@ -71,18 +87,17 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setGeneratedKeyName(St */ @Generated @Override - public SearchIndexerKnowledgeStoreTableProjectionSelector setSource(String source) { - super.setSource(source); + public SearchIndexerKnowledgeStoreTableProjectionSelector setSourceContext(String sourceContext) { + super.setSourceContext(sourceContext); return this; } /** * {@inheritDoc} */ - @Generated @Override - public SearchIndexerKnowledgeStoreTableProjectionSelector setSourceContext(String sourceContext) { - super.setSourceContext(sourceContext); + public SearchIndexerKnowledgeStoreTableProjectionSelector setInputs(InputFieldMappingEntry... inputs) { + super.setInputs(inputs); return this; } @@ -104,17 +119,17 @@ public SearchIndexerKnowledgeStoreTableProjectionSelector setInputs(List writer.writeJson(element)); + jsonWriter.writeStringField("generatedKeyName", this.generatedKeyName); jsonWriter.writeStringField("tableName", this.tableName); return jsonWriter.writeEndObject(); } /** * Reads an instance of SearchIndexerKnowledgeStoreTableProjectionSelector from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerKnowledgeStoreTableProjectionSelector if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -126,45 +141,37 @@ public static SearchIndexerKnowledgeStoreTableProjectionSelector fromJson(JsonRe throws IOException { return jsonReader.readObject(reader -> { String referenceKeyName = null; - String generatedKeyName = null; String source = null; String sourceContext = null; List inputs = null; - boolean tableNameFound = false; + String generatedKeyName = null; String tableName = 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 ("generatedKeyName".equals(fieldName)) { + generatedKeyName = reader.getString(); } 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); - - return deserializedSearchIndexerKnowledgeStoreTableProjectionSelector; - } - throw new IllegalStateException("Missing required property: tableName"); + SearchIndexerKnowledgeStoreTableProjectionSelector deserializedSearchIndexerKnowledgeStoreTableProjectionSelector + = new SearchIndexerKnowledgeStoreTableProjectionSelector(generatedKeyName, tableName); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setReferenceKeyName(referenceKeyName); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setSource(source); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setSourceContext(sourceContext); + deserializedSearchIndexerKnowledgeStoreTableProjectionSelector.setInputs(inputs); + 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/indexes/models/SearchIndexerLimits.java index d6364f372835..1c2673a9d9ab 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/indexes/models/SearchIndexerLimits.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -16,10 +13,11 @@ 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. */ @@ -42,12 +40,12 @@ public final class SearchIndexerLimits implements JsonSerializable Duration.parse(nonNullReader.getString())); @@ -115,7 +112,6 @@ public static SearchIndexerLimits fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - return deserializedSearchIndexerLimits; }); } 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/indexes/models/SearchIndexerSkill.java index 15a8b762514e..e8614743f854 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/indexes/models/SearchIndexerSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,12 +9,7 @@ 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,8 +17,9 @@ */ @Fluent public class SearchIndexerSkill implements JsonSerializable { + /* - * A URI fragment specifying the type of skill. + * The discriminator for derived types. */ @Generated private String odataType = "SearchIndexerSkill"; @@ -66,7 +59,7 @@ public class SearchIndexerSkill implements JsonSerializable /** * Creates an instance of SearchIndexerSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -77,8 +70,8 @@ public SearchIndexerSkill(List inputs, List getInputs() { /** * 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 @@ -200,7 +193,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerSkill if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -212,7 +205,8 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -244,6 +238,8 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept 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)) { @@ -255,23 +251,17 @@ public static SearchIndexerSkill fromJson(JsonReader jsonReader) throws IOExcept } else if ("#Microsoft.Skills.Util.DocumentIntelligenceLayoutSkill".equals(discriminatorValue)) { return DocumentIntelligenceLayoutSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Custom.WebApiSkill".equals(discriminatorValue)) { - return WebApiSkill.fromJsonKnownDiscriminator(readerToUse.reset()); - } else if ("#Microsoft.Skills.Custom.ChatCompletionSkill".equals(discriminatorValue)) { - return ChatCompletionSkill.fromJson(readerToUse.reset()); - } else if ("#Microsoft.Skills.Util.ContentUnderstandingSkill".equals(discriminatorValue)) { - return ContentUnderstandingSkill.fromJson(readerToUse.reset()); + return WebApiSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Custom.AmlSkill".equals(discriminatorValue)) { return AzureMachineLearningSkill.fromJson(readerToUse.reset()); } else if ("#Microsoft.Skills.Text.AzureOpenAIEmbeddingSkill".equals(discriminatorValue)) { 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 if ("#Microsoft.Skills.Util.ContentUnderstandingSkill".equals(discriminatorValue)) { + return ContentUnderstandingSkill.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Skills.Custom.ChatCompletionSkill".equals(discriminatorValue)) { + return ChatCompletionSkill.fromJson(readerToUse.reset()); } else { return fromJsonKnownDiscriminator(readerToUse.reset()); } @@ -282,9 +272,7 @@ 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; @@ -293,13 +281,10 @@ static SearchIndexerSkill fromJsonKnownDiscriminator(JsonReader jsonReader) thro 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 ("@odata.type".equals(fieldName)) { odataType = reader.getString(); } else if ("name".equals(fieldName)) { @@ -312,25 +297,12 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SearchIndexerSkill deserializedSearchIndexerSkill = new SearchIndexerSkill(inputs, outputs); + deserializedSearchIndexerSkill.odataType = odataType; + deserializedSearchIndexerSkill.name = name; + deserializedSearchIndexerSkill.description = description; + deserializedSearchIndexerSkill.context = context; + 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/indexes/models/SearchIndexerSkillset.java index 3e03e1063334..f26a823682bd 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/indexes/models/SearchIndexerSkillset.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -37,7 +35,7 @@ public final class SearchIndexerSkillset implements JsonSerializable skills; + private final List skills; /* * Details about the Azure AI service to be used when running skills. @@ -79,10 +77,23 @@ public final class SearchIndexerSkillset implements JsonSerializable skills) { this.name = name; + this.skills = skills; } /** @@ -127,18 +138,6 @@ 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. - */ - @Generated - 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. * @@ -271,8 +270,8 @@ public SearchIndexerSkillset setEncryptionKey(SearchResourceEncryptionKey encryp 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); @@ -293,10 +292,9 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -307,11 +305,10 @@ public static SearchIndexerSkillset fromJson(JsonReader jsonReader) throws IOExc 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)) { @@ -326,40 +323,14 @@ 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; + return deserializedSearchIndexerSkillset; }); } - - /** - * 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; - } } 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/indexes/models/SearchIndexerStatus.java index 23669715e983..86a9fb7af2f8 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/indexes/models/SearchIndexerStatus.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -13,7 +10,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -21,6 +17,7 @@ */ @Immutable public final class SearchIndexerStatus implements JsonSerializable { + /* * The name of the indexer. */ @@ -31,10 +28,10 @@ public final class SearchIndexerStatus implements JsonSerializable executionHistory; + private List executionHistory; /* * The execution limits for the indexer. */ @Generated - private final SearchIndexerLimits limits; + private SearchIndexerLimits limits; /* * All of the state that defines and dictates the indexer's current execution. @@ -65,22 +62,14 @@ public final class SearchIndexerStatus implements JsonSerializable executionHistory, - SearchIndexerLimits limits) { - this.status = status; - this.executionHistory = executionHistory; - this.limits = limits; + private SearchIndexerStatus() { } /** * Get the name property: The name of the indexer. - * + * * @return the name value. */ @Generated @@ -90,7 +79,7 @@ public String getName() { /** * Get the status property: Overall indexer status. - * + * * @return the status value. */ @Generated @@ -99,9 +88,9 @@ public IndexerStatus getStatus() { } /** - * Get the runtime property: Snapshot of the indexer’s cumulative runtime consumption for the service over the + * Get the runtime property: Snapshot of the indexer's cumulative runtime consumption for the service over the * current UTC period. - * + * * @return the runtime value. */ @Generated @@ -111,7 +100,7 @@ public IndexerRuntime getRuntime() { /** * Get the lastResult property: The result of the most recent or an in-progress indexer execution. - * + * * @return the lastResult value. */ @Generated @@ -122,7 +111,7 @@ public IndexerExecutionResult getLastResult() { /** * Get the executionHistory property: History of the recent indexer executions, sorted in reverse chronological * order. - * + * * @return the executionHistory value. */ @Generated @@ -132,7 +121,7 @@ public List getExecutionHistory() { /** * Get the limits property: The execution limits for the indexer. - * + * * @return the limits value. */ @Generated @@ -142,7 +131,7 @@ public SearchIndexerLimits getLimits() { /** * Get the currentState property: All of the state that defines and dictates the indexer's current execution. - * + * * @return the currentState value. */ @Generated @@ -162,7 +151,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexerStatus from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexerStatus if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -172,64 +161,31 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; - String name = null; - IndexerRuntime runtime = null; - IndexerExecutionResult lastResult = null; - IndexerCurrentState currentState = null; + SearchIndexerStatus deserializedSearchIndexerStatus = new SearchIndexerStatus(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - - if ("status".equals(fieldName)) { - status = IndexerStatus.fromString(reader.getString()); - statusFound = true; + if ("name".equals(fieldName)) { + deserializedSearchIndexerStatus.name = reader.getString(); + } else if ("status".equals(fieldName)) { + deserializedSearchIndexerStatus.status = IndexerStatus.fromString(reader.getString()); + } else if ("runtime".equals(fieldName)) { + deserializedSearchIndexerStatus.runtime = IndexerRuntime.fromJson(reader); } else if ("executionHistory".equals(fieldName)) { - executionHistory = reader.readArray(reader1 -> IndexerExecutionResult.fromJson(reader1)); - executionHistoryFound = true; + List executionHistory + = reader.readArray(reader1 -> IndexerExecutionResult.fromJson(reader1)); + deserializedSearchIndexerStatus.executionHistory = executionHistory; } else if ("limits".equals(fieldName)) { - limits = SearchIndexerLimits.fromJson(reader); - limitsFound = true; - } else if ("name".equals(fieldName)) { - name = reader.getString(); - } else if ("runtime".equals(fieldName)) { - runtime = IndexerRuntime.fromJson(reader); + deserializedSearchIndexerStatus.limits = SearchIndexerLimits.fromJson(reader); } else if ("lastResult".equals(fieldName)) { - lastResult = IndexerExecutionResult.fromJson(reader); + deserializedSearchIndexerStatus.lastResult = IndexerExecutionResult.fromJson(reader); } else if ("currentState".equals(fieldName)) { - currentState = IndexerCurrentState.fromJson(reader); + deserializedSearchIndexerStatus.currentState = IndexerCurrentState.fromJson(reader); } else { reader.skipChildren(); } } - if (statusFound && executionHistoryFound && limitsFound) { - SearchIndexerStatus deserializedSearchIndexerStatus - = new SearchIndexerStatus(status, executionHistory, limits); - deserializedSearchIndexerStatus.name = name; - deserializedSearchIndexerStatus.runtime = runtime; - deserializedSearchIndexerStatus.lastResult = lastResult; - deserializedSearchIndexerStatus.currentState = currentState; - - 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/indexes/models/SearchIndexerWarning.java index 9fe6bbde02d5..c9b0e72c3cbc 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/indexes/models/SearchIndexerWarning.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,6 +16,7 @@ */ @Immutable public final class SearchIndexerWarning implements JsonSerializable { + /* * The key of the item which generated a warning. */ @@ -29,7 +27,7 @@ public final class SearchIndexerWarning implements JsonSerializable { - boolean messageFound = false; - String message = null; - String key = null; - String name = null; - String details = null; - String documentationLink = null; + SearchIndexerWarning deserializedSearchIndexerWarning = new SearchIndexerWarning(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("message".equals(fieldName)) { - message = reader.getString(); - messageFound = true; + deserializedSearchIndexerWarning.message = reader.getString(); } else if ("key".equals(fieldName)) { - key = reader.getString(); + deserializedSearchIndexerWarning.key = reader.getString(); } else if ("name".equals(fieldName)) { - name = reader.getString(); + deserializedSearchIndexerWarning.name = reader.getString(); } else if ("details".equals(fieldName)) { - details = reader.getString(); + deserializedSearchIndexerWarning.details = reader.getString(); } else if ("documentationLink".equals(fieldName)) { - documentationLink = reader.getString(); + deserializedSearchIndexerWarning.documentationLink = reader.getString(); } else { 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"); + return deserializedSearchIndexerWarning; }); } } 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 index 9c1728d11a1c..d321a26c5b25 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,10 +9,7 @@ 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 @@ -40,7 +35,7 @@ public final class SearchResourceEncryptionKey implements JsonSerializable { - boolean keyNameFound = false; String keyName = null; - boolean vaultUrlFound = false; - String vaultUrl = null; + String vaultUri = null; String keyVersion = null; AzureActiveDirectoryApplicationCredentials accessCredentials = null; SearchIndexerDataIdentity identity = null; @@ -179,10 +197,8 @@ public static SearchResourceEncryptionKey fromJson(JsonReader jsonReader) throws reader.nextToken(); if ("keyVaultKeyName".equals(fieldName)) { keyName = reader.getString(); - keyNameFound = true; } else if ("keyVaultUri".equals(fieldName)) { - vaultUrl = reader.getString(); - vaultUrlFound = true; + vaultUri = reader.getString(); } else if ("keyVaultKeyVersion".equals(fieldName)) { keyVersion = reader.getString(); } else if ("accessCredentials".equals(fieldName)) { @@ -193,73 +209,12 @@ public static SearchResourceEncryptionKey fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - if (keyNameFound && vaultUrlFound) { - SearchResourceEncryptionKey deserializedSearchResourceEncryptionKey - = new SearchResourceEncryptionKey(keyName, vaultUrl); - deserializedSearchResourceEncryptionKey.keyVersion = keyVersion; - deserializedSearchResourceEncryptionKey.accessCredentials = accessCredentials; - deserializedSearchResourceEncryptionKey.identity = identity; - return deserializedSearchResourceEncryptionKey; - } - List missingProperties = new ArrayList<>(); - if (!keyNameFound) { - missingProperties.add("keyVaultKeyName"); - } - if (!vaultUrlFound) { - missingProperties.add("keyVaultUri"); - } - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SearchResourceEncryptionKey deserializedSearchResourceEncryptionKey + = new SearchResourceEncryptionKey(keyName, vaultUri); + deserializedSearchResourceEncryptionKey.keyVersion = keyVersion; + deserializedSearchResourceEncryptionKey.accessCredentials = accessCredentials; + deserializedSearchResourceEncryptionKey.identity = identity; + return deserializedSearchResourceEncryptionKey; }); } - - /** - * 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/SearchServiceCounters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SearchServiceCounters.java index 7baf7b4e5eab..ddf88b36603f 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/indexes/models/SearchServiceCounters.java @@ -1,31 +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; -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. */ @Generated - private ResourceCounter aliasCounter; + private final ResourceCounter aliasCounter; /* * Total number of documents across all indexes in the service. @@ -67,39 +63,46 @@ public final class SearchServiceCounters implements JsonSerializable { - 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)) { @@ -303,42 +256,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/indexes/models/SearchServiceLimits.java index 8452ae8aab19..4322dd42ac97 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/indexes/models/SearchServiceLimits.java @@ -1,13 +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; -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; @@ -17,8 +14,9 @@ /** * Represents various service level limits. */ -@Fluent +@Immutable public final class SearchServiceLimits implements JsonSerializable { + /* * The maximum allowed fields per index. */ @@ -51,7 +49,7 @@ public final class SearchServiceLimits implements JsonSerializable { + /* * Service level resource counters. */ @@ -29,32 +24,35 @@ public final class SearchServiceStatistics implements JsonSerializable { - boolean countersFound = false; SearchServiceCounters counters = null; - boolean limitsFound = false; SearchServiceLimits limits = null; ServiceIndexersRuntime indexersRuntime = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("counters".equals(fieldName)) { counters = SearchServiceCounters.fromJson(reader); - countersFound = true; } else if ("limits".equals(fieldName)) { limits = SearchServiceLimits.fromJson(reader); - limitsFound = true; } else if ("indexersRuntime".equals(fieldName)) { indexersRuntime = ServiceIndexersRuntime.fromJson(reader); } else { reader.skipChildren(); } } - if (countersFound && limitsFound) { - SearchServiceStatistics deserializedSearchServiceStatistics - = new SearchServiceStatistics(counters, limits); - deserializedSearchServiceStatistics.indexersRuntime = indexersRuntime; - - return deserializedSearchServiceStatistics; - } - 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, indexersRuntime); }); } } 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/indexes/models/SearchSuggester.java index ff50d903ae42..ae83a75f9eac 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/indexes/models/SearchSuggester.java @@ -1,24 +1,22 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; -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.Arrays; 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 { /* @@ -31,7 +29,7 @@ public final class SearchSuggester implements JsonSerializable * A value indicating the capabilities of the suggester. */ @Generated - private String searchMode = "analyzingInfixMatching"; + private final String searchMode = "analyzingInfixMatching"; /* * The list of field names to which the suggester applies. Each field must be searchable. @@ -39,6 +37,17 @@ public final class SearchSuggester implements JsonSerializable @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. + */ + public SearchSuggester(String name, String... sourceFields) { + this.name = name; + this.sourceFields = (sourceFields == null) ? null : Arrays.asList(sourceFields); + } + /** * Creates an instance of SearchSuggester class. * @@ -47,9 +56,8 @@ public final class SearchSuggester implements JsonSerializable */ @Generated public SearchSuggester(String name, List sourceFields) { - this.searchMode = "analyzingInfixMatching"; - this.sourceFields = sourceFields; this.name = name; + this.sourceFields = sourceFields; } /** @@ -91,8 +99,8 @@ public List getSourceFields() { 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(); } @@ -108,40 +116,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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/indexes/models/SemanticConfiguration.java index c3176ca35b77..6997821842ac 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/indexes/models/SemanticConfiguration.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,14 +10,13 @@ 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. */ @Fluent public final class SemanticConfiguration implements JsonSerializable { + /* * The name of the semantic configuration. */ @@ -49,7 +45,7 @@ public final class SemanticConfiguration implements JsonSerializable { - boolean nameFound = false; String name = null; - boolean prioritizedFieldsFound = false; SemanticPrioritizedFields prioritizedFields = null; RankingOrder rankingOrder = 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 ("rankingOrder".equals(fieldName)) { rankingOrder = RankingOrder.fromString(reader.getString()); } else if ("flightingOptIn".equals(fieldName)) { @@ -177,24 +168,11 @@ public static SemanticConfiguration fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - if (nameFound && prioritizedFieldsFound) { - SemanticConfiguration deserializedSemanticConfiguration - = new SemanticConfiguration(name, prioritizedFields); - deserializedSemanticConfiguration.rankingOrder = rankingOrder; - deserializedSemanticConfiguration.flightingOptIn = flightingOptIn; - - return deserializedSemanticConfiguration; - } - List missingProperties = new ArrayList<>(); - if (!nameFound) { - missingProperties.add("name"); - } - if (!prioritizedFieldsFound) { - missingProperties.add("prioritizedFields"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + SemanticConfiguration deserializedSemanticConfiguration + = new SemanticConfiguration(name, prioritizedFields); + deserializedSemanticConfiguration.rankingOrder = rankingOrder; + deserializedSemanticConfiguration.flightingOptIn = flightingOptIn; + return deserializedSemanticConfiguration; }); } } 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/indexes/models/SemanticField.java index 93f1e6395d05..bdf395da44be 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/indexes/models/SemanticField.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,15 +16,16 @@ */ @Immutable public final class SemanticField implements JsonSerializable { + /* - * The fieldName property. + * File name */ @Generated private final String fieldName; /** * Creates an instance of SemanticField class. - * + * * @param fieldName the fieldName value to set. */ @Generated @@ -36,8 +34,8 @@ public SemanticField(String fieldName) { } /** - * Get the fieldName property: The fieldName property. - * + * Get the fieldName property: File name. + * * @return the fieldName value. */ @Generated @@ -58,7 +56,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SemanticField from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SemanticField if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -68,23 +66,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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(); reader.nextToken(); - 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/indexes/models/SemanticPrioritizedFields.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticPrioritizedFields.java index 80c5ce9dc8a2..c3bbf1b09f41 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/indexes/models/SemanticPrioritizedFields.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -88,6 +86,20 @@ 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. + * + * @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 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 @@ -116,6 +128,20 @@ 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 + * 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; + } + /** * 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 @@ -176,32 +202,4 @@ public static SemanticPrioritizedFields fromJson(JsonReader jsonReader) throws I 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/indexes/models/SemanticSearch.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SemanticSearch.java index d708f6f01e88..b27c63bc4915 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/indexes/models/SemanticSearch.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @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. @@ -43,7 +42,7 @@ 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. - * + * * @return the defaultConfigurationName value. */ @Generated @@ -54,7 +53,7 @@ public String getDefaultConfigurationName() { /** * 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. - * + * * @param defaultConfigurationName the defaultConfigurationName value to set. * @return the SemanticSearch object itself. */ @@ -66,7 +65,7 @@ public SemanticSearch setDefaultConfigurationName(String defaultConfigurationNam /** * Get the configurations property: The semantic configurations for the index. - * + * * @return the configurations value. */ @Generated @@ -76,7 +75,18 @@ public List getConfigurations() { /** * Set the configurations property: The semantic configurations for the index. - * + * + * @param configurations the configurations value to set. + * @return the SemanticSearch object itself. + */ + public SemanticSearch setConfigurations(SemanticConfiguration... configurations) { + this.configurations = (configurations == null) ? null : Arrays.asList(configurations); + return this; + } + + /** + * Set the configurations property: The semantic configurations for the index. + * * @param configurations the configurations value to set. * @return the SemanticSearch object itself. */ @@ -101,7 +111,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SemanticSearch from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SemanticSearch if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -114,7 +124,6 @@ public static SemanticSearch fromJson(JsonReader jsonReader) throws IOException while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("defaultConfiguration".equals(fieldName)) { deserializedSemanticSearch.defaultConfigurationName = reader.getString(); } else if ("configurations".equals(fieldName)) { @@ -125,7 +134,6 @@ public static SemanticSearch fromJson(JsonReader jsonReader) throws IOException reader.skipChildren(); } } - return deserializedSemanticSearch; }); } 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/SentimentSkillLanguage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillLanguage.java deleted file mode 100644 index 41d7950e68dd..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SentimentSkillLanguage.java +++ /dev/null @@ -1,137 +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.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * Deprecated. The language codes supported for input text by SentimentSkill. - */ -public final class SentimentSkillLanguage extends ExpandableStringEnum { - /** - * Danish. - */ - @Generated - public static final SentimentSkillLanguage DA = fromString("da"); - - /** - * Dutch. - */ - @Generated - public static final SentimentSkillLanguage NL = fromString("nl"); - - /** - * English. - */ - @Generated - public static final SentimentSkillLanguage EN = fromString("en"); - - /** - * Finnish. - */ - @Generated - public static final SentimentSkillLanguage FI = fromString("fi"); - - /** - * French. - */ - @Generated - public static final SentimentSkillLanguage FR = fromString("fr"); - - /** - * German. - */ - @Generated - public static final SentimentSkillLanguage DE = fromString("de"); - - /** - * Greek. - */ - @Generated - public static final SentimentSkillLanguage EL = fromString("el"); - - /** - * Italian. - */ - @Generated - public static final SentimentSkillLanguage IT = fromString("it"); - - /** - * Norwegian (Bokmaal). - */ - @Generated - public static final SentimentSkillLanguage NO = fromString("no"); - - /** - * Polish. - */ - @Generated - public static final SentimentSkillLanguage PL = fromString("pl"); - - /** - * Portuguese (Portugal). - */ - @Generated - public static final SentimentSkillLanguage PT_PT = fromString("pt-PT"); - - /** - * Russian. - */ - @Generated - public static final SentimentSkillLanguage RU = fromString("ru"); - - /** - * Spanish. - */ - @Generated - public static final SentimentSkillLanguage ES = fromString("es"); - - /** - * Swedish. - */ - @Generated - public static final SentimentSkillLanguage SV = fromString("sv"); - - /** - * Turkish. - */ - @Generated - public static final SentimentSkillLanguage TR = fromString("tr"); - - /** - * Creates a new instance of SentimentSkillLanguage value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public SentimentSkillLanguage() { - } - - /** - * Creates or finds a SentimentSkillLanguage from its string representation. - * - * @param name a name to look for. - * @return the corresponding SentimentSkillLanguage. - */ - @Generated - public static SentimentSkillLanguage fromString(String name) { - return fromString(name, SentimentSkillLanguage.class); - } - - /** - * Gets known SentimentSkillLanguage values. - * - * @return known SentimentSkillLanguage values. - */ - @Generated - public static Collection 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/indexes/models/SentimentSkillV3.java similarity index 81% 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/indexes/models/SentimentSkillV3.java index 45477e8af7ef..52455526fdc0 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/indexes/models/SentimentSkillV3.java @@ -1,21 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.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; /** @@ -25,8 +18,9 @@ */ @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"; @@ -53,7 +47,7 @@ public final class SentimentSkillV3 extends SearchIndexerSkill { /** * Creates an instance of SentimentSkillV3 class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -63,8 +57,8 @@ public SentimentSkillV3(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -222,13 +214,10 @@ public static SentimentSkillV3 fromJson(JsonReader jsonReader) throws IOExceptio 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)) { @@ -247,28 +236,15 @@ 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; - - 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)); + 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; }); } } 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/ServiceIndexersRuntime.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ServiceIndexersRuntime.java index 817a354b7423..06cb9b1ea6c7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ServiceIndexersRuntime.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/ServiceIndexersRuntime.java @@ -1,13 +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; -import com.azure.core.annotation.Fluent; 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; @@ -16,14 +13,13 @@ import java.io.IOException; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; /** - * Represents service level indexers runtime information. + * Represents service-level indexer runtime counters. */ -@Fluent +@Immutable public final class ServiceIndexersRuntime implements JsonSerializable { + /* * Cumulative runtime of all indexers in the service from the beginningTime to endingTime, in seconds. */ @@ -50,13 +46,13 @@ public final class ServiceIndexersRuntime implements JsonSerializable { - boolean usedSecondsFound = false; long usedSeconds = 0L; - boolean beginningTimeFound = false; OffsetDateTime beginningTime = null; - boolean endingTimeFound = false; OffsetDateTime endingTime = null; Long remainingSeconds = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("usedSeconds".equals(fieldName)) { usedSeconds = reader.getLong(); - usedSecondsFound = true; } else if ("beginningTime".equals(fieldName)) { beginningTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - beginningTimeFound = true; } else if ("endingTime".equals(fieldName)) { endingTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - endingTimeFound = true; } else if ("remainingSeconds".equals(fieldName)) { remainingSeconds = reader.getNullable(JsonReader::getLong); } else { reader.skipChildren(); } } - if (usedSecondsFound && beginningTimeFound && endingTimeFound) { - ServiceIndexersRuntime deserializedServiceIndexersRuntime - = new ServiceIndexersRuntime(usedSeconds, beginningTime, endingTime); - deserializedServiceIndexersRuntime.remainingSeconds = remainingSeconds; - - return deserializedServiceIndexersRuntime; - } - List missingProperties = new ArrayList<>(); - if (!usedSecondsFound) { - missingProperties.add("usedSeconds"); - } - if (!beginningTimeFound) { - missingProperties.add("beginningTime"); - } - if (!endingTimeFound) { - missingProperties.add("endingTime"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + ServiceIndexersRuntime deserializedServiceIndexersRuntime + = new ServiceIndexersRuntime(usedSeconds, beginningTime, endingTime); + deserializedServiceIndexersRuntime.remainingSeconds = remainingSeconds; + return deserializedServiceIndexersRuntime; }); } } 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/indexes/models/ShaperSkill.java index 4a93aeb15fdb..7ddce5d9b960 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/indexes/models/ShaperSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -21,15 +17,16 @@ */ @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"; /** * Creates an instance of ShaperSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -39,8 +36,8 @@ public ShaperSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -118,13 +113,10 @@ public static ShaperSkill 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)) { @@ -137,25 +129,12 @@ 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; - - 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)); + ShaperSkill deserializedShaperSkill = new ShaperSkill(inputs, outputs); + deserializedShaperSkill.setName(name); + deserializedShaperSkill.setDescription(description); + deserializedShaperSkill.setContext(context); + deserializedShaperSkill.odataType = odataType; + 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/indexes/models/ShingleTokenFilter.java index 2f31e0597732..bf3e00dbc530 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/indexes/models/ShingleTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,7 +17,7 @@ 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"; @@ -73,7 +71,7 @@ public ShingleTokenFilter(String 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. */ @@ -136,7 +134,7 @@ public ShingleTokenFilter setMinShingleSize(Integer minShingleSize) { * @return the outputUnigrams value. */ @Generated - public Boolean areOutputUnigrams() { + public Boolean isOutputUnigrams() { return this.outputUnigrams; } @@ -160,7 +158,7 @@ public ShingleTokenFilter setOutputUnigrams(Boolean outputUnigrams) { * @return the outputUnigramsIfNoShingles value. */ @Generated - public Boolean areOutputUnigramsIfNoShingles() { + public Boolean isOutputUnigramsIfNoShingles() { return this.outputUnigramsIfNoShingles; } @@ -255,7 +253,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -269,7 +266,6 @@ public static ShingleTokenFilter fromJson(JsonReader jsonReader) throws IOExcept 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)) { @@ -288,18 +284,15 @@ 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/indexes/models/SimilarityAlgorithm.java index 4b9e99eaf00d..96574dd450fe 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/indexes/models/SimilarityAlgorithm.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -21,8 +18,9 @@ */ @Immutable public class SimilarityAlgorithm implements JsonSerializable { + /* - * The @odata.type property. + * The discriminator for derived types. */ @Generated private String odataType = "SimilarityAlgorithm"; @@ -35,8 +33,8 @@ public SimilarityAlgorithm() { } /** - * Get the odataType property: The @odata.type property. - * + * Get the odataType property: The discriminator for derived types. + * * @return the odataType value. */ @Generated @@ -57,7 +55,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SimilarityAlgorithm from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SimilarityAlgorithm if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -68,7 +66,8 @@ public static SimilarityAlgorithm fromJson(JsonReader jsonReader) throws IOExcep return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -98,14 +97,12 @@ static SimilarityAlgorithm fromJsonKnownDiscriminator(JsonReader jsonReader) thr while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedSimilarityAlgorithm.odataType = reader.getString(); } else { reader.skipChildren(); } } - return deserializedSimilarityAlgorithm; }); } 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/indexes/models/SkillNames.java similarity index 82% 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/indexes/models/SkillNames.java index 97e89799261a..d17a0a019a0f 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/indexes/models/SkillNames.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.implementation.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -13,13 +10,15 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; 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. */ @@ -35,7 +34,7 @@ public SkillNames() { /** * Get the skillNames property: the names of skills to be reset. - * + * * @return the skillNames value. */ @Generated @@ -45,7 +44,18 @@ public List getSkillNames() { /** * Set the skillNames property: the names of skills to be reset. - * + * + * @param skillNames the skillNames value to set. + * @return the SkillNames object itself. + */ + public SkillNames setSkillNames(String... skillNames) { + this.skillNames = (skillNames == null) ? null : Arrays.asList(skillNames); + return this; + } + + /** + * Set the skillNames property: the names of skills to be reset. + * * @param skillNames the skillNames value to set. * @return the SkillNames object itself. */ @@ -68,7 +78,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SkillNames from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SkillNames if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. @@ -81,7 +91,6 @@ public static SkillNames fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("skillNames".equals(fieldName)) { List skillNames = reader.readArray(reader1 -> reader1.getString()); deserializedSkillNames.skillNames = skillNames; @@ -89,7 +98,6 @@ public static SkillNames fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedSkillNames; }); } 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/indexes/models/SnowballTokenFilter.java index 282900820a84..74e9349c8d48 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/indexes/models/SnowballTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,16 +9,15 @@ 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. */ @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"; @@ -34,7 +30,7 @@ public final class SnowballTokenFilter extends TokenFilter { /** * Creates an instance of SnowballTokenFilter class. - * + * * @param name the name value to set. * @param language the language value to set. */ @@ -45,8 +41,8 @@ public SnowballTokenFilter(String name, SnowballTokenFilterLanguage 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 @@ -57,7 +53,7 @@ public String getOdataType() { /** * Get the language property: The language to use. - * + * * @return the language value. */ @Generated @@ -80,7 +76,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SnowballTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SnowballTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -90,43 +86,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + SnowballTokenFilter deserializedSnowballTokenFilter = new SnowballTokenFilter(name, language); + deserializedSnowballTokenFilter.odataType = odataType; + return deserializedSnowballTokenFilter; }); } } 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 index f0f496cb4f3d..ee1dbfab19e9 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/SoftDeleteColumnDeletionDetectionPolicy.java index 967429e1c914..735833ff8e30 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/indexes/models/SoftDeleteColumnDeletionDetectionPolicy.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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"; @@ -45,8 +43,8 @@ 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 @@ -57,7 +55,7 @@ public String getOdataType() { /** * Get the softDeleteColumnName property: The name of the column to use for soft-deletion detection. - * + * * @return the softDeleteColumnName value. */ @Generated @@ -67,7 +65,7 @@ public String getSoftDeleteColumnName() { /** * Set the softDeleteColumnName property: The name of the column to use for soft-deletion detection. - * + * * @param softDeleteColumnName the softDeleteColumnName value to set. * @return the SoftDeleteColumnDeletionDetectionPolicy object itself. */ @@ -79,7 +77,7 @@ public SoftDeleteColumnDeletionDetectionPolicy setSoftDeleteColumnName(String so /** * Get the softDeleteMarkerValue property: The marker value that identifies an item as deleted. - * + * * @return the softDeleteMarkerValue value. */ @Generated @@ -89,7 +87,7 @@ public String getSoftDeleteMarkerValue() { /** * Set the softDeleteMarkerValue property: The marker value that identifies an item as deleted. - * + * * @param softDeleteMarkerValue the softDeleteMarkerValue value to set. * @return the SoftDeleteColumnDeletionDetectionPolicy object itself. */ @@ -114,7 +112,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SoftDeleteColumnDeletionDetectionPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SoftDeleteColumnDeletionDetectionPolicy if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -128,7 +126,6 @@ public static SoftDeleteColumnDeletionDetectionPolicy fromJson(JsonReader jsonRe while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedSoftDeleteColumnDeletionDetectionPolicy.odataType = reader.getString(); } else if ("softDeleteColumnName".equals(fieldName)) { @@ -139,7 +136,6 @@ public static SoftDeleteColumnDeletionDetectionPolicy fromJson(JsonReader jsonRe reader.skipChildren(); } } - return 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/indexes/models/SplitSkill.java index 2207bb0ade64..4ec733bbb428 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/indexes/models/SplitSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,8 +16,9 @@ */ @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"; @@ -77,7 +74,7 @@ public final class SplitSkill extends SearchIndexerSkill { /** * Creates an instance of SplitSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. */ @@ -87,8 +84,8 @@ public SplitSkill(List inputs, List { - boolean inputsFound = false; List inputs = null; - boolean outputsFound = false; List outputs = null; String name = null; String description = null; @@ -349,13 +344,10 @@ public static SplitSkill 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)) { @@ -382,32 +374,19 @@ 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/indexes/models/SplitSkillEncoderModelName.java index 2ad957867687..c850522af988 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/indexes/models/SplitSkillEncoderModelName.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,25 +17,25 @@ public final class SplitSkillEncoderModelName extends ExpandableStringEnum { + /** * Amharic. */ @@ -214,7 +212,7 @@ public final class SplitSkillLanguage extends ExpandableStringEnum { + /** * The length will be measured by character. */ @@ -28,7 +26,7 @@ public final class SplitSkillUnit extends ExpandableStringEnum { /** * Creates a new instance of SplitSkillUnit value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -38,7 +36,7 @@ public SplitSkillUnit() { /** * Creates or finds a SplitSkillUnit from its string representation. - * + * * @param name a name to look for. * @return the corresponding SplitSkillUnit. */ @@ -49,7 +47,7 @@ public static SplitSkillUnit fromString(String name) { /** * Gets known SplitSkillUnit values. - * + * * @return known SplitSkillUnit values. */ @Generated 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/indexes/models/SqlIntegratedChangeTrackingPolicy.java index d459ba2556f9..28a5b5b76662 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/indexes/models/SqlIntegratedChangeTrackingPolicy.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @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"; @@ -33,8 +31,8 @@ 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 @@ -56,7 +54,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SqlIntegratedChangeTrackingPolicy from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SqlIntegratedChangeTrackingPolicy if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -70,14 +68,12 @@ public static SqlIntegratedChangeTrackingPolicy fromJson(JsonReader jsonReader) while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("@odata.type".equals(fieldName)) { deserializedSqlIntegratedChangeTrackingPolicy.odataType = reader.getString(); } else { reader.skipChildren(); } } - return 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/indexes/models/StemmerOverrideTokenFilter.java index 39d270287ddf..c272029c9976 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/indexes/models/StemmerOverrideTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,18 +9,20 @@ 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; /** * 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. + * any stemming filters. This token filter is implemented using Apache Lucene. See + * http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.html. */ @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"; @@ -36,7 +35,18 @@ public final class StemmerOverrideTokenFilter extends TokenFilter { /** * Creates an instance of StemmerOverrideTokenFilter class. - * + * + * @param name the name value to set. + * @param rules the rules value to set. + */ + public StemmerOverrideTokenFilter(String name, String... rules) { + super(name); + this.rules = (rules == null) ? null : Arrays.asList(rules); + } + + /** + * Creates an instance of StemmerOverrideTokenFilter class. + * * @param name the name value to set. * @param rules the rules value to set. */ @@ -47,8 +57,8 @@ public StemmerOverrideTokenFilter(String name, List 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 @@ -60,7 +70,7 @@ public String getOdataType() { /** * Get the rules property: A list of stemming rules in the following format: "word => stem", for example: "ran * => run". - * + * * @return the rules value. */ @Generated @@ -83,7 +93,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of StemmerOverrideTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of StemmerOverrideTokenFilter if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -93,44 +103,26 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + StemmerOverrideTokenFilter deserializedStemmerOverrideTokenFilter + = new StemmerOverrideTokenFilter(name, rules); + deserializedStemmerOverrideTokenFilter.odataType = odataType; + 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/indexes/models/StemmerTokenFilter.java index f93c1d86257c..e8378e237ca7 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/indexes/models/StemmerTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,16 +9,16 @@ 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. See + * https://learn.microsoft.com/rest/api/searchservice/Custom-analyzers-in-Azure-Search#TokenFilters. */ @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"; @@ -34,7 +31,7 @@ public final class StemmerTokenFilter extends TokenFilter { /** * Creates an instance of StemmerTokenFilter class. - * + * * @param name the name value to set. * @param language the language value to set. */ @@ -45,8 +42,8 @@ public StemmerTokenFilter(String name, StemmerTokenFilterLanguage 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 @@ -57,7 +54,7 @@ public String getOdataType() { /** * Get the language property: The language to use. - * + * * @return the language value. */ @Generated @@ -80,7 +77,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of StemmerTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of StemmerTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -90,43 +87,25 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + StemmerTokenFilter deserializedStemmerTokenFilter = new StemmerTokenFilter(name, language); + deserializedStemmerTokenFilter.odataType = odataType; + return deserializedStemmerTokenFilter; }); } } 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 index b87d611325a5..e73802f5a227 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -196,17 +194,17 @@ public enum StemmerTokenFilterLanguage { LATVIAN("latvian"), /** - * Selects the Lucene stemming tokenizer for Norwegian (Bokmål). + * Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l). */ NORWEGIAN("norwegian"), /** - * Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does light stemming. + * Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l) that does light stemming. */ LIGHT_NORWEGIAN("lightNorwegian"), /** - * Selects the Lucene stemming tokenizer for Norwegian (Bokmål) that does minimal stemming. + * Selects the Lucene stemming tokenizer for Norwegian (BokmÃ¥l) that does minimal stemming. */ MINIMAL_NORWEGIAN("minimalNorwegian"), 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/indexes/models/StopAnalyzer.java index ded988e52b7a..36d777e7d9ab 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/indexes/models/StopAnalyzer.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,7 +20,7 @@ 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"; @@ -44,7 +42,7 @@ public StopAnalyzer(String 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. */ @@ -64,6 +62,17 @@ 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. + */ + public StopAnalyzer setStopwords(String... stopwords) { + this.stopwords = (stopwords == null) ? null : Arrays.asList(stopwords); + return this; + } + /** * Set the stopwords property: A list of stopwords. * @@ -101,7 +110,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -110,7 +118,6 @@ public static StopAnalyzer fromJson(JsonReader jsonReader) throws IOException { 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)) { @@ -119,24 +126,10 @@ 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; + return deserializedStopAnalyzer; }); } - - /** - * 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; - } } 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 index 7ff27e11c54d..be0fec0d06be 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/StopwordsTokenFilter.java index 4aab8e4b5193..3b37c8df1fb7 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/indexes/models/StopwordsTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -15,13 +13,14 @@ 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. See + * http://lucene.apache.org/core/4_10_3/analyzers-common/org/apache/lucene/analysis/core/StopFilter.html. */ @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"; @@ -44,13 +43,13 @@ public final class StopwordsTokenFilter extends TokenFilter { * false. */ @Generated - private Boolean caseIgnored; + private Boolean ignoreCase; /* * A value indicating whether to ignore the last search term if it's a stop word. Default is true. */ @Generated - private Boolean trailingStopWordsRemoved; + private Boolean removeTrailingStopWords; /** * Creates an instance of StopwordsTokenFilter class. @@ -63,7 +62,7 @@ public StopwordsTokenFilter(String 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. */ @@ -84,6 +83,18 @@ 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. + * + * @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; + } + /** * Set the stopwords property: The list of stopwords. This property and the stopwords list property cannot both be * set. @@ -122,50 +133,50 @@ public StopwordsTokenFilter setStopwordsList(StopwordsList stopwordsList) { } /** - * Get the caseIgnored property: A value indicating whether to ignore case. If true, all words are converted to - * lower case first. Default is false. + * 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. */ @Generated - public Boolean isCaseIgnored() { - return this.caseIgnored; + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether to ignore case. If true, all words are converted to - * lower case first. Default is false. + * 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. */ @Generated - public StopwordsTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + 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 + * 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 trailingStopWordsRemoved value. + * @return the removeTrailingStopWords value. */ @Generated - public Boolean areTrailingStopWordsRemoved() { - return this.trailingStopWordsRemoved; + public Boolean isRemoveTrailingStopWords() { + return this.removeTrailingStopWords; } /** - * Set the trailingStopWordsRemoved property: A value indicating whether to ignore the last search term if it's a + * Set the removeTrailingStopWords 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. + * @param removeTrailingStopWords the removeTrailingStopWords value to set. * @return the StopwordsTokenFilter object itself. */ @Generated - public StopwordsTokenFilter setTrailingStopWordsRemoved(Boolean trailingStopWordsRemoved) { - this.trailingStopWordsRemoved = trailingStopWordsRemoved; + public StopwordsTokenFilter setRemoveTrailingStopWords(Boolean removeTrailingStopWords) { + this.removeTrailingStopWords = removeTrailingStopWords; return this; } @@ -180,8 +191,8 @@ 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(); } @@ -197,19 +208,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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)) { @@ -217,35 +226,20 @@ 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/indexes/models/SynonymMap.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/SynonymMap.java index 4aab6de09517..8aaed89bb19e 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/indexes/models/SynonymMap.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,6 +10,10 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; /** * Represents a synonym map definition. @@ -23,19 +25,19 @@ public final class SynonymMap implements JsonSerializable { * The name of the synonym map. */ @Generated - private String name; + private final String name; /* * The format of the synonym map. Only the 'solr' format is currently supported. */ @Generated - private String format = "solr"; + private final String format = "solr"; /* * A series of synonym rules in the specified synonym map format. The rules must be separated by newlines. */ @Generated - private String synonyms; + private final List synonyms; /* * A description of an encryption key that you create in Azure Key Vault. This key is used to provide an additional @@ -56,9 +58,25 @@ public final class SynonymMap implements JsonSerializable { /** * Creates an instance of SynonymMap class. + * + * @param name the name value to set. + * @param synonyms the synonyms value to set. + */ + public SynonymMap(String name, String... synonyms) { + this.name = name; + this.synonyms = (synonyms == null) ? null : Arrays.asList(synonyms); + } + + /** + * Creates an instance of SynonymMap class. + * + * @param name the name value to set. + * @param synonyms the synonyms value to set. */ @Generated - public SynonymMap() { + public SynonymMap(String name, List synonyms) { + this.name = name; + this.synonyms = synonyms; } /** @@ -72,27 +90,24 @@ public String getName() { } /** - * Get the synonyms property: A series of synonym rules in the specified synonym map format. The rules must be - * separated by newlines. + * Get the format property: The format of the synonym map. Only the 'solr' format is currently supported. * - * @return the synonyms value. + * @return the format value. */ @Generated - public String getSynonyms() { - return this.synonyms; + 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 + * Get 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. + * @return the synonyms value. */ @Generated - public SynonymMap setSynonyms(String synonyms) { - this.synonyms = synonyms; - return this; + public List getSynonyms() { + return this.synonyms; } /** @@ -160,7 +175,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("name", this.name); jsonWriter.writeStringField("format", this.format); - jsonWriter.writeStringField("synonyms", this.synonyms); + if (this.synonyms != null) { + jsonWriter.writeStringField("synonyms", + this.synonyms.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining("\n"))); + } jsonWriter.writeJsonField("encryptionKey", this.encryptionKey); jsonWriter.writeStringField("@odata.etag", this.eTag); return jsonWriter.writeEndObject(); @@ -172,65 +192,40 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { * @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; + List 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.getNullable(nonNullReader -> { + String synonymsEncodedAsString = nonNullReader.getString(); + return synonymsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(synonymsEncodedAsString.split("\n", -1))); + }); } 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/indexes/models/SynonymTokenFilter.java index 5679a96712fe..3f4a31946273 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/indexes/models/SynonymTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -11,7 +9,7 @@ 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; /** @@ -21,7 +19,7 @@ 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"; @@ -39,7 +37,7 @@ public final class SynonymTokenFilter extends TokenFilter { * A value indicating whether to case-fold input for matching. Default is false. */ @Generated - private Boolean caseIgnored; + private Boolean ignoreCase; /* * A value indicating whether all words in the list of synonyms (if => notation is not used) will map to one @@ -52,6 +50,17 @@ public final class SynonymTokenFilter extends TokenFilter { @Generated private Boolean expand; + /** + * Creates an instance of SynonymTokenFilter class. + * + * @param name the name value to set. + * @param synonyms the synonyms value to set. + */ + public SynonymTokenFilter(String name, String... synonyms) { + super(name); + this.synonyms = (synonyms == null) ? null : Arrays.asList(synonyms); + } + /** * Creates an instance of SynonymTokenFilter class. * @@ -65,7 +74,7 @@ public SynonymTokenFilter(String name, List 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. */ @@ -89,24 +98,24 @@ public List getSynonyms() { } /** - * Get the caseIgnored property: A value indicating whether to case-fold input for matching. Default is false. + * Get the ignoreCase property: A value indicating whether to case-fold input for matching. Default is false. * - * @return the caseIgnored value. + * @return the ignoreCase value. */ @Generated - public Boolean isCaseIgnored() { - return this.caseIgnored; + public Boolean isIgnoreCase() { + return this.ignoreCase; } /** - * Set the caseIgnored property: A value indicating whether to case-fold input for matching. Default is false. + * Set the ignoreCase property: A value indicating whether to case-fold input for matching. Default is false. * - * @param caseIgnored the caseIgnored value to set. + * @param ignoreCase the ignoreCase value to set. * @return the SynonymTokenFilter object itself. */ @Generated - public SynonymTokenFilter setCaseIgnored(Boolean caseIgnored) { - this.caseIgnored = caseIgnored; + public SynonymTokenFilter setIgnoreCase(Boolean ignoreCase) { + this.ignoreCase = ignoreCase; return this; } @@ -121,7 +130,7 @@ public SynonymTokenFilter setCaseIgnored(Boolean caseIgnored) { * @return the expand value. */ @Generated - public Boolean getExpand() { + public Boolean isExpand() { return this.expand; } @@ -152,7 +161,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { 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(); } @@ -169,48 +178,33 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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/indexes/models/TagScoringFunction.java index 2f841f8ef1e9..a7b2a3e0aaa4 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/indexes/models/TagScoringFunction.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,17 +9,15 @@ 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. */ @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"; @@ -35,7 +30,7 @@ public final class TagScoringFunction extends ScoringFunction { /** * Creates an instance of TagScoringFunction class. - * + * * @param fieldName the fieldName value to set. * @param boost the boost value to set. * @param parameters the parameters value to set. @@ -47,9 +42,8 @@ public TagScoringFunction(String fieldName, double boost, TagScoringParameters p } /** - * 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 @@ -60,7 +54,7 @@ public String getType() { /** * Get the parameters property: Parameter values for the tag scoring function. - * + * * @return the parameters value. */ @Generated @@ -95,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of TagScoringFunction from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of TagScoringFunction if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -105,56 +99,32 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { String jsonFieldName = reader.getFieldName(); reader.nextToken(); - 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; - - 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)); + TagScoringFunction deserializedTagScoringFunction = new TagScoringFunction(fieldName, boost, parameters); + deserializedTagScoringFunction.setInterpolation(interpolation); + deserializedTagScoringFunction.type = type; + 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/indexes/models/TagScoringParameters.java index 3ede051958f3..2d57443e215e 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/indexes/models/TagScoringParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,6 +16,7 @@ */ @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. @@ -28,7 +26,7 @@ public final class TagScoringParameters implements JsonSerializable { - boolean tagsParameterFound = false; String tagsParameter = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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/indexes/models/TextSplitMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TextSplitMode.java index 125c58d9a249..89c1e54a9c68 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/indexes/models/TextSplitMode.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * A value indicating which split mode to perform. */ public final class TextSplitMode extends ExpandableStringEnum { + /** * Split the text into individual pages. */ @@ -28,7 +26,7 @@ public final class TextSplitMode extends ExpandableStringEnum { /** * Creates a new instance of TextSplitMode value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -38,7 +36,7 @@ public TextSplitMode() { /** * Creates or finds a TextSplitMode from its string representation. - * + * * @param name a name to look for. * @return the corresponding TextSplitMode. */ @@ -49,7 +47,7 @@ public static TextSplitMode fromString(String name) { /** * Gets known TextSplitMode values. - * + * * @return known TextSplitMode values. */ @Generated 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/indexes/models/TextTranslationSkill.java index 2b32ecf270be..bde72547cc57 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/indexes/models/TextTranslationSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -12,7 +9,6 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; import java.util.List; /** @@ -20,8 +16,9 @@ */ @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"; @@ -48,7 +45,7 @@ public final class TextTranslationSkill extends SearchIndexerSkill { /** * Creates an instance of TextTranslationSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. * @param defaultToLanguageCode the defaultToLanguageCode value to set. @@ -61,8 +58,8 @@ 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; @@ -210,13 +204,10 @@ public static TextTranslationSkill fromJson(JsonReader jsonReader) throws IOExce 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)) { @@ -225,7 +216,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)) { @@ -236,31 +226,15 @@ 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/indexes/models/TextTranslationSkillLanguage.java index ad994faebbbd..dda466d2b9e2 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/indexes/models/TextTranslationSkillLanguage.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The language codes supported for input text by TextTranslationSkill. */ public final class TextTranslationSkillLanguage extends ExpandableStringEnum { + /** * Afrikaans. */ @@ -448,7 +446,7 @@ public final class TextTranslationSkillLanguage extends ExpandableStringEnum { + /* * The dictionary of per-field weights to boost document scoring. The keys are field names and the values are the * weights for each field. @@ -29,7 +27,7 @@ public final class TextWeights implements JsonSerializable { /** * Creates an instance of TextWeights class. - * + * * @param weights the weights value to set. */ @Generated @@ -40,7 +38,7 @@ public TextWeights(Map 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. - * + * * @return the weights value. */ @Generated @@ -61,7 +59,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of TextWeights from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of TextWeights if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -71,23 +69,17 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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(); reader.nextToken(); - 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/indexes/models/TokenCharacterKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/TokenCharacterKind.java index 1ab00644e176..36bf518fffa7 100644 --- 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 @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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/indexes/models/TokenFilter.java index bb1e2ebbc4a2..812ede6c629a 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/indexes/models/TokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -12,10 +9,6 @@ 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,8 +16,9 @@ */ @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"; @@ -38,7 +32,7 @@ public class TokenFilter implements JsonSerializable { /** * Creates an instance of TokenFilter class. - * + * * @param name the name value to set. */ @Generated @@ -47,8 +41,8 @@ public TokenFilter(String 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 @@ -59,7 +53,7 @@ public String getOdataType() { /** * 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 @@ -81,7 +75,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of TokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of TokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -93,7 +87,8 @@ public static TokenFilter fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -113,6 +108,8 @@ public static TokenFilter fromJson(JsonReader jsonReader) throws IOException { return CommonGramTokenFilter.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.DictionaryDecompounderTokenFilter".equals(discriminatorValue)) { return DictionaryDecompounderTokenFilter.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Azure.Search.EdgeNGramTokenFilter".equals(discriminatorValue)) { + return EdgeNGramTokenFilter.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.EdgeNGramTokenFilterV2".equals(discriminatorValue)) { return EdgeNGramTokenFilterV2.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.ElisionTokenFilter".equals(discriminatorValue)) { @@ -125,6 +122,8 @@ public static TokenFilter fromJson(JsonReader jsonReader) throws IOException { return LengthTokenFilter.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.LimitTokenFilter".equals(discriminatorValue)) { return LimitTokenFilter.fromJson(readerToUse.reset()); + } else if ("#Microsoft.Azure.Search.NGramTokenFilter".equals(discriminatorValue)) { + return NGramTokenFilter.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.NGramTokenFilterV2".equals(discriminatorValue)) { return NGramTokenFilterV2.fromJson(readerToUse.reset()); } else if ("#Microsoft.Azure.Search.PatternCaptureTokenFilter".equals(discriminatorValue)) { @@ -151,10 +150,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()); } @@ -165,29 +160,22 @@ 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) { 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 { reader.skipChildren(); } } - if (nameFound) { - TokenFilter deserializedTokenFilter = new TokenFilter(name); - deserializedTokenFilter.odataType = odataType; - - return deserializedTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + TokenFilter deserializedTokenFilter = new TokenFilter(name); + deserializedTokenFilter.odataType = odataType; + 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/indexes/models/TokenFilterName.java index d4ad4eee76f0..8252fb1aa5d7 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/indexes/models/TokenFilterName.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * Defines the names of all token filters supported by the search engine. */ public final class TokenFilterName extends ExpandableStringEnum { + /** * 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. @@ -44,7 +42,7 @@ public final class TokenFilterName extends ExpandableStringEnum 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 + * 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. */ @@ -178,8 +176,8 @@ public final class TokenFilterName extends ExpandableStringEnum 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 @@ -256,7 +254,7 @@ public final class TokenFilterName extends ExpandableStringEnum /** * Creates a new instance of TokenFilterName value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -266,7 +264,7 @@ public TokenFilterName() { /** * Creates or finds a TokenFilterName from its string representation. - * + * * @param name a name to look for. * @return the corresponding TokenFilterName. */ @@ -277,7 +275,7 @@ public static TokenFilterName fromString(String name) { /** * Gets known TokenFilterName values. - * + * * @return known TokenFilterName values. */ @Generated 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/indexes/models/TruncateTokenFilter.java index 3a0e7e45ed7d..9a5ef3de5b18 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/indexes/models/TruncateTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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"; @@ -32,7 +30,7 @@ public final class TruncateTokenFilter extends TokenFilter { /** * Creates an instance of TruncateTokenFilter class. - * + * * @param name the name value to set. */ @Generated @@ -41,8 +39,8 @@ public TruncateTokenFilter(String 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 @@ -53,7 +51,7 @@ public String getOdataType() { /** * Get the length property: The length at which terms will be truncated. Default and maximum is 300. - * + * * @return the length value. */ @Generated @@ -63,7 +61,7 @@ public Integer getLength() { /** * Set the length property: The length at which terms will be truncated. Default and maximum is 300. - * + * * @param length the length value to set. * @return the TruncateTokenFilter object itself. */ @@ -88,7 +86,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of TruncateTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of TruncateTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -98,17 +96,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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 ("length".equals(fieldName)) { @@ -117,14 +112,10 @@ public static TruncateTokenFilter fromJson(JsonReader jsonReader) throws IOExcep reader.skipChildren(); } } - if (nameFound) { - TruncateTokenFilter deserializedTruncateTokenFilter = new TruncateTokenFilter(name); - deserializedTruncateTokenFilter.odataType = odataType; - deserializedTruncateTokenFilter.length = length; - - return deserializedTruncateTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + TruncateTokenFilter deserializedTruncateTokenFilter = new TruncateTokenFilter(name); + deserializedTruncateTokenFilter.odataType = odataType; + deserializedTruncateTokenFilter.length = length; + 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/indexes/models/UaxUrlEmailTokenizer.java index 23d246e36092..f067222abe27 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/indexes/models/UaxUrlEmailTokenizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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"; @@ -33,7 +31,7 @@ public final class UaxUrlEmailTokenizer extends LexicalTokenizer { /** * Creates an instance of UaxUrlEmailTokenizer class. - * + * * @param name the name value to set. */ @Generated @@ -42,8 +40,8 @@ public UaxUrlEmailTokenizer(String 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 @@ -55,7 +53,7 @@ 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 @@ -66,7 +64,7 @@ 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 UaxUrlEmailTokenizer object itself. */ @@ -91,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of UaxUrlEmailTokenizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of UaxUrlEmailTokenizer if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -101,17 +99,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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)) { @@ -120,14 +115,10 @@ public static UaxUrlEmailTokenizer fromJson(JsonReader jsonReader) throws IOExce reader.skipChildren(); } } - if (nameFound) { - UaxUrlEmailTokenizer deserializedUaxUrlEmailTokenizer = new UaxUrlEmailTokenizer(name); - deserializedUaxUrlEmailTokenizer.odataType = odataType; - deserializedUaxUrlEmailTokenizer.maxTokenLength = maxTokenLength; - - return deserializedUaxUrlEmailTokenizer; - } - throw new IllegalStateException("Missing required property: name"); + UaxUrlEmailTokenizer deserializedUaxUrlEmailTokenizer = new UaxUrlEmailTokenizer(name); + deserializedUaxUrlEmailTokenizer.odataType = odataType; + deserializedUaxUrlEmailTokenizer.maxTokenLength = maxTokenLength; + 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/indexes/models/UniqueTokenFilter.java index 9655f1e9020f..c06a679f8287 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/indexes/models/UniqueTokenFilter.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,8 +15,9 @@ */ @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"; @@ -32,7 +30,7 @@ public final class UniqueTokenFilter extends TokenFilter { /** * Creates an instance of UniqueTokenFilter class. - * + * * @param name the name value to set. */ @Generated @@ -41,8 +39,8 @@ public UniqueTokenFilter(String 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 @@ -54,7 +52,7 @@ public String getOdataType() { /** * Get the onlyOnSamePosition property: A value indicating whether to remove duplicates only at the same position. * Default is false. - * + * * @return the onlyOnSamePosition value. */ @Generated @@ -65,7 +63,7 @@ public Boolean isOnlyOnSamePosition() { /** * Set the onlyOnSamePosition property: A value indicating whether to remove duplicates only at the same position. * Default is false. - * + * * @param onlyOnSamePosition the onlyOnSamePosition value to set. * @return the UniqueTokenFilter object itself. */ @@ -90,7 +88,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of UniqueTokenFilter from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of UniqueTokenFilter if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -100,17 +98,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; 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 ("onlyOnSamePosition".equals(fieldName)) { @@ -119,14 +114,10 @@ public static UniqueTokenFilter fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - if (nameFound) { - UniqueTokenFilter deserializedUniqueTokenFilter = new UniqueTokenFilter(name); - deserializedUniqueTokenFilter.odataType = odataType; - deserializedUniqueTokenFilter.onlyOnSamePosition = onlyOnSamePosition; - - return deserializedUniqueTokenFilter; - } - throw new IllegalStateException("Missing required property: name"); + UniqueTokenFilter deserializedUniqueTokenFilter = new UniqueTokenFilter(name); + deserializedUniqueTokenFilter.odataType = odataType; + deserializedUniqueTokenFilter.onlyOnSamePosition = onlyOnSamePosition; + return deserializedUniqueTokenFilter; }); } } 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/indexes/models/VectorEncodingFormat.java index 0ddddb3f8c19..6793fbed8e35 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/indexes/models/VectorEncodingFormat.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The encoding format for interpreting vector field contents. */ public final class VectorEncodingFormat extends ExpandableStringEnum { + /** * Encoding format representing bits packed into a wider data type. */ @@ -22,7 +20,7 @@ public final class VectorEncodingFormat extends ExpandableStringEnum 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. + */ + public VectorSearch setProfiles(VectorSearchProfile... profiles) { + this.profiles = (profiles == null) ? null : Arrays.asList(profiles); + return this; + } + /** * Set the profiles property: Defines combinations of configurations to use with vector search. * @@ -85,6 +94,18 @@ public List getAlgorithms() { return this.algorithms; } + /** + * 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 algorithms property: Contains configuration options specific to the algorithm used during indexing or * querying. @@ -108,6 +129,17 @@ 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. + */ + public VectorSearch setVectorizers(VectorSearchVectorizer... vectorizers) { + this.vectorizers = (vectorizers == null) ? null : Arrays.asList(vectorizers); + return this; + } + /** * Set the vectorizers property: Contains configuration options on how to vectorize text vector queries. * @@ -131,6 +163,18 @@ public List getCompressions() { return this.compressions; } + /** + * 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 compressions property: Contains configuration options specific to the compression method used during * indexing or querying. @@ -196,50 +240,4 @@ public static VectorSearch fromJson(JsonReader jsonReader) throws IOException { 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/indexes/models/VectorSearchAlgorithmConfiguration.java index 9622b80fd75d..290c2c44e475 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/indexes/models/VectorSearchAlgorithmConfiguration.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @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"); @@ -33,7 +31,7 @@ public class VectorSearchAlgorithmConfiguration implements JsonSerializable { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -113,30 +112,23 @@ 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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedVectorSearchAlgorithmConfiguration; - } - throw new IllegalStateException("Missing required property: name"); + VectorSearchAlgorithmConfiguration deserializedVectorSearchAlgorithmConfiguration + = new VectorSearchAlgorithmConfiguration(name); + deserializedVectorSearchAlgorithmConfiguration.kind = kind; + 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/indexes/models/VectorSearchAlgorithmKind.java index efddd7174766..8ebf9de59b53 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/indexes/models/VectorSearchAlgorithmKind.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The algorithm used for indexing and querying. */ public final class VectorSearchAlgorithmKind extends ExpandableStringEnum { + /** * HNSW (Hierarchical Navigable Small World), a type of approximate nearest neighbors algorithm. */ @@ -28,7 +26,7 @@ public final class VectorSearchAlgorithmKind extends ExpandableStringEnum { + /** * Measures the angle between vectors to quantify their similarity, disregarding magnitude. The smaller the angle, * the closer the similarity. @@ -45,7 +43,7 @@ public final class VectorSearchAlgorithmMetric extends ExpandableStringEnum { + /* - * 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"); @@ -31,27 +29,6 @@ public class VectorSearchCompression implements JsonSerializable { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -270,26 +182,17 @@ 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; - Double defaultOversampling = null; RescoringOptions rescoringOptions = null; Integer truncationDimension = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { compressionName = reader.getString(); - compressionNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchCompressionKind.fromString(reader.getString()); - } else if ("rerankWithOriginalVectors".equals(fieldName)) { - rerankWithOriginalVectors = reader.getNullable(JsonReader::getBoolean); - } else if ("defaultOversampling".equals(fieldName)) { - defaultOversampling = reader.getNullable(JsonReader::getDouble); } else if ("rescoringOptions".equals(fieldName)) { rescoringOptions = RescoringOptions.fromJson(reader); } else if ("truncationDimension".equals(fieldName)) { @@ -298,18 +201,11 @@ 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; - - return deserializedVectorSearchCompression; - } - throw new IllegalStateException("Missing required property: name"); + VectorSearchCompression deserializedVectorSearchCompression = new VectorSearchCompression(compressionName); + deserializedVectorSearchCompression.kind = kind; + deserializedVectorSearchCompression.rescoringOptions = rescoringOptions; + deserializedVectorSearchCompression.truncationDimension = truncationDimension; + 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/indexes/models/VectorSearchCompressionKind.java index f9995b9dace4..2807fd3683b8 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/indexes/models/VectorSearchCompressionKind.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The compression method used for indexing and querying. */ 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 @@ -32,7 +30,7 @@ public final class VectorSearchCompressionKind 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. @@ -33,7 +31,7 @@ public final class VectorSearchCompressionRescoreStorageMethod /** * Creates a new instance of VectorSearchCompressionRescoreStorageMethod value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -43,7 +41,7 @@ public VectorSearchCompressionRescoreStorageMethod() { /** * Creates or finds a VectorSearchCompressionRescoreStorageMethod from its string representation. - * + * * @param name a name to look for. * @return the corresponding VectorSearchCompressionRescoreStorageMethod. */ @@ -54,7 +52,7 @@ public static VectorSearchCompressionRescoreStorageMethod fromString(String name /** * Gets known VectorSearchCompressionRescoreStorageMethod values. - * + * * @return known VectorSearchCompressionRescoreStorageMethod values. */ @Generated 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/indexes/models/VectorSearchCompressionTarget.java index 2041e9bb92f0..c17940e842f0 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/indexes/models/VectorSearchCompressionTarget.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,15 +11,16 @@ * The quantized data type of compressed vector values. */ public final class VectorSearchCompressionTarget extends ExpandableStringEnum { + /** - * Static value int8 for VectorSearchCompressionTarget. + * 8-bit signed integer. */ @Generated public static final VectorSearchCompressionTarget INT8 = fromString("int8"); /** * Creates a new instance of VectorSearchCompressionTarget value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -32,7 +30,7 @@ public VectorSearchCompressionTarget() { /** * Creates or finds a VectorSearchCompressionTarget from its string representation. - * + * * @param name a name to look for. * @return the corresponding VectorSearchCompressionTarget. */ @@ -43,7 +41,7 @@ public static VectorSearchCompressionTarget fromString(String name) { /** * Gets known VectorSearchCompressionTarget values. - * + * * @return known VectorSearchCompressionTarget values. */ @Generated 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/indexes/models/VectorSearchProfile.java index 44e8e38a8cd0..ff695e8d0812 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/indexes/models/VectorSearchProfile.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,14 +10,13 @@ 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. */ @Fluent public final class VectorSearchProfile implements JsonSerializable { + /* * The name to associate with this particular vector search profile. */ @@ -47,7 +43,7 @@ public final class VectorSearchProfile implements JsonSerializable { - boolean nameFound = false; String name = null; - boolean algorithmConfigurationNameFound = false; String algorithmConfigurationName = null; String vectorizerName = null; String compressionName = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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)) { @@ -174,24 +165,11 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + VectorSearchProfile deserializedVectorSearchProfile + = new VectorSearchProfile(name, algorithmConfigurationName); + deserializedVectorSearchProfile.vectorizerName = vectorizerName; + deserializedVectorSearchProfile.compressionName = compressionName; + 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/indexes/models/VectorSearchVectorizer.java index df2b0e133229..4ebd1d15215f 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/indexes/models/VectorSearchVectorizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -19,8 +16,9 @@ */ @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"); @@ -33,7 +31,7 @@ public class VectorSearchVectorizer implements JsonSerializable { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -117,29 +116,22 @@ 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) { String fieldName = reader.getFieldName(); reader.nextToken(); - 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; - - return deserializedVectorSearchVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + VectorSearchVectorizer deserializedVectorSearchVectorizer = new VectorSearchVectorizer(vectorizerName); + deserializedVectorSearchVectorizer.kind = kind; + 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/indexes/models/VectorSearchVectorizerKind.java index e50d7e11f62f..efb652e99b7e 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/indexes/models/VectorSearchVectorizerKind.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The vectorization method to be used during query time. */ public final class VectorSearchVectorizerKind extends ExpandableStringEnum { + /** * Generate embeddings using an Azure OpenAI resource at query time. */ @@ -41,7 +39,7 @@ public final class VectorSearchVectorizerKind extends ExpandableStringEnum 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) { 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)) { @@ -157,36 +148,19 @@ 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"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + VisionVectorizeSkill deserializedVisionVectorizeSkill + = new VisionVectorizeSkill(inputs, outputs, modelVersion); + deserializedVisionVectorizeSkill.setName(name); + deserializedVisionVectorizeSkill.setDescription(description); + deserializedVisionVectorizeSkill.setContext(context); + deserializedVisionVectorizeSkill.odataType = odataType; + 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/indexes/models/VisualFeature.java index 6ac2ce27b315..6710ea27cad0 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/indexes/models/VisualFeature.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The strings indicating what visual feature types to return. */ public final class VisualFeature extends ExpandableStringEnum { + /** * Visual features recognized as adult persons. */ @@ -58,7 +56,7 @@ public final class VisualFeature extends ExpandableStringEnum { /** * Creates a new instance of VisualFeature value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -68,7 +66,7 @@ public VisualFeature() { /** * Creates or finds a VisualFeature from its string representation. - * + * * @param name a name to look for. * @return the corresponding VisualFeature. */ @@ -79,7 +77,7 @@ public static VisualFeature fromString(String name) { /** * Gets known VisualFeature values. - * + * * @return known VisualFeature values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiHttpHeaders.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiHttpHeaders.java new file mode 100644 index 000000000000..5cee33fb2e51 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebApiHttpHeaders.java @@ -0,0 +1,97 @@ +// 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.indexes.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.LinkedHashMap; +import java.util.Map; + +/** + * A dictionary of http request headers. + */ +@Fluent +public final class WebApiHttpHeaders implements JsonSerializable { + + /* + * A dictionary of http request headers. + */ + @Generated + private Map additionalProperties; + + /** + * Creates an instance of WebApiHttpHeaders class. + */ + @Generated + public WebApiHttpHeaders() { + } + + /** + * Get the additionalProperties property: A dictionary of http request headers. + * + * @return the additionalProperties value. + */ + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + /** + * Set the additionalProperties property: A dictionary of http request headers. + * + * @param additionalProperties the additionalProperties value to set. + * @return the WebApiHttpHeaders object itself. + */ + @Generated + public WebApiHttpHeaders setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @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 WebApiHttpHeaders from the JsonReader. + * + * @param jsonReader The JsonReader being read. + * @return An instance of WebApiHttpHeaders 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 WebApiHttpHeaders. + */ + @Generated + public static WebApiHttpHeaders fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + WebApiHttpHeaders deserializedWebApiHttpHeaders = new WebApiHttpHeaders(); + 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.getString()); + } + deserializedWebApiHttpHeaders.additionalProperties = additionalProperties; + return deserializedWebApiHttpHeaders; + }); + } +} 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/indexes/models/WebApiSkill.java index a17d7d74b24d..4708e1ec4f95 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/indexes/models/WebApiSkill.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -14,17 +11,16 @@ 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. */ @Fluent -public class WebApiSkill extends SearchIndexerSkill { +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"; @@ -39,7 +35,7 @@ public class WebApiSkill extends SearchIndexerSkill { * The headers required to make the http request. */ @Generated - private Map httpHeaders; + private WebApiHttpHeaders httpHeaders; /* * The method for the http request. @@ -85,7 +81,7 @@ public class WebApiSkill extends SearchIndexerSkill { /** * Creates an instance of WebApiSkill class. - * + * * @param inputs the inputs value to set. * @param outputs the outputs value to set. * @param uri the uri value to set. @@ -97,8 +93,8 @@ public WebApiSkill(List inputs, List getHttpHeaders() { + public WebApiHttpHeaders getHttpHeaders() { return this.httpHeaders; } /** * Set the httpHeaders property: The headers required to make the http request. - * + * * @param httpHeaders the httpHeaders value to set. * @return the WebApiSkill object itself. */ @Generated - public WebApiSkill setHttpHeaders(Map httpHeaders) { + public WebApiSkill setHttpHeaders(WebApiHttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; return this; } /** * Get the httpMethod property: The method for the http request. - * + * * @return the httpMethod value. */ @Generated @@ -151,7 +147,7 @@ public String getHttpMethod() { /** * Set the httpMethod property: The method for the http request. - * + * * @param httpMethod the httpMethod value to set. * @return the WebApiSkill object itself. */ @@ -163,7 +159,7 @@ public WebApiSkill setHttpMethod(String httpMethod) { /** * Get the timeout property: The desired timeout for the request. Default is 30 seconds. - * + * * @return the timeout value. */ @Generated @@ -173,7 +169,7 @@ public Duration getTimeout() { /** * Set the timeout property: The desired timeout for the request. Default is 30 seconds. - * + * * @param timeout the timeout value to set. * @return the WebApiSkill object itself. */ @@ -185,7 +181,7 @@ public WebApiSkill setTimeout(Duration timeout) { /** * Get the batchSize property: The desired batch size which indicates number of documents. - * + * * @return the batchSize value. */ @Generated @@ -195,7 +191,7 @@ public Integer getBatchSize() { /** * Set the batchSize property: The desired batch size which indicates number of documents. - * + * * @param batchSize the batchSize value to set. * @return the WebApiSkill object itself. */ @@ -207,7 +203,7 @@ public WebApiSkill setBatchSize(Integer batchSize) { /** * Get the degreeOfParallelism property: If set, the number of parallel calls that can be made to the Web API. - * + * * @return the degreeOfParallelism value. */ @Generated @@ -217,7 +213,7 @@ public Integer getDegreeOfParallelism() { /** * Set the degreeOfParallelism property: If set, the number of parallel calls that can be made to the Web API. - * + * * @param degreeOfParallelism the degreeOfParallelism value to set. * @return the WebApiSkill object itself. */ @@ -233,7 +229,7 @@ public WebApiSkill setDegreeOfParallelism(Integer degreeOfParallelism) { * 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 @@ -247,7 +243,7 @@ public String getAuthResourceId() { * 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. */ @@ -262,7 +258,7 @@ public WebApiSkill setAuthResourceId(String authResourceId) { * 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 @@ -275,7 +271,7 @@ public SearchIndexerDataIdentity getAuthIdentity() { * 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. */ @@ -329,7 +325,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("context", getContext()); jsonWriter.writeStringField("uri", this.uri); jsonWriter.writeStringField("@odata.type", this.odataType); - jsonWriter.writeMapField("httpHeaders", this.httpHeaders, (writer, element) -> writer.writeString(element)); + jsonWriter.writeJsonField("httpHeaders", this.httpHeaders); jsonWriter.writeStringField("httpMethod", this.httpMethod); jsonWriter.writeStringField("timeout", CoreUtils.durationToStringWithDays(this.timeout)); jsonWriter.writeNumberField("batchSize", this.batchSize); @@ -341,7 +337,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebApiSkill from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebApiSkill if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -351,43 +347,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static WebApiSkill fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - String discriminatorValue = null; - try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading - while (readerToUse.nextToken() != JsonToken.END_OBJECT) { - String fieldName = readerToUse.getFieldName(); - readerToUse.nextToken(); - if ("@odata.type".equals(fieldName)) { - discriminatorValue = readerToUse.getString(); - break; - } else { - readerToUse.skipChildren(); - } - } - // Use the discriminator value to determine which subtype should be deserialized. - if ("#Microsoft.Skills.Custom.ChatCompletionSkill".equals(discriminatorValue)) { - return ChatCompletionSkill.fromJson(readerToUse.reset()); - } else { - return fromJsonKnownDiscriminator(readerToUse.reset()); - } - } - }); - } - - @Generated - static WebApiSkill fromJsonKnownDiscriminator(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; + WebApiHttpHeaders httpHeaders = null; String httpMethod = null; Duration timeout = null; Integer batchSize = null; @@ -397,13 +364,10 @@ static WebApiSkill fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx 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)) { @@ -412,11 +376,10 @@ static WebApiSkill fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx 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)) { - httpHeaders = reader.readMap(reader1 -> reader1.getString()); + httpHeaders = WebApiHttpHeaders.fromJson(reader); } else if ("httpMethod".equals(fieldName)) { httpMethod = reader.getString(); } else if ("timeout".equals(fieldName)) { @@ -433,35 +396,19 @@ static WebApiSkill fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx 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/indexes/models/WebApiVectorizer.java index e561eaa7e212..b1f856ce8a21 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/indexes/models/WebApiVectorizer.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,8 +16,9 @@ */ @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; @@ -33,7 +31,7 @@ public final class WebApiVectorizer extends VectorSearchVectorizer { /** * Creates an instance of WebApiVectorizer class. - * + * * @param vectorizerName the vectorizerName value to set. */ @Generated @@ -42,8 +40,8 @@ public WebApiVectorizer(String 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 @@ -54,7 +52,7 @@ public VectorSearchVectorizerKind getKind() { /** * Get the webApiParameters property: Specifies the properties of the user-defined vectorizer. - * + * * @return the webApiParameters value. */ @Generated @@ -64,7 +62,7 @@ public WebApiVectorizerParameters getWebApiParameters() { /** * Set the webApiParameters property: Specifies the properties of the user-defined vectorizer. - * + * * @param webApiParameters the webApiParameters value to set. * @return the WebApiVectorizer object itself. */ @@ -89,7 +87,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebApiVectorizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebApiVectorizer if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -99,17 +97,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { vectorizerName = reader.getString(); - vectorizerNameFound = true; } else if ("kind".equals(fieldName)) { kind = VectorSearchVectorizerKind.fromString(reader.getString()); } else if ("customWebApiParameters".equals(fieldName)) { @@ -118,14 +113,10 @@ public static WebApiVectorizer fromJson(JsonReader jsonReader) throws IOExceptio reader.skipChildren(); } } - if (vectorizerNameFound) { - WebApiVectorizer deserializedWebApiVectorizer = new WebApiVectorizer(vectorizerName); - deserializedWebApiVectorizer.kind = kind; - deserializedWebApiVectorizer.webApiParameters = webApiParameters; - - return deserializedWebApiVectorizer; - } - throw new IllegalStateException("Missing required property: name"); + WebApiVectorizer deserializedWebApiVectorizer = new WebApiVectorizer(vectorizerName); + deserializedWebApiVectorizer.kind = kind; + deserializedWebApiVectorizer.webApiParameters = webApiParameters; + 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/indexes/models/WebApiVectorizerParameters.java index 2e54f92a74be..1a04d6659d6e 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/indexes/models/WebApiVectorizerParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,6 +19,7 @@ */ @Fluent public final class WebApiVectorizerParameters implements JsonSerializable { + /* * The URI of the Web API providing the vectorizer. */ @@ -73,7 +71,7 @@ public WebApiVectorizerParameters() { /** * Get the url property: The URI of the Web API providing the vectorizer. - * + * * @return the url value. */ @Generated @@ -83,7 +81,7 @@ public String getUrl() { /** * Set the url property: The URI of the Web API providing the vectorizer. - * + * * @param url the url value to set. * @return the WebApiVectorizerParameters object itself. */ @@ -95,7 +93,7 @@ public WebApiVectorizerParameters setUrl(String url) { /** * Get the httpHeaders property: The headers required to make the HTTP request. - * + * * @return the httpHeaders value. */ @Generated @@ -105,7 +103,7 @@ public Map getHttpHeaders() { /** * Set the httpHeaders property: The headers required to make the HTTP request. - * + * * @param httpHeaders the httpHeaders value to set. * @return the WebApiVectorizerParameters object itself. */ @@ -117,7 +115,7 @@ public WebApiVectorizerParameters setHttpHeaders(Map httpHeaders /** * Get the httpMethod property: The method for the HTTP request. - * + * * @return the httpMethod value. */ @Generated @@ -127,7 +125,7 @@ public String getHttpMethod() { /** * Set the httpMethod property: The method for the HTTP request. - * + * * @param httpMethod the httpMethod value to set. * @return the WebApiVectorizerParameters object itself. */ @@ -139,7 +137,7 @@ public WebApiVectorizerParameters setHttpMethod(String httpMethod) { /** * Get the timeout property: The desired timeout for the request. Default is 30 seconds. - * + * * @return the timeout value. */ @Generated @@ -149,7 +147,7 @@ public Duration getTimeout() { /** * Set the timeout property: The desired timeout for the request. Default is 30 seconds. - * + * * @param timeout the timeout value to set. * @return the WebApiVectorizerParameters object itself. */ @@ -166,7 +164,7 @@ public WebApiVectorizerParameters setTimeout(Duration timeout) { * 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 @@ -181,7 +179,7 @@ public String getAuthResourceId() { * 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. */ @@ -196,7 +194,7 @@ public WebApiVectorizerParameters setAuthResourceId(String authResourceId) { * 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 @@ -209,7 +207,7 @@ public SearchIndexerDataIdentity getAuthIdentity() { * 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. */ @@ -237,7 +235,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebApiVectorizerParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebApiVectorizerParameters if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -250,7 +248,6 @@ public static WebApiVectorizerParameters fromJson(JsonReader jsonReader) throws while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("uri".equals(fieldName)) { deserializedWebApiVectorizerParameters.url = reader.getString(); } else if ("httpHeaders".equals(fieldName)) { @@ -269,7 +266,6 @@ public static WebApiVectorizerParameters fromJson(JsonReader jsonReader) throws reader.skipChildren(); } } - return deserializedWebApiVectorizerParameters; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSource.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSource.java index fa6d895775cd..dbc10ee8ffc1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSource.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSource.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -18,6 +15,7 @@ */ @Fluent public final class WebKnowledgeSource extends KnowledgeSource { + /* * The type of the knowledge source. */ @@ -32,7 +30,7 @@ public final class WebKnowledgeSource extends KnowledgeSource { /** * Creates an instance of WebKnowledgeSource class. - * + * * @param name the name value to set. */ @Generated @@ -42,7 +40,7 @@ public WebKnowledgeSource(String name) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -53,7 +51,7 @@ public KnowledgeSourceKind getKind() { /** * Get the webParameters property: The parameters for the web knowledge source. - * + * * @return the webParameters value. */ @Generated @@ -63,7 +61,7 @@ public WebKnowledgeSourceParameters getWebParameters() { /** * Set the webParameters property: The parameters for the web knowledge source. - * + * * @param webParameters the webParameters value to set. * @return the WebKnowledgeSource object itself. */ @@ -121,7 +119,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebKnowledgeSource from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebKnowledgeSource if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -131,7 +129,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static WebKnowledgeSource fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean nameFound = false; String name = null; String description = null; String eTag = null; @@ -141,10 +138,8 @@ public static WebKnowledgeSource 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 ("description".equals(fieldName)) { description = reader.getString(); } else if ("@odata.etag".equals(fieldName)) { @@ -159,17 +154,13 @@ public static WebKnowledgeSource fromJson(JsonReader jsonReader) throws IOExcept reader.skipChildren(); } } - if (nameFound) { - WebKnowledgeSource deserializedWebKnowledgeSource = new WebKnowledgeSource(name); - deserializedWebKnowledgeSource.setDescription(description); - deserializedWebKnowledgeSource.setETag(eTag); - deserializedWebKnowledgeSource.setEncryptionKey(encryptionKey); - deserializedWebKnowledgeSource.kind = kind; - deserializedWebKnowledgeSource.webParameters = webParameters; - - return deserializedWebKnowledgeSource; - } - throw new IllegalStateException("Missing required property: name"); + WebKnowledgeSource deserializedWebKnowledgeSource = new WebKnowledgeSource(name); + deserializedWebKnowledgeSource.setDescription(description); + deserializedWebKnowledgeSource.setETag(eTag); + deserializedWebKnowledgeSource.setEncryptionKey(encryptionKey); + deserializedWebKnowledgeSource.kind = kind; + deserializedWebKnowledgeSource.webParameters = webParameters; + return deserializedWebKnowledgeSource; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomain.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomain.java index cc483843ffc8..0c5c88196a4e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomain.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomain.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public final class WebKnowledgeSourceDomain implements JsonSerializable { + /* * The address of the domain. */ @@ -33,7 +31,7 @@ public final class WebKnowledgeSourceDomain implements JsonSerializable { - boolean addressFound = false; String address = null; Boolean includeSubpages = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("address".equals(fieldName)) { address = reader.getString(); - addressFound = true; } else if ("includeSubpages".equals(fieldName)) { includeSubpages = reader.getNullable(JsonReader::getBoolean); } else { reader.skipChildren(); } } - if (addressFound) { - WebKnowledgeSourceDomain deserializedWebKnowledgeSourceDomain = new WebKnowledgeSourceDomain(address); - deserializedWebKnowledgeSourceDomain.includeSubpages = includeSubpages; - - return deserializedWebKnowledgeSourceDomain; - } - throw new IllegalStateException("Missing required property: address"); + WebKnowledgeSourceDomain deserializedWebKnowledgeSourceDomain = new WebKnowledgeSourceDomain(address); + deserializedWebKnowledgeSourceDomain.includeSubpages = includeSubpages; + return deserializedWebKnowledgeSourceDomain; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomains.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomains.java index f246b8511be6..7306145cd4a3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomains.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomains.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,14 +18,15 @@ */ @Fluent public final class WebKnowledgeSourceDomains implements JsonSerializable { + /* - * Domains that are allowed for web results + * Domains that are allowed for web results. */ @Generated private List allowedDomains; /* - * Domains that are blocked from web results + * Domains that are blocked from web results. */ @Generated private List blockedDomains; @@ -41,7 +40,7 @@ public WebKnowledgeSourceDomains() { /** * Get the allowedDomains property: Domains that are allowed for web results. - * + * * @return the allowedDomains value. */ @Generated @@ -51,7 +50,18 @@ public List getAllowedDomains() { /** * Set the allowedDomains property: Domains that are allowed for web results. - * + * + * @param allowedDomains the allowedDomains value to set. + * @return the WebKnowledgeSourceDomains object itself. + */ + public WebKnowledgeSourceDomains setAllowedDomains(WebKnowledgeSourceDomain... allowedDomains) { + this.allowedDomains = (allowedDomains == null) ? null : Arrays.asList(allowedDomains); + return this; + } + + /** + * Set the allowedDomains property: Domains that are allowed for web results. + * * @param allowedDomains the allowedDomains value to set. * @return the WebKnowledgeSourceDomains object itself. */ @@ -63,7 +73,7 @@ public WebKnowledgeSourceDomains setAllowedDomains(List getBlockedDomains() { /** * Set the blockedDomains property: Domains that are blocked from web results. - * + * + * @param blockedDomains the blockedDomains value to set. + * @return the WebKnowledgeSourceDomains object itself. + */ + public WebKnowledgeSourceDomains setBlockedDomains(WebKnowledgeSourceDomain... blockedDomains) { + this.blockedDomains = (blockedDomains == null) ? null : Arrays.asList(blockedDomains); + return this; + } + + /** + * Set the blockedDomains property: Domains that are blocked from web results. + * * @param blockedDomains the blockedDomains value to set. * @return the WebKnowledgeSourceDomains object itself. */ @@ -99,7 +120,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebKnowledgeSourceDomains from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebKnowledgeSourceDomains if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -112,7 +133,6 @@ public static WebKnowledgeSourceDomains fromJson(JsonReader jsonReader) throws I while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("allowedDomains".equals(fieldName)) { List allowedDomains = reader.readArray(reader1 -> WebKnowledgeSourceDomain.fromJson(reader1)); @@ -125,7 +145,6 @@ public static WebKnowledgeSourceDomains fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - return deserializedWebKnowledgeSourceDomains; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceParameters.java index b0681e135001..1b905f3b6deb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceParameters.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -19,6 +16,7 @@ */ @Fluent public final class WebKnowledgeSourceParameters implements JsonSerializable { + /* * Domain allow/block configuration for web results. */ @@ -34,7 +32,7 @@ public WebKnowledgeSourceParameters() { /** * Get the domains property: Domain allow/block configuration for web results. - * + * * @return the domains value. */ @Generated @@ -44,7 +42,7 @@ public WebKnowledgeSourceDomains getDomains() { /** * Set the domains property: Domain allow/block configuration for web results. - * + * * @param domains the domains value to set. * @return the WebKnowledgeSourceParameters object itself. */ @@ -67,7 +65,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebKnowledgeSourceParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebKnowledgeSourceParameters if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -80,14 +78,12 @@ public static WebKnowledgeSourceParameters fromJson(JsonReader jsonReader) throw while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("domains".equals(fieldName)) { deserializedWebKnowledgeSourceParameters.domains = WebKnowledgeSourceDomains.fromJson(reader); } else { reader.skipChildren(); } } - return deserializedWebKnowledgeSourceParameters; }); } 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/indexes/models/WordDelimiterTokenFilter.java index 80adcf6d8d96..03a6de571487 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/indexes/models/WordDelimiterTokenFilter.java @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; import com.azure.core.annotation.Fluent; @@ -22,7 +20,7 @@ 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"; @@ -45,14 +43,14 @@ public final class WordDelimiterTokenFilter extends TokenFilter { * "Azure-Search" becomes "AzureSearch". Default is false. */ @Generated - private Boolean wordsCatenated; + 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. */ @Generated - private Boolean numbersCatenated; + private Boolean catenateNumbers; /* * A value indicating whether all subword parts will be catenated. For example, if this is set to true, @@ -104,7 +102,7 @@ public WordDelimiterTokenFilter(String 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. */ @@ -121,7 +119,7 @@ public String getOdataType() { * @return the generateWordParts value. */ @Generated - public Boolean generateWordParts() { + public Boolean isGenerateWordParts() { return this.generateWordParts; } @@ -144,7 +142,7 @@ public WordDelimiterTokenFilter setGenerateWordParts(Boolean generateWordParts) * @return the generateNumberParts value. */ @Generated - public Boolean generateNumberParts() { + public Boolean isGenerateNumberParts() { return this.generateNumberParts; } @@ -161,50 +159,50 @@ public WordDelimiterTokenFilter setGenerateNumberParts(Boolean generateNumberPar } /** - * Get the wordsCatenated property: A value indicating whether maximum runs of word parts will be catenated. For + * 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 wordsCatenated value. + * @return the catenateWords value. */ @Generated - public Boolean areWordsCatenated() { - return this.wordsCatenated; + public Boolean isCatenateWords() { + return this.catenateWords; } /** - * Set the wordsCatenated property: A value indicating whether maximum runs of word parts will be catenated. For + * 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 wordsCatenated the wordsCatenated value to set. + * @param catenateWords the catenateWords value to set. * @return the WordDelimiterTokenFilter object itself. */ @Generated - public WordDelimiterTokenFilter setWordsCatenated(Boolean wordsCatenated) { - this.wordsCatenated = wordsCatenated; + 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. */ @Generated - public Boolean areNumbersCatenated() { - return this.numbersCatenated; + 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. */ @Generated - public WordDelimiterTokenFilter setNumbersCatenated(Boolean numbersCatenated) { - this.numbersCatenated = numbersCatenated; + public WordDelimiterTokenFilter setCatenateNumbers(Boolean catenateNumbers) { + this.catenateNumbers = catenateNumbers; return this; } @@ -215,7 +213,7 @@ public WordDelimiterTokenFilter setNumbersCatenated(Boolean numbersCatenated) { * @return the catenateAll value. */ @Generated - public Boolean catenateAll() { + public Boolean isCatenateAll() { return this.catenateAll; } @@ -239,7 +237,7 @@ public WordDelimiterTokenFilter setCatenateAll(Boolean catenateAll) { * @return the splitOnCaseChange value. */ @Generated - public Boolean splitOnCaseChange() { + public Boolean isSplitOnCaseChange() { return this.splitOnCaseChange; } @@ -287,7 +285,7 @@ public WordDelimiterTokenFilter setPreserveOriginal(Boolean preserveOriginal) { * @return the splitOnNumerics value. */ @Generated - public Boolean splitOnNumerics() { + public Boolean isSplitOnNumerics() { return this.splitOnNumerics; } @@ -338,6 +336,17 @@ 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. + */ + public WordDelimiterTokenFilter setProtectedWords(String... protectedWords) { + this.protectedWords = (protectedWords == null) ? null : Arrays.asList(protectedWords); + return this; + } + /** * Set the protectedWords property: A list of tokens to protect from being delimited. * @@ -361,8 +370,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); @@ -385,13 +394,12 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -403,7 +411,6 @@ public static WordDelimiterTokenFilter fromJson(JsonReader jsonReader) throws IO 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)) { @@ -411,9 +418,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)) { @@ -430,33 +437,19 @@ 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/indexes/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/package-info.java index 59602397f637..f2bc920d9996 100644 --- 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 @@ -1,11 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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 SearchServiceClient. + * 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. */ 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 index 0e24b2a8baf2..0d58d3da58a1 100644 --- 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 @@ -1,470 +1,9 @@ // 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:

- * - *
    - *
  • 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 SearchIndexClient. + * 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; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalAsyncClient.java new file mode 100644 index 000000000000..588f36c7ac29 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalAsyncClient.java @@ -0,0 +1,246 @@ +// 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.knowledgebases; + +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.HttpPipeline; +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.SearchServiceVersion; +import com.azure.search.documents.implementation.KnowledgeBaseRetrievalClientImpl; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the asynchronous KnowledgeBaseRetrievalClient type. + */ +@ServiceClient(builder = KnowledgeBaseRetrievalClientBuilder.class, isAsync = true) +public final class KnowledgeBaseRetrievalAsyncClient { + + @Generated + private final KnowledgeBaseRetrievalClientImpl serviceClient; + + /** + * Initializes an instance of KnowledgeBaseRetrievalAsyncClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + KnowledgeBaseRetrievalAsyncClient(KnowledgeBaseRetrievalClientImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. + * + * @return the pipeline. + */ + HttpPipeline getHttpPipeline() { + return serviceClient.getHttpPipeline(); + } + + /** + * Gets the endpoint used to communicate with the Azure AI Search service. + * + * @return The endpoint. + */ + public String getEndpoint() { + return serviceClient.getEndpoint(); + } + + /** + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. + * + * @return The service version. + */ + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     messages (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     intents (Optional): [
+     *          (Optional){
+     *             type: String(semantic) (Required)
+     *         }
+     *     ]
+     *     maxRuntimeInSeconds: Integer (Optional)
+     *     maxOutputSize: Integer (Optional)
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     includeActivity: Boolean (Optional)
+     *     outputMode: String(extractiveData/answerSynthesis) (Optional)
+     *     knowledgeSourceParams (Optional): [
+     *          (Optional){
+     *             kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             knowledgeSourceName: String (Required)
+     *             includeReferences: Boolean (Optional)
+     *             includeReferenceSourceData: Boolean (Optional)
+     *             alwaysQuerySource: Boolean (Optional)
+     *             rerankerThreshold: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     response (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     activity (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint/modelQueryPlanning/modelAnswerSynthesis/agenticReasoning) (Required)
+     *             id: int (Required)
+     *             elapsedMs: Integer (Optional)
+     *             error (Optional): {
+     *                 code: String (Optional)
+     *                 message: String (Optional)
+     *                 target: String (Optional)
+     *                 details (Optional): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *                 additionalInfo (Optional): [
+     *                      (Optional){
+     *                         type: String (Optional)
+     *                         info (Optional): {
+     *                             String: Object (Required)
+     *                         }
+     *                     }
+     *                 ]
+     *             }
+     *         }
+     *     ]
+     *     references (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             id: String (Required)
+     *             activitySource: int (Required)
+     *             sourceData (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *             rerankerScore: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @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 output contract for the retrieval response along with {@link Response} on successful completion of + * {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> retrieveWithResponse(String knowledgeBaseName, BinaryData retrievalRequest, + RequestOptions requestOptions) { + return this.serviceClient.retrieveWithResponseAsync(knowledgeBaseName, retrievalRequest, requestOptions); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @param querySourceAuthorization Token identifying the user for which the query is being executed. This token is + * used to enforce security restrictions on documents. + * @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 output contract for the retrieval response on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono retrieve(String knowledgeBaseName, + KnowledgeBaseRetrievalRequest retrievalRequest, String querySourceAuthorization) { + // Generated convenience method for retrieveWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (querySourceAuthorization != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-query-source-authorization"), + querySourceAuthorization); + } + return retrieveWithResponse(knowledgeBaseName, BinaryData.fromObject(retrievalRequest), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeBaseRetrievalResponse.class)); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @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 output contract for the retrieval response on successful completion of {@link Mono}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono retrieve(String knowledgeBaseName, + KnowledgeBaseRetrievalRequest retrievalRequest) { + // Generated convenience method for retrieveWithResponse + RequestOptions requestOptions = new RequestOptions(); + return retrieveWithResponse(knowledgeBaseName, BinaryData.fromObject(retrievalRequest), requestOptions) + .flatMap(FluxUtil::toMono) + .map(protocolMethodData -> protocolMethodData.toObject(KnowledgeBaseRetrievalResponse.class)); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClient.java new file mode 100644 index 000000000000..d2d1d1aae7b1 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClient.java @@ -0,0 +1,243 @@ +// 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.knowledgebases; + +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.HttpPipeline; +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.SearchServiceVersion; +import com.azure.search.documents.implementation.KnowledgeBaseRetrievalClientImpl; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; + +/** + * Initializes a new instance of the synchronous KnowledgeBaseRetrievalClient type. + */ +@ServiceClient(builder = KnowledgeBaseRetrievalClientBuilder.class) +public final class KnowledgeBaseRetrievalClient { + + @Generated + private final KnowledgeBaseRetrievalClientImpl serviceClient; + + /** + * Initializes an instance of KnowledgeBaseRetrievalClient class. + * + * @param serviceClient the service client implementation. + */ + @Generated + KnowledgeBaseRetrievalClient(KnowledgeBaseRetrievalClientImpl serviceClient) { + this.serviceClient = serviceClient; + } + + /** + * Gets the {@link HttpPipeline} used to communicate with the Azure AI Search service. + * + * @return the pipeline. + */ + HttpPipeline getHttpPipeline() { + return serviceClient.getHttpPipeline(); + } + + /** + * Gets the endpoint used to communicate with the Azure AI Search service. + * + * @return The endpoint. + */ + public String getEndpoint() { + return serviceClient.getEndpoint(); + } + + /** + * Gets the {@link SearchServiceVersion} used to communicate with the Azure AI Search service. + * + * @return The service version. + */ + public SearchServiceVersion getServiceVersion() { + return serviceClient.getServiceVersion(); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + *

Header Parameters

+ * + * + * + * + *
Header Parameters
NameTypeRequiredDescription
x-ms-query-source-authorizationStringNoToken identifying the user for which + * the query is being executed. This token is used to enforce security restrictions on documents.
+ * You can add these to a request with {@link RequestOptions#addHeader} + *

Request Body Schema

+ * + *
+     * {@code
+     * {
+     *     messages (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     intents (Optional): [
+     *          (Optional){
+     *             type: String(semantic) (Required)
+     *         }
+     *     ]
+     *     maxRuntimeInSeconds: Integer (Optional)
+     *     maxOutputSize: Integer (Optional)
+     *     retrievalReasoningEffort (Optional): {
+     *         kind: String(minimal/low/medium) (Required)
+     *     }
+     *     includeActivity: Boolean (Optional)
+     *     outputMode: String(extractiveData/answerSynthesis) (Optional)
+     *     knowledgeSourceParams (Optional): [
+     *          (Optional){
+     *             kind: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             knowledgeSourceName: String (Required)
+     *             includeReferences: Boolean (Optional)
+     *             includeReferenceSourceData: Boolean (Optional)
+     *             alwaysQuerySource: Boolean (Optional)
+     *             rerankerThreshold: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + *

Response Body Schema

+ * + *
+     * {@code
+     * {
+     *     response (Optional): [
+     *          (Optional){
+     *             role: String (Optional)
+     *             content (Required): [
+     *                  (Required){
+     *                     type: String(text/image) (Required)
+     *                 }
+     *             ]
+     *         }
+     *     ]
+     *     activity (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint/modelQueryPlanning/modelAnswerSynthesis/agenticReasoning) (Required)
+     *             id: int (Required)
+     *             elapsedMs: Integer (Optional)
+     *             error (Optional): {
+     *                 code: String (Optional)
+     *                 message: String (Optional)
+     *                 target: String (Optional)
+     *                 details (Optional): [
+     *                     (recursive schema, see above)
+     *                 ]
+     *                 additionalInfo (Optional): [
+     *                      (Optional){
+     *                         type: String (Optional)
+     *                         info (Optional): {
+     *                             String: Object (Required)
+     *                         }
+     *                     }
+     *                 ]
+     *             }
+     *         }
+     *     ]
+     *     references (Optional): [
+     *          (Optional){
+     *             type: String(searchIndex/azureBlob/indexedSharePoint/indexedOneLake/web/remoteSharePoint) (Required)
+     *             id: String (Required)
+     *             activitySource: int (Required)
+     *             sourceData (Optional): {
+     *                 String: Object (Required)
+     *             }
+     *             rerankerScore: Float (Optional)
+     *         }
+     *     ]
+     * }
+     * }
+     * 
+ * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @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 output contract for the retrieval response along with {@link Response}. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public Response retrieveWithResponse(String knowledgeBaseName, BinaryData retrievalRequest, + RequestOptions requestOptions) { + return this.serviceClient.retrieveWithResponse(knowledgeBaseName, retrievalRequest, requestOptions); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @param querySourceAuthorization Token identifying the user for which the query is being executed. This token is + * used to enforce security restrictions on documents. + * @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 output contract for the retrieval response. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeBaseRetrievalResponse retrieve(String knowledgeBaseName, + KnowledgeBaseRetrievalRequest retrievalRequest, String querySourceAuthorization) { + // Generated convenience method for retrieveWithResponse + RequestOptions requestOptions = new RequestOptions(); + if (querySourceAuthorization != null) { + requestOptions.setHeader(HttpHeaderName.fromString("x-ms-query-source-authorization"), + querySourceAuthorization); + } + return retrieveWithResponse(knowledgeBaseName, BinaryData.fromObject(retrievalRequest), requestOptions) + .getValue() + .toObject(KnowledgeBaseRetrievalResponse.class); + } + + /** + * KnowledgeBase retrieves relevant data from backing stores. + * + * @param knowledgeBaseName The name of the knowledge base. + * @param retrievalRequest The retrieval request to process. + * @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 output contract for the retrieval response. + */ + @Generated + @ServiceMethod(returns = ReturnType.SINGLE) + public KnowledgeBaseRetrievalResponse retrieve(String knowledgeBaseName, + KnowledgeBaseRetrievalRequest retrievalRequest) { + // Generated convenience method for retrieveWithResponse + RequestOptions requestOptions = new RequestOptions(); + return retrieveWithResponse(knowledgeBaseName, BinaryData.fromObject(retrievalRequest), requestOptions) + .getValue() + .toObject(KnowledgeBaseRetrievalResponse.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClientBuilder.java new file mode 100644 index 000000000000..8b3cff419532 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClientBuilder.java @@ -0,0 +1,377 @@ +// 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.knowledgebases; + +import com.azure.core.annotation.Generated; +import com.azure.core.annotation.ServiceClientBuilder; +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.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.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.builder.ClientBuilderUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.search.documents.SearchAudience; +import com.azure.search.documents.SearchServiceVersion; +import com.azure.search.documents.implementation.KnowledgeBaseRetrievalClientImpl; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * A builder for creating a new instance of the KnowledgeBaseRetrievalClient type. + */ +@ServiceClientBuilder(serviceClients = { KnowledgeBaseRetrievalClient.class, KnowledgeBaseRetrievalAsyncClient.class }) +public final class KnowledgeBaseRetrievalClientBuilder 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; + + /** + * Create an instance of the KnowledgeBaseRetrievalClientBuilder. + */ + @Generated + public KnowledgeBaseRetrievalClientBuilder() { + this.pipelinePolicies = new ArrayList<>(); + } + + /* + * The HTTP client used to send the request. + */ + @Generated + private HttpClient httpClient; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder httpClient(HttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + /* + * The HTTP pipeline to send requests through. + */ + @Generated + private HttpPipeline pipeline; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder 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; + } + + /* + * The logging configuration for HTTP requests and responses. + */ + @Generated + private HttpLogOptions httpLogOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder 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; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder clientOptions(ClientOptions clientOptions) { + this.clientOptions = clientOptions; + return this; + } + + /* + * The retry options to configure retry policy for failed requests. + */ + @Generated + private RetryOptions retryOptions; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder retryOptions(RetryOptions retryOptions) { + this.retryOptions = retryOptions; + return this; + } + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder 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; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /* + * The TokenCredential used for authentication. + */ + @Generated + private TokenCredential tokenCredential; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder credential(TokenCredential tokenCredential) { + this.tokenCredential = tokenCredential; + return this; + } + + /* + * The KeyCredential used for authentication. + */ + @Generated + private KeyCredential keyCredential; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder credential(KeyCredential keyCredential) { + this.keyCredential = keyCredential; + return this; + } + + /* + * The service endpoint + */ + @Generated + private String endpoint; + + /** + * {@inheritDoc}. + */ + @Generated + @Override + public KnowledgeBaseRetrievalClientBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * Service version + */ + @Generated + private SearchServiceVersion serviceVersion; + + /** + * Sets Service version. + * + * @param serviceVersion the serviceVersion value. + * @return the KnowledgeBaseRetrievalClientBuilder. + */ + @Generated + public KnowledgeBaseRetrievalClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; + return this; + } + + /* + * The retry policy that will attempt to retry failed requests, if applicable. + */ + @Generated + private RetryPolicy retryPolicy; + + /** + * Sets The retry policy that will attempt to retry failed requests, if applicable. + * + * @param retryPolicy the retryPolicy value. + * @return the KnowledgeBaseRetrievalClientBuilder. + */ + @Generated + public KnowledgeBaseRetrievalClientBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + /** + * Sets the Audience to use for authentication with Microsoft Entra ID. + *

+ * 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 KnowledgeBaseRetrievalClientBuilder object. + */ + public KnowledgeBaseRetrievalClientBuilder audience(SearchAudience audience) { + if (audience == null) { + this.scopes = DEFAULT_SCOPES; + } else { + this.scopes = new String[] { audience.getValue() + "/.default" }; + } + return this; + } + + /** + * Builds an instance of KnowledgeBaseRetrievalClientImpl with the provided parameters. + * + * @return an instance of KnowledgeBaseRetrievalClientImpl. + */ + @Generated + private KnowledgeBaseRetrievalClientImpl buildInnerClient() { + this.validateClient(); + HttpPipeline localPipeline = (pipeline != null) ? pipeline : createHttpPipeline(); + SearchServiceVersion localServiceVersion + = (serviceVersion != null) ? serviceVersion : SearchServiceVersion.getLatest(); + KnowledgeBaseRetrievalClientImpl client = new KnowledgeBaseRetrievalClientImpl(localPipeline, + JacksonAdapter.createDefaultSerializerAdapter(), this.endpoint, localServiceVersion); + return client; + } + + @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, 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; + } + + /** + * Builds an instance of KnowledgeBaseRetrievalAsyncClient class. + * + * @return an instance of KnowledgeBaseRetrievalAsyncClient. + */ + @Generated + public KnowledgeBaseRetrievalAsyncClient buildAsyncClient() { + return new KnowledgeBaseRetrievalAsyncClient(buildInnerClient()); + } + + /** + * Builds an instance of KnowledgeBaseRetrievalClient class. + * + * @return an instance of KnowledgeBaseRetrievalClient. + */ + @Generated + public KnowledgeBaseRetrievalClient buildClient() { + return new KnowledgeBaseRetrievalClient(buildInnerClient()); + } + + private static final ClientLogger LOGGER = new ClientLogger(KnowledgeBaseRetrievalClientBuilder.class); + + @Generated + private String[] scopes = DEFAULT_SCOPES; +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseAsyncClient.java deleted file mode 100644 index 219a9aa15704..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseAsyncClient.java +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.knowledgebases; - -import static com.azure.core.util.FluxUtil.monoError; -import static com.azure.core.util.FluxUtil.withContext; - -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.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.knowledgebases.implementation.KnowledgeBaseRetrievalClientImpl; -import com.azure.search.documents.knowledgebases.implementation.KnowledgeRetrievalsImpl; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; -import com.azure.search.documents.implementation.util.MappingUtils; - -import reactor.core.publisher.Mono; - -/** - * This class provides an asynchronous client for interacting with Azure AI Search Knowledge Agents, enabling retrieval of knowledge and data from various configured backing stores. - * - *

Overview

- *

- * The {@code SearchKnowledgeBaseAsyncClient} exposes asynchronous APIs for sending retrieval requests to a knowledge agent in Azure AI Search. The agent can aggregate and return relevant data from multiple sources, such as Azure AI Search indexes, vector stores, and other knowledge bases configured in your Azure AI Search instance. - *

- * - *

Getting Started

- *

- * Instances of this client are created via the {@link SearchKnowledgeBaseClientBuilder}, which supports fluent configuration of credentials, endpoints, agent names, API versions, and other client options. Authentication can be performed using either an API key or Azure Active Directory credentials. The builder allows you to specify all required parameters for your scenario. - *

- * - *

Thread Safety

- *

- * This client is thread-safe and intended to be shared and reused across threads. Client instances are immutable and do not maintain any mutable state. - *

- * - *

Additional Information

- *
    - *
  • For more information about Azure AI Search Knowledge Agents, see the Azure documentation.
  • - *
  • For authentication details, see the Azure AI Search security documentation.
  • - *
  • For Azure SDK for Java guidelines, see the Azure SDK for Java Introduction.
  • - *
- * - * @see SearchKnowledgeBaseClientBuilder - * @see SearchKnowledgeBaseClient - * @see com.azure.search.documents.knowledgebases - */ -@ServiceClient(builder = SearchKnowledgeBaseClientBuilder.class, isAsync = true) -public final class SearchKnowledgeBaseAsyncClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchKnowledgeBaseAsyncClient.class); - - private final String endpoint; - private final String agentName; - private final SearchServiceVersion serviceVersion; - private final HttpPipeline httpPipeline; - private final KnowledgeBaseRetrievalClientImpl impl; - private final KnowledgeRetrievalsImpl retrievals; - - /** - * Package-private constructor to be used by {@link SearchKnowledgeBaseClientBuilder}. - */ - SearchKnowledgeBaseAsyncClient(String endpoint, String agentName, SearchServiceVersion serviceVersion, - HttpPipeline httpPipeline) { - this.endpoint = endpoint; - this.agentName = agentName; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.impl - = new KnowledgeBaseRetrievalClientImpl(httpPipeline, endpoint, agentName, serviceVersion.getVersion()); - this.retrievals = impl.getKnowledgeRetrievals(); - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Gets the agent name. - * - * @return the agentName value. - */ - public String getAgentName() { - return this.agentName; - } - - /** - * Gets the API version. - * - * @return the apiVersion value. - */ - public SearchServiceVersion getServiceVersion() { - return this.serviceVersion; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Asynchronously retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. - * @return a {@link Mono} emitting the output contract for the retrieval response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono retrieve(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization) { - return retrievals.retrieveAsync(retrievalRequest, xMsQuerySourceAuthorization, null); - } - - /** - * Asynchronously retrieves relevant data from backing stores, with a full HTTP response. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. - * @return a {@link Mono} emitting the output contract for the retrieval response along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> - retrieveWithResponse(KnowledgeBaseRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization) { - return withContext(context -> retrieveWithResponse(retrievalRequest, xMsQuerySourceAuthorization, context)); - } - - Mono> retrieveWithResponse(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization, Context context) { - try { - return retrievals.retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, null, context) - .onErrorMap(MappingUtils::exceptionMapper); - } catch (RuntimeException e) { - return monoError(LOGGER, e); - } - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseClient.java deleted file mode 100644 index 1daaf7da1db5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseClient.java +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.knowledgebases; - -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.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.knowledgebases.implementation.KnowledgeBaseRetrievalClientImpl; -import com.azure.search.documents.knowledgebases.implementation.KnowledgeRetrievalsImpl; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; - -/** - * This class provides a client that contains the operations for retrieving knowledge from an Azure AI Search agent. - * - *

Overview

- *

- * The {@code SearchKnowledgeBaseClient} provides a synchronous API for interacting with Azure AI Search knowledge knowledgebases. This client enables you to send retrieval requests to a knowledge agent, which can aggregate and return relevant data from various backing stores configured in your Azure AI Search instance. - *

- * - *

- * The client is designed to be instantiated via the {@link SearchKnowledgeBaseClientBuilder}, which allows for fluent configuration of credentials, endpoints, agent names, and other client options. Once built, the client exposes methods to perform retrieval operations, returning structured responses that include the agent's results and any associated metadata. - *

- * - *

Getting Started

- *

- * To get started, configure and build an instance of this client using the {@link SearchKnowledgeBaseClientBuilder}. Authentication can be performed using either an API key or Azure Active Directory credentials, and the builder allows you to specify the agent name, endpoint, and API version as required by your scenario. - *

- * - *

Thread Safety

- *

- * This client is thread-safe and intended to be shared across threads and reused for multiple requests. - *

- * - *

Additional Information

- *

- * For more information about Azure AI Search knowledge knowledgebases, see the Azure documentation. For advanced scenarios, such as customizing the HTTP pipeline or integrating with other Azure SDK components, refer to the Azure SDK for Java design guidelines and the documentation for {@link SearchKnowledgeBaseClientBuilder}. - *

- * - * @see SearchKnowledgeBaseClientBuilder - * @see SearchKnowledgeBaseAsyncClient - */ -@ServiceClient(builder = SearchKnowledgeBaseClientBuilder.class) -public final class SearchKnowledgeBaseClient { - private static final ClientLogger LOGGER = new ClientLogger(SearchKnowledgeBaseClient.class); - - private final String endpoint; - private final String agentName; - private final SearchServiceVersion serviceVersion; - private final HttpPipeline httpPipeline; - private final KnowledgeBaseRetrievalClientImpl impl; - private final KnowledgeRetrievalsImpl retrievals; - - /** - * Package-private constructor to be used by {@link SearchKnowledgeBaseClientBuilder}. - */ - SearchKnowledgeBaseClient(String endpoint, String agentName, SearchServiceVersion serviceVersion, - HttpPipeline httpPipeline) { - this.endpoint = endpoint; - this.agentName = agentName; - this.serviceVersion = serviceVersion; - this.httpPipeline = httpPipeline; - this.impl - = new KnowledgeBaseRetrievalClientImpl(httpPipeline, endpoint, agentName, serviceVersion.getVersion()); - this.retrievals = impl.getKnowledgeRetrievals(); - } - - /** - * Gets the endpoint for the Azure AI Search service. - * - * @return the endpoint value. - */ - public String getEndpoint() { - return this.endpoint; - } - - /** - * Gets the agent name. - * - * @return the agentName value. - */ - public String getAgentName() { - return this.agentName; - } - - /** - * Gets the API version. - * - * @return the apiVersion value. - */ - public SearchServiceVersion getServiceVersion() { - return this.serviceVersion; - } - - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return the pipeline. - */ - public HttpPipeline getHttpPipeline() { - return this.httpPipeline; - } - - /** - * Retrieves relevant data from backing stores synchronously. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. - * @return the output contract for the retrieval response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBaseRetrievalResponse retrieve(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization) { - return retrievals.retrieve(retrievalRequest, xMsQuerySourceAuthorization, null); - } - - /** - * Retrieves relevant data from backing stores synchronously, with a full HTTP response. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. - * @param context The context to associate with this operation. - * @return the output contract for the retrieval response along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response retrieveWithResponse(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization, Context context) { - return retrievals.retrieveWithResponse(retrievalRequest, xMsQuerySourceAuthorization, null, context); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseClientBuilder.java deleted file mode 100644 index 0a6758966b6e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/SearchKnowledgeBaseClientBuilder.java +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -package com.azure.search.documents.knowledgebases; - -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.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.logging.ClientLogger; -import com.azure.core.util.serializer.JsonSerializer; -import com.azure.search.documents.SearchServiceVersion; -import com.azure.search.documents.implementation.util.Utility; -import com.azure.search.documents.models.SearchAudience; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * This class provides a fluent builder API to help configure and instantiate {@link SearchKnowledgeBaseClient} - * and {@link SearchKnowledgeBaseAsyncClient} for interacting with Azure AI Search Knowledge Agents. - * - *

Overview

- *

- * This builder enables the creation of both synchronous and asynchronous clients for Azure AI Search Knowledge Agents, - * allowing you to interact with knowledge retrieval and knowledgeBase-based search capabilities. The builder supports configuration - * of authentication, endpoint, knowledgeBase name, API version, and HTTP pipeline options, following Azure SDK for Java standards. - *

- * - *

Getting Started

- *

- * To create a client, configure the required properties such as the service endpoint, knowledgeBase name, API version, and authentication - * credentials. The builder supports both API key and Microsoft Entra ID (role-based) authentication. Additional options such as - * custom HTTP pipeline policies, retry options, logging, and serialization can also be configured. - *

- * - *

Authentication

- *

- * Azure AI Search Knowledge Agents support authentication using either an {@link AzureKeyCredential} (API key) or a - * {@link TokenCredential} (Microsoft Entra ID). When using Microsoft Entra ID, you may also specify a {@link SearchAudience} - * to target a specific Azure cloud environment. - *

- * - *

Client Instantiation

- *

- * Use {@link #buildClient()} to create a synchronous {@link SearchKnowledgeBaseClient}, or {@link #buildAsyncClient()} to create - * an asynchronous {@link SearchKnowledgeBaseAsyncClient}. Each call to these methods returns a new client instance with the - * configured options. - *

- * - *

Thread Safety

- *

- * Client instances created by this builder are thread-safe and intended to be shared and reused across threads. The builder itself - * is not thread-safe and should not be used concurrently from multiple threads. - *

- * - *

Additional Information

- *
    - *
  • For more information about Azure AI Search Knowledge Agents, see the Azure documentation.
  • - *
  • For authentication details, see the Azure AI Search security documentation.
  • - *
  • For Azure SDK for Java guidelines, see the Azure SDK for Java Introduction.
  • - *
- * - * @see SearchKnowledgeBaseClient - * @see SearchKnowledgeBaseAsyncClient - * @see com.azure.search.documents.knowledgebases - */ -@ServiceClientBuilder(serviceClients = { SearchKnowledgeBaseClient.class, SearchKnowledgeBaseAsyncClient.class }) -public final class SearchKnowledgeBaseClientBuilder - implements AzureKeyCredentialTrait, - ConfigurationTrait, EndpointTrait, - HttpTrait, TokenCredentialTrait { - - private static final ClientLogger LOGGER = new ClientLogger(SearchKnowledgeBaseClientBuilder.class); - - private final List perCallPolicies = new ArrayList<>(); - private final List perRetryPolicies = new ArrayList<>(); - - private AzureKeyCredential azureKeyCredential; - private TokenCredential tokenCredential; - private SearchAudience audience; - private String endpoint; - private String knowledgeBaseName; - private SearchServiceVersion serviceVersion; - 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 new builder instance. - */ - public SearchKnowledgeBaseClientBuilder() { - } - - /** - * Sets the service endpoint for the Azure AI Search instance. - * - * @param endpoint The URL of the Azure AI Search instance. - * @return The updated builder object. - */ - @Override - public SearchKnowledgeBaseClientBuilder endpoint(String endpoint) { - this.endpoint = endpoint; - return this; - } - - /** - * Sets the knowledgeBase name for the Azure AI Search knowledgeBase. - * - * @param knowledgeBaseName The name of the knowledgeBase. - * @return The updated builder object. - */ - public SearchKnowledgeBaseClientBuilder knowledgeBaseName(String knowledgeBaseName) { - this.knowledgeBaseName = knowledgeBaseName; - return this; - } - - /** - * Sets the API version to use for requests. - * - * @param apiVersion The API version. - * @return The updated builder object. - */ - public SearchKnowledgeBaseClientBuilder serviceVersion(SearchServiceVersion apiVersion) { - this.serviceVersion = apiVersion; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder credential(AzureKeyCredential credential) { - this.azureKeyCredential = credential; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder credential(TokenCredential credential) { - this.tokenCredential = credential; - return this; - } - - /** - * Sets the audience for the Azure AI Search instance. - * - * @param audience The audience to use. - * @return The updated builder object. - */ - public SearchKnowledgeBaseClientBuilder audience(SearchAudience audience) { - this.audience = audience; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder httpLogOptions(HttpLogOptions logOptions) { - this.httpLogOptions = logOptions; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder clientOptions(ClientOptions clientOptions) { - this.clientOptions = clientOptions; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder addPolicy(HttpPipelinePolicy policy) { - Objects.requireNonNull(policy, "'policy' cannot be null."); - this.perCallPolicies.add(policy); // For simplicity, treat as per-call; refine as needed - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder httpClient(HttpClient client) { - this.httpClient = client; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder pipeline(HttpPipeline httpPipeline) { - this.httpPipeline = httpPipeline; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder configuration(Configuration configuration) { - this.configuration = configuration; - return this; - } - - @Override - public SearchKnowledgeBaseClientBuilder retryOptions(RetryOptions retryOptions) { - this.retryOptions = retryOptions; - return this; - } - - /** - * Builds a synchronous {@link SearchKnowledgeBaseClient}. - * - * @return a new {@link SearchKnowledgeBaseClient} instance. - */ - public SearchKnowledgeBaseClient buildClient() { - validateRequiredFields(); - SearchServiceVersion serviceVersion - = this.serviceVersion != null ? this.serviceVersion : SearchServiceVersion.getLatest(); - HttpPipeline pipeline = this.httpPipeline != null - ? this.httpPipeline - : Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - return new SearchKnowledgeBaseClient(endpoint, knowledgeBaseName, serviceVersion, pipeline); - } - - /** - * Builds an asynchronous {@link SearchKnowledgeBaseAsyncClient}. - * - * @return a new {@link SearchKnowledgeBaseAsyncClient} instance. - */ - public SearchKnowledgeBaseAsyncClient buildAsyncClient() { - validateRequiredFields(); - SearchServiceVersion serviceVersion - = this.serviceVersion != null ? this.serviceVersion : SearchServiceVersion.getLatest(); - HttpPipeline pipeline = this.httpPipeline != null - ? this.httpPipeline - : Utility.buildHttpPipeline(clientOptions, httpLogOptions, configuration, retryPolicy, retryOptions, - azureKeyCredential, tokenCredential, audience, perCallPolicies, perRetryPolicies, httpClient, LOGGER); - return new SearchKnowledgeBaseAsyncClient(endpoint, knowledgeBaseName, serviceVersion, pipeline); - } - - private void validateRequiredFields() { - Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); - Objects.requireNonNull(knowledgeBaseName, "'knowledgeBaseName' cannot be null."); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/KnowledgeBaseRetrievalClientImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/KnowledgeBaseRetrievalClientImpl.java deleted file mode 100644 index eff69f8fd5f8..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/KnowledgeBaseRetrievalClientImpl.java +++ /dev/null @@ -1,147 +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.knowledgebases.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 KnowledgeBaseRetrievalClient type. - */ -public final class KnowledgeBaseRetrievalClientImpl { - /** - * 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 knowledge base. - */ - private final String knowledgeBaseName; - - /** - * Gets The name of the knowledge base. - * - * @return the knowledgeBaseName value. - */ - public String getKnowledgeBaseName() { - return this.knowledgeBaseName; - } - - /** - * 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 KnowledgeRetrievalsImpl object to access its operations. - */ - private final KnowledgeRetrievalsImpl knowledgeRetrievals; - - /** - * Gets the KnowledgeRetrievalsImpl object to access its operations. - * - * @return the KnowledgeRetrievalsImpl object. - */ - public KnowledgeRetrievalsImpl getKnowledgeRetrievals() { - return this.knowledgeRetrievals; - } - - /** - * Initializes an instance of KnowledgeBaseRetrievalClient client. - * - * @param endpoint The endpoint URL of the search service. - * @param knowledgeBaseName The name of the knowledge base. - * @param apiVersion Api Version. - */ - public KnowledgeBaseRetrievalClientImpl(String endpoint, String knowledgeBaseName, String apiVersion) { - this(new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy()).build(), - JacksonAdapter.createDefaultSerializerAdapter(), endpoint, knowledgeBaseName, apiVersion); - } - - /** - * Initializes an instance of KnowledgeBaseRetrievalClient client. - * - * @param httpPipeline The HTTP pipeline to send requests through. - * @param endpoint The endpoint URL of the search service. - * @param knowledgeBaseName The name of the knowledge base. - * @param apiVersion Api Version. - */ - public KnowledgeBaseRetrievalClientImpl(HttpPipeline httpPipeline, String endpoint, String knowledgeBaseName, - String apiVersion) { - this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, knowledgeBaseName, apiVersion); - } - - /** - * Initializes an instance of KnowledgeBaseRetrievalClient 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 knowledgeBaseName The name of the knowledge base. - * @param apiVersion Api Version. - */ - public KnowledgeBaseRetrievalClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdapter, - String endpoint, String knowledgeBaseName, String apiVersion) { - this.httpPipeline = httpPipeline; - this.serializerAdapter = serializerAdapter; - this.endpoint = endpoint; - this.knowledgeBaseName = knowledgeBaseName; - this.apiVersion = apiVersion; - this.knowledgeRetrievals = new KnowledgeRetrievalsImpl(this); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/KnowledgeRetrievalsImpl.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/KnowledgeRetrievalsImpl.java deleted file mode 100644 index 90adff5467f1..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/KnowledgeRetrievalsImpl.java +++ /dev/null @@ -1,218 +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.knowledgebases.implementation; - -import com.azure.core.annotation.BodyParam; -import com.azure.core.annotation.ExpectedResponses; -import com.azure.core.annotation.HeaderParam; -import com.azure.core.annotation.Host; -import com.azure.core.annotation.HostParam; -import com.azure.core.annotation.Post; -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.knowledgebases.implementation.models.ErrorResponseException; -import com.azure.search.documents.knowledgebases.implementation.models.RequestOptions; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; -import java.util.UUID; -import reactor.core.publisher.Mono; - -/** - * An instance of this class provides access to all the operations defined in KnowledgeRetrievals. - */ -public final class KnowledgeRetrievalsImpl { - /** - * The proxy service used to perform REST calls. - */ - private final KnowledgeRetrievalsService service; - - /** - * The service client containing this operation class. - */ - private final KnowledgeBaseRetrievalClientImpl client; - - /** - * Initializes an instance of KnowledgeRetrievalsImpl. - * - * @param client the instance of the service client containing this operation class. - */ - KnowledgeRetrievalsImpl(KnowledgeBaseRetrievalClientImpl client) { - this.service = RestProxy.create(KnowledgeRetrievalsService.class, client.getHttpPipeline(), - client.getSerializerAdapter()); - this.client = client; - } - - /** - * The interface defining all the services for KnowledgeBaseRetrievalClientKnowledgeRetrievals to be used by the - * proxy service to perform REST calls. - */ - @Host("{endpoint}/knowledgebases('{knowledgeBaseName}')") - @ServiceInterface(name = "KnowledgeBaseRetrievalClientKnowledgeRetrievals") - public interface KnowledgeRetrievalsService { - @Post("/retrieve") - @ExpectedResponses({ 200, 206 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Mono> retrieve(@HostParam("endpoint") String endpoint, - @HostParam("knowledgeBaseName") String knowledgeBaseName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") KnowledgeBaseRetrievalRequest retrievalRequest, Context context); - - @Post("/retrieve") - @ExpectedResponses({ 200, 206 }) - @UnexpectedResponseExceptionType(ErrorResponseException.class) - Response retrieveSync(@HostParam("endpoint") String endpoint, - @HostParam("knowledgeBaseName") String knowledgeBaseName, - @HeaderParam("x-ms-client-request-id") UUID xMsClientRequestId, - @QueryParam("api-version") String apiVersion, - @HeaderParam("x-ms-query-source-authorization") String xMsQuerySourceAuthorization, - @HeaderParam("Accept") String accept, - @BodyParam("application/json") KnowledgeBaseRetrievalRequest retrievalRequest, Context context); - } - - /** - * KnowledgeBase retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @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 output contract for the retrieval response along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> retrieveWithResponseAsync( - KnowledgeBaseRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, - RequestOptions requestOptions) { - return FluxUtil.withContext(context -> retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, - requestOptions, context)); - } - - /** - * KnowledgeBase retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @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 output contract for the retrieval response along with {@link Response} on successful completion of - * {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono> retrieveWithResponseAsync( - KnowledgeBaseRetrievalRequest retrievalRequest, String xMsQuerySourceAuthorization, - 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.retrieve(this.client.getEndpoint(), this.client.getKnowledgeBaseName(), xMsClientRequestId, - this.client.getApiVersion(), xMsQuerySourceAuthorization, accept, retrievalRequest, context); - } - - /** - * KnowledgeBase retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @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 output contract for the retrieval response on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono retrieveAsync(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization, RequestOptions requestOptions) { - return retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, requestOptions) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * KnowledgeBase retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @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 output contract for the retrieval response on successful completion of {@link Mono}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Mono retrieveAsync(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization, RequestOptions requestOptions, Context context) { - return retrieveWithResponseAsync(retrievalRequest, xMsQuerySourceAuthorization, requestOptions, context) - .flatMap(res -> Mono.justOrEmpty(res.getValue())); - } - - /** - * KnowledgeBase retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @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 output contract for the retrieval response along with {@link Response}. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public Response retrieveWithResponse(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization, 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.retrieveSync(this.client.getEndpoint(), this.client.getKnowledgeBaseName(), xMsClientRequestId, - this.client.getApiVersion(), xMsQuerySourceAuthorization, accept, retrievalRequest, context); - } - - /** - * KnowledgeBase retrieves relevant data from backing stores. - * - * @param retrievalRequest The retrieval request to process. - * @param xMsQuerySourceAuthorization Token identifying the user for which the query is being executed. This token - * is used to enforce security restrictions on documents. - * @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 output contract for the retrieval response. - */ - @ServiceMethod(returns = ReturnType.SINGLE) - public KnowledgeBaseRetrievalResponse retrieve(KnowledgeBaseRetrievalRequest retrievalRequest, - String xMsQuerySourceAuthorization, RequestOptions requestOptions) { - return retrieveWithResponse(retrievalRequest, xMsQuerySourceAuthorization, requestOptions, Context.NONE) - .getValue(); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorAdditionalInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorAdditionalInfo.java deleted file mode 100644 index 4808a92dd411..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorAdditionalInfo.java +++ /dev/null @@ -1,99 +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.knowledgebases.implementation.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; - -/** - * The resource management error additional info. - */ -@Immutable -public final class ErrorAdditionalInfo implements JsonSerializable { - /* - * The additional info type. - */ - @Generated - private String type; - - /* - * The additional info. - */ - @Generated - private Object info; - - /** - * Creates an instance of ErrorAdditionalInfo class. - */ - @Generated - public ErrorAdditionalInfo() { - } - - /** - * Get the type property: The additional info type. - * - * @return the type value. - */ - @Generated - public String getType() { - return this.type; - } - - /** - * Get the info property: The additional info. - * - * @return the info value. - */ - @Generated - public Object getInfo() { - return this.info; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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/knowledgebases/implementation/models/ErrorDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorDetail.java deleted file mode 100644 index 5f75ab869444..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorDetail.java +++ /dev/null @@ -1,157 +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.knowledgebases.implementation.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.List; - -/** - * The error detail. - */ -@Immutable -public final class ErrorDetail implements JsonSerializable { - /* - * The error code. - */ - @Generated - private String code; - - /* - * The error message. - */ - @Generated - private String message; - - /* - * The error target. - */ - @Generated - private String target; - - /* - * The error details. - */ - @Generated - private List details; - - /* - * The error additional info. - */ - @Generated - private List additionalInfo; - - /** - * Creates an instance of ErrorDetail class. - */ - @Generated - public ErrorDetail() { - } - - /** - * Get the code property: The error code. - * - * @return the code value. - */ - @Generated - public String getCode() { - return this.code; - } - - /** - * Get the message property: The error message. - * - * @return the message value. - */ - @Generated - public String getMessage() { - return this.message; - } - - /** - * Get the target property: The error target. - * - * @return the target value. - */ - @Generated - public String getTarget() { - return this.target; - } - - /** - * Get the details property: The error details. - * - * @return the details value. - */ - @Generated - public List getDetails() { - return this.details; - } - - /** - * Get the additionalInfo property: The error additional info. - * - * @return the additionalInfo value. - */ - @Generated - public List getAdditionalInfo() { - return this.additionalInfo; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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/knowledgebases/implementation/models/ErrorResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorResponse.java deleted file mode 100644 index f7636483521c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorResponse.java +++ /dev/null @@ -1,97 +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.knowledgebases.implementation.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; - -/** - * 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. - */ - @Generated - private ErrorDetail error; - - /** - * Creates an instance of ErrorResponse class. - */ - @Generated - public ErrorResponse() { - } - - /** - * Get the error property: The error object. - * - * @return the error value. - */ - @Generated - 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. - */ - @Generated - public ErrorResponse setError(ErrorDetail error) { - this.error = error; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @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. - */ - @Generated - 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/knowledgebases/implementation/models/ErrorResponseException.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/ErrorResponseException.java deleted file mode 100644 index 893cc0749731..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/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.knowledgebases.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/knowledgebases/implementation/models/RequestOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/RequestOptions.java deleted file mode 100644 index 604c6bc78b71..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/RequestOptions.java +++ /dev/null @@ -1,52 +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.knowledgebases.implementation.models; - -import com.azure.core.annotation.Fluent; -import com.azure.core.annotation.Generated; -import java.util.UUID; - -/** - * Parameter group. - */ -@Fluent -public final class RequestOptions { - /* - * The tracking ID sent with the request to help with debugging. - */ - @Generated - private UUID xMsClientRequestId; - - /** - * Creates an instance of RequestOptions class. - */ - @Generated - public RequestOptions() { - } - - /** - * Get the xMsClientRequestId property: The tracking ID sent with the request to help with debugging. - * - * @return the xMsClientRequestId value. - */ - @Generated - 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. - */ - @Generated - 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/knowledgebases/implementation/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/models/package-info.java deleted file mode 100644 index e1f874071435..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/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 KnowledgeBaseRetrievalClient. - * Client that can be used to query an knowledge base. - */ -package com.azure.search.documents.knowledgebases.implementation.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/package-info.java deleted file mode 100644 index 0e3d46cf2887..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/implementation/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 implementations for KnowledgeBaseRetrievalClient. - * Client that can be used to query an knowledge base. - */ -package com.azure.search.documents.knowledgebases.implementation; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServices.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AIServices.java similarity index 81% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServices.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AIServices.java index 67fdc7439436..28821be76622 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/AIServices.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AIServices.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.knowledgebases.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -15,10 +12,11 @@ import java.io.IOException; /** - * Parameters for Azure Blob Storage knowledge source. + * Parameters for AI Services. */ @Fluent public final class AIServices implements JsonSerializable { + /* * The URI of the AI Services endpoint. */ @@ -33,7 +31,7 @@ public final class AIServices implements JsonSerializable { /** * Creates an instance of AIServices class. - * + * * @param uri the uri value to set. */ @Generated @@ -43,7 +41,7 @@ public AIServices(String uri) { /** * Get the uri property: The URI of the AI Services endpoint. - * + * * @return the uri value. */ @Generated @@ -53,7 +51,7 @@ public String getUri() { /** * Get the apiKey property: The API key for accessing AI Services. - * + * * @return the apiKey value. */ @Generated @@ -63,7 +61,7 @@ public String getApiKey() { /** * Set the apiKey property: The API key for accessing AI Services. - * + * * @param apiKey the apiKey value to set. * @return the AIServices object itself. */ @@ -87,7 +85,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AIServices from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AIServices if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. @@ -97,29 +95,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static AIServices fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean uriFound = false; String uri = null; String apiKey = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("uri".equals(fieldName)) { uri = reader.getString(); - uriFound = true; } else if ("apiKey".equals(fieldName)) { apiKey = reader.getString(); } else { reader.skipChildren(); } } - if (uriFound) { - AIServices deserializedAIServices = new AIServices(uri); - deserializedAIServices.apiKey = apiKey; - - return deserializedAIServices; - } - throw new IllegalStateException("Missing required property: uri"); + AIServices deserializedAIServices = new AIServices(uri); + deserializedAIServices.apiKey = apiKey; + return deserializedAIServices; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AzureBlobKnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AzureBlobKnowledgeSourceParams.java index 1496f70914fa..f13b5941d71d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AzureBlobKnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/AzureBlobKnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -11,6 +8,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** @@ -18,6 +16,7 @@ */ @Fluent public final class AzureBlobKnowledgeSourceParams extends KnowledgeSourceParams { + /* * The type of the knowledge source. */ @@ -26,7 +25,7 @@ public final class AzureBlobKnowledgeSourceParams extends KnowledgeSourceParams /** * Creates an instance of AzureBlobKnowledgeSourceParams class. - * + * * @param knowledgeSourceName the knowledgeSourceName value to set. */ @Generated @@ -36,7 +35,7 @@ public AzureBlobKnowledgeSourceParams(String knowledgeSourceName) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -103,7 +102,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AzureBlobKnowledgeSourceParams from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AzureBlobKnowledgeSourceParams if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -113,7 +112,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static AzureBlobKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; Boolean includeReferences = null; Boolean includeReferenceSourceData = null; @@ -123,10 +121,8 @@ public static AzureBlobKnowledgeSourceParams fromJson(JsonReader jsonReader) thr while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("includeReferences".equals(fieldName)) { includeReferences = reader.getNullable(JsonReader::getBoolean); } else if ("includeReferenceSourceData".equals(fieldName)) { @@ -141,18 +137,14 @@ public static AzureBlobKnowledgeSourceParams fromJson(JsonReader jsonReader) thr reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - AzureBlobKnowledgeSourceParams deserializedAzureBlobKnowledgeSourceParams - = new AzureBlobKnowledgeSourceParams(knowledgeSourceName); - deserializedAzureBlobKnowledgeSourceParams.setIncludeReferences(includeReferences); - deserializedAzureBlobKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); - deserializedAzureBlobKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); - deserializedAzureBlobKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); - deserializedAzureBlobKnowledgeSourceParams.kind = kind; - - return deserializedAzureBlobKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + AzureBlobKnowledgeSourceParams deserializedAzureBlobKnowledgeSourceParams + = new AzureBlobKnowledgeSourceParams(knowledgeSourceName); + deserializedAzureBlobKnowledgeSourceParams.setIncludeReferences(includeReferences); + deserializedAzureBlobKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); + deserializedAzureBlobKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); + deserializedAzureBlobKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); + deserializedAzureBlobKnowledgeSourceParams.kind = kind; + return deserializedAzureBlobKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CompletedSynchronizationState.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/CompletedSynchronizationState.java similarity index 76% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CompletedSynchronizationState.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/CompletedSynchronizationState.java index 9d8a000cdaf1..c53509143c7f 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/CompletedSynchronizationState.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/CompletedSynchronizationState.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.knowledgebases.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -16,14 +13,13 @@ import java.io.IOException; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; /** * Represents the completed state of the last synchronization. */ @Immutable public final class CompletedSynchronizationState implements JsonSerializable { + /* * The start time of the last completed synchronization. */ @@ -56,7 +52,7 @@ public final class CompletedSynchronizationState implements JsonSerializable { - boolean startTimeFound = false; OffsetDateTime startTime = null; - boolean endTimeFound = false; OffsetDateTime endTime = null; - boolean itemsUpdatesProcessedFound = false; int itemsUpdatesProcessed = 0; - boolean itemsUpdatesFailedFound = false; int itemsUpdatesFailed = 0; - boolean itemsSkippedFound = false; int itemsSkipped = 0; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("startTime".equals(fieldName)) { startTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - startTimeFound = true; } else if ("endTime".equals(fieldName)) { endTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - endTimeFound = true; } else if ("itemsUpdatesProcessed".equals(fieldName)) { itemsUpdatesProcessed = reader.getInt(); - itemsUpdatesProcessedFound = true; } else if ("itemsUpdatesFailed".equals(fieldName)) { itemsUpdatesFailed = reader.getInt(); - itemsUpdatesFailedFound = true; } else if ("itemsSkipped".equals(fieldName)) { itemsSkipped = reader.getInt(); - itemsSkippedFound = true; } else { reader.skipChildren(); } } - if (startTimeFound - && endTimeFound - && itemsUpdatesProcessedFound - && itemsUpdatesFailedFound - && itemsSkippedFound) { - return new CompletedSynchronizationState(startTime, endTime, itemsUpdatesProcessed, itemsUpdatesFailed, - itemsSkipped); - } - List missingProperties = new ArrayList<>(); - if (!startTimeFound) { - missingProperties.add("startTime"); - } - if (!endTimeFound) { - missingProperties.add("endTime"); - } - if (!itemsUpdatesProcessedFound) { - missingProperties.add("itemsUpdatesProcessed"); - } - if (!itemsUpdatesFailedFound) { - missingProperties.add("itemsUpdatesFailed"); - } - if (!itemsSkippedFound) { - missingProperties.add("itemsSkipped"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new CompletedSynchronizationState(startTime, endTime, itemsUpdatesProcessed, itemsUpdatesFailed, + itemsSkipped); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedOneLakeKnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedOneLakeKnowledgeSourceParams.java index a2a43f2132bb..526450d5a24a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedOneLakeKnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedOneLakeKnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -11,6 +8,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** @@ -18,6 +16,7 @@ */ @Fluent public final class IndexedOneLakeKnowledgeSourceParams extends KnowledgeSourceParams { + /* * The type of the knowledge source. */ @@ -26,7 +25,7 @@ public final class IndexedOneLakeKnowledgeSourceParams extends KnowledgeSourcePa /** * Creates an instance of IndexedOneLakeKnowledgeSourceParams class. - * + * * @param knowledgeSourceName the knowledgeSourceName value to set. */ @Generated @@ -36,7 +35,7 @@ public IndexedOneLakeKnowledgeSourceParams(String knowledgeSourceName) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -103,7 +102,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexedOneLakeKnowledgeSourceParams from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexedOneLakeKnowledgeSourceParams if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -113,7 +112,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexedOneLakeKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; Boolean includeReferences = null; Boolean includeReferenceSourceData = null; @@ -123,10 +121,8 @@ public static IndexedOneLakeKnowledgeSourceParams fromJson(JsonReader jsonReader while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("includeReferences".equals(fieldName)) { includeReferences = reader.getNullable(JsonReader::getBoolean); } else if ("includeReferenceSourceData".equals(fieldName)) { @@ -141,19 +137,14 @@ public static IndexedOneLakeKnowledgeSourceParams fromJson(JsonReader jsonReader reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - IndexedOneLakeKnowledgeSourceParams deserializedIndexedOneLakeKnowledgeSourceParams - = new IndexedOneLakeKnowledgeSourceParams(knowledgeSourceName); - deserializedIndexedOneLakeKnowledgeSourceParams.setIncludeReferences(includeReferences); - deserializedIndexedOneLakeKnowledgeSourceParams - .setIncludeReferenceSourceData(includeReferenceSourceData); - deserializedIndexedOneLakeKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); - deserializedIndexedOneLakeKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); - deserializedIndexedOneLakeKnowledgeSourceParams.kind = kind; - - return deserializedIndexedOneLakeKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + IndexedOneLakeKnowledgeSourceParams deserializedIndexedOneLakeKnowledgeSourceParams + = new IndexedOneLakeKnowledgeSourceParams(knowledgeSourceName); + deserializedIndexedOneLakeKnowledgeSourceParams.setIncludeReferences(includeReferences); + deserializedIndexedOneLakeKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); + deserializedIndexedOneLakeKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); + deserializedIndexedOneLakeKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); + deserializedIndexedOneLakeKnowledgeSourceParams.kind = kind; + return deserializedIndexedOneLakeKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedSharePointKnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedSharePointKnowledgeSourceParams.java index 2c016c0338db..4b36e1b8f917 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedSharePointKnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/IndexedSharePointKnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -11,6 +8,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** @@ -18,6 +16,7 @@ */ @Fluent public final class IndexedSharePointKnowledgeSourceParams extends KnowledgeSourceParams { + /* * The type of the knowledge source. */ @@ -26,7 +25,7 @@ public final class IndexedSharePointKnowledgeSourceParams extends KnowledgeSourc /** * Creates an instance of IndexedSharePointKnowledgeSourceParams class. - * + * * @param knowledgeSourceName the knowledgeSourceName value to set. */ @Generated @@ -36,7 +35,7 @@ public IndexedSharePointKnowledgeSourceParams(String knowledgeSourceName) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -103,7 +102,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexedSharePointKnowledgeSourceParams from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexedSharePointKnowledgeSourceParams if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -113,7 +112,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexedSharePointKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; Boolean includeReferences = null; Boolean includeReferenceSourceData = null; @@ -123,10 +121,8 @@ public static IndexedSharePointKnowledgeSourceParams fromJson(JsonReader jsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("includeReferences".equals(fieldName)) { includeReferences = reader.getNullable(JsonReader::getBoolean); } else if ("includeReferenceSourceData".equals(fieldName)) { @@ -141,19 +137,15 @@ public static IndexedSharePointKnowledgeSourceParams fromJson(JsonReader jsonRea reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - IndexedSharePointKnowledgeSourceParams deserializedIndexedSharePointKnowledgeSourceParams - = new IndexedSharePointKnowledgeSourceParams(knowledgeSourceName); - deserializedIndexedSharePointKnowledgeSourceParams.setIncludeReferences(includeReferences); - deserializedIndexedSharePointKnowledgeSourceParams - .setIncludeReferenceSourceData(includeReferenceSourceData); - deserializedIndexedSharePointKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); - deserializedIndexedSharePointKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); - deserializedIndexedSharePointKnowledgeSourceParams.kind = kind; - - return deserializedIndexedSharePointKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + IndexedSharePointKnowledgeSourceParams deserializedIndexedSharePointKnowledgeSourceParams + = new IndexedSharePointKnowledgeSourceParams(knowledgeSourceName); + deserializedIndexedSharePointKnowledgeSourceParams.setIncludeReferences(includeReferences); + deserializedIndexedSharePointKnowledgeSourceParams + .setIncludeReferenceSourceData(includeReferenceSourceData); + deserializedIndexedSharePointKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); + deserializedIndexedSharePointKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); + deserializedIndexedSharePointKnowledgeSourceParams.kind = kind; + return deserializedIndexedSharePointKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecord.java index ebc531019a1e..38cfe2d12d3e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecord.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecord.java @@ -1,13 +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.knowledgebases.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; @@ -15,15 +12,17 @@ import java.io.IOException; /** - * Base type for activity records. + * Base type for activity records. Tracks execution details, timing, and errors for knowledge base operations. */ -@Fluent +@Immutable public class KnowledgeBaseActivityRecord implements JsonSerializable { + /* * The type of the activity record. */ @Generated - private String type = "KnowledgeBaseActivityRecord"; + private KnowledgeBaseActivityRecordType type + = KnowledgeBaseActivityRecordType.fromString("KnowledgeBaseActivityRecord"); /* * The ID of the activity record. @@ -46,27 +45,27 @@ public class KnowledgeBaseActivityRecord implements JsonSerializable { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -160,21 +160,7 @@ public static KnowledgeBaseActivityRecord fromJson(JsonReader jsonReader) throws } } // Use the discriminator value to determine which subtype should be deserialized. - if ("KnowledgeBaseRetrievalActivityRecord".equals(discriminatorValue)) { - return KnowledgeBaseRetrievalActivityRecord.fromJsonKnownDiscriminator(readerToUse.reset()); - } else if ("searchIndex".equals(discriminatorValue)) { - return KnowledgeBaseSearchIndexActivityRecord.fromJson(readerToUse.reset()); - } else if ("azureBlob".equals(discriminatorValue)) { - return KnowledgeBaseAzureBlobActivityRecord.fromJson(readerToUse.reset()); - } else if ("indexedSharePoint".equals(discriminatorValue)) { - return KnowledgeBaseIndexedSharePointActivityRecord.fromJson(readerToUse.reset()); - } else if ("indexedOneLake".equals(discriminatorValue)) { - return KnowledgeBaseIndexedOneLakeActivityRecord.fromJson(readerToUse.reset()); - } else if ("web".equals(discriminatorValue)) { - return KnowledgeBaseWebActivityRecord.fromJson(readerToUse.reset()); - } else if ("remoteSharePoint".equals(discriminatorValue)) { - return KnowledgeBaseRemoteSharePointActivityRecord.fromJson(readerToUse.reset()); - } else if ("modelQueryPlanning".equals(discriminatorValue)) { + if ("modelQueryPlanning".equals(discriminatorValue)) { return KnowledgeBaseModelQueryPlanningActivityRecord.fromJson(readerToUse.reset()); } else if ("modelAnswerSynthesis".equals(discriminatorValue)) { return KnowledgeBaseModelAnswerSynthesisActivityRecord.fromJson(readerToUse.reset()); @@ -190,20 +176,17 @@ public static KnowledgeBaseActivityRecord fromJson(JsonReader jsonReader) throws @Generated static KnowledgeBaseActivityRecord fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; int id = 0; - String type = null; + KnowledgeBaseActivityRecordType type = null; Integer elapsedMs = null; KnowledgeBaseErrorDetail error = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getInt(); - idFound = true; } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseActivityRecordType.fromString(reader.getString()); } else if ("elapsedMs".equals(fieldName)) { elapsedMs = reader.getNullable(JsonReader::getInt); } else if ("error".equals(fieldName)) { @@ -212,16 +195,11 @@ static KnowledgeBaseActivityRecord fromJsonKnownDiscriminator(JsonReader jsonRea reader.skipChildren(); } } - if (idFound) { - KnowledgeBaseActivityRecord deserializedKnowledgeBaseActivityRecord - = new KnowledgeBaseActivityRecord(id); - deserializedKnowledgeBaseActivityRecord.type = type; - deserializedKnowledgeBaseActivityRecord.elapsedMs = elapsedMs; - deserializedKnowledgeBaseActivityRecord.error = error; - - return deserializedKnowledgeBaseActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); + KnowledgeBaseActivityRecord deserializedKnowledgeBaseActivityRecord = new KnowledgeBaseActivityRecord(id); + deserializedKnowledgeBaseActivityRecord.type = type; + deserializedKnowledgeBaseActivityRecord.elapsedMs = elapsedMs; + deserializedKnowledgeBaseActivityRecord.error = error; + return deserializedKnowledgeBaseActivityRecord; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecordType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecordType.java new file mode 100644 index 000000000000..463bfa50f26e --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecordType.java @@ -0,0 +1,99 @@ +// 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.knowledgebases.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of activity record. + */ +public final class KnowledgeBaseActivityRecordType extends ExpandableStringEnum { + + /** + * Search index retrieval activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType SEARCH_INDEX = fromString("searchIndex"); + + /** + * Azure Blob retrieval activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType AZURE_BLOB = fromString("azureBlob"); + + /** + * Indexed SharePoint retrieval activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType INDEXED_SHARE_POINT = fromString("indexedSharePoint"); + + /** + * Indexed OneLake retrieval activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType INDEXED_ONE_LAKE = fromString("indexedOneLake"); + + /** + * Web retrieval activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType WEB = fromString("web"); + + /** + * Remote SharePoint retrieval activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType REMOTE_SHARE_POINT = fromString("remoteSharePoint"); + + /** + * LLM query planning activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType MODEL_QUERY_PLANNING = fromString("modelQueryPlanning"); + + /** + * LLM answer synthesis activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType MODEL_ANSWER_SYNTHESIS = fromString("modelAnswerSynthesis"); + + /** + * Agentic reasoning activity. + */ + @Generated + public static final KnowledgeBaseActivityRecordType AGENTIC_REASONING = fromString("agenticReasoning"); + + /** + * Creates a new instance of KnowledgeBaseActivityRecordType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public KnowledgeBaseActivityRecordType() { + } + + /** + * Creates or finds a KnowledgeBaseActivityRecordType from its string representation. + * + * @param name a name to look for. + * @return the corresponding KnowledgeBaseActivityRecordType. + */ + @Generated + public static KnowledgeBaseActivityRecordType fromString(String name) { + return fromString(name, KnowledgeBaseActivityRecordType.class); + } + + /** + * Gets known KnowledgeBaseActivityRecordType values. + * + * @return known KnowledgeBaseActivityRecordType values. + */ + @Generated + public static Collection values() { + return values(KnowledgeBaseActivityRecordType.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAgenticReasoningActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAgenticReasoningActivityRecord.java index c68136a17607..4715505d3e51 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAgenticReasoningActivityRecord.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAgenticReasoningActivityRecord.java @@ -1,13 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; @@ -16,13 +13,14 @@ /** * Represents an agentic reasoning activity record. */ -@Fluent +@Immutable public final class KnowledgeBaseAgenticReasoningActivityRecord extends KnowledgeBaseActivityRecord { + /* * The type of the activity record. */ @Generated - private String type = "agenticReasoning"; + private KnowledgeBaseActivityRecordType type = KnowledgeBaseActivityRecordType.AGENTIC_REASONING; /* * The number of input tokens for agentic reasoning. @@ -31,35 +29,35 @@ public final class KnowledgeBaseAgenticReasoningActivityRecord extends Knowledge private Integer reasoningTokens; /* - * The retrievalReasoningEffort property. + * The retrieval reasoning effort configuration. */ @Generated private KnowledgeRetrievalReasoningEffort retrievalReasoningEffort; /** * Creates an instance of KnowledgeBaseAgenticReasoningActivityRecord class. - * + * * @param id the id value to set. */ @Generated - public KnowledgeBaseAgenticReasoningActivityRecord(int id) { + private KnowledgeBaseAgenticReasoningActivityRecord(int id) { super(id); } /** * Get the type property: The type of the activity record. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseActivityRecordType getType() { return this.type; } /** * Get the reasoningTokens property: The number of input tokens for agentic reasoning. - * + * * @return the reasoningTokens value. */ @Generated @@ -68,20 +66,8 @@ public Integer getReasoningTokens() { } /** - * Set the reasoningTokens property: The number of input tokens for agentic reasoning. - * - * @param reasoningTokens the reasoningTokens value to set. - * @return the KnowledgeBaseAgenticReasoningActivityRecord object itself. - */ - @Generated - public KnowledgeBaseAgenticReasoningActivityRecord setReasoningTokens(Integer reasoningTokens) { - this.reasoningTokens = reasoningTokens; - return this; - } - - /** - * Get the retrievalReasoningEffort property: The retrievalReasoningEffort property. - * + * Get the retrievalReasoningEffort property: The retrieval reasoning effort configuration. + * * @return the retrievalReasoningEffort value. */ @Generated @@ -89,39 +75,6 @@ public KnowledgeRetrievalReasoningEffort getRetrievalReasoningEffort() { return this.retrievalReasoningEffort; } - /** - * Set the retrievalReasoningEffort property: The retrievalReasoningEffort property. - * - * @param retrievalReasoningEffort the retrievalReasoningEffort value to set. - * @return the KnowledgeBaseAgenticReasoningActivityRecord object itself. - */ - @Generated - public KnowledgeBaseAgenticReasoningActivityRecord - setRetrievalReasoningEffort(KnowledgeRetrievalReasoningEffort retrievalReasoningEffort) { - this.retrievalReasoningEffort = retrievalReasoningEffort; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAgenticReasoningActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAgenticReasoningActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - /** * {@inheritDoc} */ @@ -132,7 +85,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("id", getId()); jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeNumberField("reasoningTokens", this.reasoningTokens); jsonWriter.writeJsonField("retrievalReasoningEffort", this.retrievalReasoningEffort); return jsonWriter.writeEndObject(); @@ -140,7 +93,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseAgenticReasoningActivityRecord from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseAgenticReasoningActivityRecord if the JsonReader was pointing to an instance * of it, or null if it was pointing to JSON null. @@ -150,26 +103,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseAgenticReasoningActivityRecord fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; int id = 0; Integer elapsedMs = null; KnowledgeBaseErrorDetail error = null; - String type = "agenticReasoning"; + KnowledgeBaseActivityRecordType type = KnowledgeBaseActivityRecordType.AGENTIC_REASONING; Integer reasoningTokens = null; KnowledgeRetrievalReasoningEffort retrievalReasoningEffort = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getInt(); - idFound = true; } else if ("elapsedMs".equals(fieldName)) { elapsedMs = reader.getNullable(JsonReader::getInt); } else if ("error".equals(fieldName)) { error = KnowledgeBaseErrorDetail.fromJson(reader); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseActivityRecordType.fromString(reader.getString()); } else if ("reasoningTokens".equals(fieldName)) { reasoningTokens = reader.getNullable(JsonReader::getInt); } else if ("retrievalReasoningEffort".equals(fieldName)) { @@ -178,19 +128,14 @@ public static KnowledgeBaseAgenticReasoningActivityRecord fromJson(JsonReader js reader.skipChildren(); } } - if (idFound) { - KnowledgeBaseAgenticReasoningActivityRecord deserializedKnowledgeBaseAgenticReasoningActivityRecord - = new KnowledgeBaseAgenticReasoningActivityRecord(id); - deserializedKnowledgeBaseAgenticReasoningActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseAgenticReasoningActivityRecord.setError(error); - deserializedKnowledgeBaseAgenticReasoningActivityRecord.type = type; - deserializedKnowledgeBaseAgenticReasoningActivityRecord.reasoningTokens = reasoningTokens; - deserializedKnowledgeBaseAgenticReasoningActivityRecord.retrievalReasoningEffort - = retrievalReasoningEffort; - - return deserializedKnowledgeBaseAgenticReasoningActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); + KnowledgeBaseAgenticReasoningActivityRecord deserializedKnowledgeBaseAgenticReasoningActivityRecord + = new KnowledgeBaseAgenticReasoningActivityRecord(id); + deserializedKnowledgeBaseAgenticReasoningActivityRecord.setElapsedMs(elapsedMs); + deserializedKnowledgeBaseAgenticReasoningActivityRecord.setError(error); + deserializedKnowledgeBaseAgenticReasoningActivityRecord.type = type; + deserializedKnowledgeBaseAgenticReasoningActivityRecord.reasoningTokens = reasoningTokens; + deserializedKnowledgeBaseAgenticReasoningActivityRecord.retrievalReasoningEffort = retrievalReasoningEffort; + return deserializedKnowledgeBaseAgenticReasoningActivityRecord; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobActivityArguments.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobActivityArguments.java deleted file mode 100644 index 78b5ec562f7e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobActivityArguments.java +++ /dev/null @@ -1,96 +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.knowledgebases.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; - -/** - * Represents the arguments the azure blob retrieval activity was run with. - */ -@Fluent -public final class KnowledgeBaseAzureBlobActivityArguments - implements JsonSerializable { - /* - * The search string used to query blob contents. - */ - @Generated - private String search; - - /** - * Creates an instance of KnowledgeBaseAzureBlobActivityArguments class. - */ - @Generated - public KnowledgeBaseAzureBlobActivityArguments() { - } - - /** - * Get the search property: The search string used to query blob contents. - * - * @return the search value. - */ - @Generated - public String getSearch() { - return this.search; - } - - /** - * Set the search property: The search string used to query blob contents. - * - * @param search the search value to set. - * @return the KnowledgeBaseAzureBlobActivityArguments object itself. - */ - @Generated - public KnowledgeBaseAzureBlobActivityArguments setSearch(String search) { - this.search = search; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("search", this.search); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseAzureBlobActivityArguments from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseAzureBlobActivityArguments 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 KnowledgeBaseAzureBlobActivityArguments. - */ - @Generated - public static KnowledgeBaseAzureBlobActivityArguments fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeBaseAzureBlobActivityArguments deserializedKnowledgeBaseAzureBlobActivityArguments - = new KnowledgeBaseAzureBlobActivityArguments(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("search".equals(fieldName)) { - deserializedKnowledgeBaseAzureBlobActivityArguments.search = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeBaseAzureBlobActivityArguments; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobActivityRecord.java deleted file mode 100644 index 855af19e30c1..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobActivityRecord.java +++ /dev/null @@ -1,212 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a azure blob retrieval activity record. - */ -@Fluent -public final class KnowledgeBaseAzureBlobActivityRecord extends KnowledgeBaseRetrievalActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "azureBlob"; - - /* - * The azure blob arguments for the retrieval activity. - */ - @Generated - private KnowledgeBaseAzureBlobActivityArguments azureBlobArguments; - - /** - * Creates an instance of KnowledgeBaseAzureBlobActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseAzureBlobActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the azureBlobArguments property: The azure blob arguments for the retrieval activity. - * - * @return the azureBlobArguments value. - */ - @Generated - public KnowledgeBaseAzureBlobActivityArguments getAzureBlobArguments() { - return this.azureBlobArguments; - } - - /** - * Set the azureBlobArguments property: The azure blob arguments for the retrieval activity. - * - * @param azureBlobArguments the azureBlobArguments value to set. - * @return the KnowledgeBaseAzureBlobActivityRecord object itself. - */ - @Generated - public KnowledgeBaseAzureBlobActivityRecord - setAzureBlobArguments(KnowledgeBaseAzureBlobActivityArguments azureBlobArguments) { - this.azureBlobArguments = azureBlobArguments; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - super.setKnowledgeSourceName(knowledgeSourceName); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobActivityRecord setQueryTime(OffsetDateTime queryTime) { - super.setQueryTime(queryTime); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobActivityRecord setCount(Integer count) { - super.setCount(count); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("knowledgeSourceName", getKnowledgeSourceName()); - jsonWriter.writeStringField("queryTime", - getQueryTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getQueryTime())); - jsonWriter.writeNumberField("count", getCount()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("azureBlobArguments", this.azureBlobArguments); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseAzureBlobActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseAzureBlobActivityRecord 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 KnowledgeBaseAzureBlobActivityRecord. - */ - @Generated - public static KnowledgeBaseAzureBlobActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - String type = "azureBlob"; - KnowledgeBaseAzureBlobActivityArguments azureBlobArguments = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("azureBlobArguments".equals(fieldName)) { - azureBlobArguments = KnowledgeBaseAzureBlobActivityArguments.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseAzureBlobActivityRecord deserializedKnowledgeBaseAzureBlobActivityRecord - = new KnowledgeBaseAzureBlobActivityRecord(id); - deserializedKnowledgeBaseAzureBlobActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseAzureBlobActivityRecord.setError(error); - deserializedKnowledgeBaseAzureBlobActivityRecord.setKnowledgeSourceName(knowledgeSourceName); - deserializedKnowledgeBaseAzureBlobActivityRecord.setQueryTime(queryTime); - deserializedKnowledgeBaseAzureBlobActivityRecord.setCount(count); - deserializedKnowledgeBaseAzureBlobActivityRecord.type = type; - deserializedKnowledgeBaseAzureBlobActivityRecord.azureBlobArguments = azureBlobArguments; - - return deserializedKnowledgeBaseAzureBlobActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobReference.java index d4a686461454..638613da1991 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobReference.java @@ -1,31 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** * Represents an Azure Blob Storage document reference. */ -@Fluent +@Immutable public final class KnowledgeBaseAzureBlobReference extends KnowledgeBaseReference { + /* * The type of the reference. */ @Generated - private String type = "azureBlob"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.AZURE_BLOB; /* * The blob URL for the reference. @@ -35,29 +31,29 @@ public final class KnowledgeBaseAzureBlobReference extends KnowledgeBaseReferenc /** * Creates an instance of KnowledgeBaseAzureBlobReference class. - * + * * @param id the id value to set. * @param activitySource the activitySource value to set. */ @Generated - public KnowledgeBaseAzureBlobReference(String id, int activitySource) { + private KnowledgeBaseAzureBlobReference(String id, int activitySource) { super(id, activitySource); } /** * Get the type property: The type of the reference. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseReferenceType getType() { return this.type; } /** * Get the blobUrl property: The blob URL for the reference. - * + * * @return the blobUrl value. */ @Generated @@ -65,38 +61,6 @@ public String getBlobUrl() { return this.blobUrl; } - /** - * Set the blobUrl property: The blob URL for the reference. - * - * @param blobUrl the blobUrl value to set. - * @return the KnowledgeBaseAzureBlobReference object itself. - */ - @Generated - public KnowledgeBaseAzureBlobReference setBlobUrl(String blobUrl) { - this.blobUrl = blobUrl; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobReference setSourceData(Map sourceData) { - super.setSourceData(sourceData); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseAzureBlobReference setRerankerScore(Float rerankerScore) { - super.setRerankerScore(rerankerScore); - return this; - } - /** * {@inheritDoc} */ @@ -108,14 +72,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("activitySource", getActivitySource()); jsonWriter.writeMapField("sourceData", getSourceData(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", getRerankerScore()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("blobUrl", this.blobUrl); return jsonWriter.writeEndObject(); } /** * Reads an instance of KnowledgeBaseAzureBlobReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseAzureBlobReference if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -125,56 +89,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseAzureBlobReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; Map sourceData = null; Float rerankerScore = null; - String type = "azureBlob"; + KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.AZURE_BLOB; String blobUrl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getFloat); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("blobUrl".equals(fieldName)) { blobUrl = reader.getString(); } else { reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseAzureBlobReference deserializedKnowledgeBaseAzureBlobReference - = new KnowledgeBaseAzureBlobReference(id, activitySource); - deserializedKnowledgeBaseAzureBlobReference.setSourceData(sourceData); - deserializedKnowledgeBaseAzureBlobReference.setRerankerScore(rerankerScore); - deserializedKnowledgeBaseAzureBlobReference.type = type; - deserializedKnowledgeBaseAzureBlobReference.blobUrl = blobUrl; - - return deserializedKnowledgeBaseAzureBlobReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseAzureBlobReference deserializedKnowledgeBaseAzureBlobReference + = new KnowledgeBaseAzureBlobReference(id, activitySource); + deserializedKnowledgeBaseAzureBlobReference.setSourceData(sourceData); + deserializedKnowledgeBaseAzureBlobReference.setRerankerScore(rerankerScore); + deserializedKnowledgeBaseAzureBlobReference.type = type; + deserializedKnowledgeBaseAzureBlobReference.blobUrl = blobUrl; + return deserializedKnowledgeBaseAzureBlobReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorAdditionalInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorAdditionalInfo.java index b2401fecfa9b..c0ae62923b37 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorAdditionalInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorAdditionalInfo.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -13,12 +10,14 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Map; /** * The resource management error additional info. */ @Immutable public final class KnowledgeBaseErrorAdditionalInfo implements JsonSerializable { + /* * The additional info type. */ @@ -29,18 +28,18 @@ public final class KnowledgeBaseErrorAdditionalInfo implements JsonSerializable< * The additional info. */ @Generated - private Object info; + private Map info; /** * Creates an instance of KnowledgeBaseErrorAdditionalInfo class. */ @Generated - public KnowledgeBaseErrorAdditionalInfo() { + private KnowledgeBaseErrorAdditionalInfo() { } /** * Get the type property: The additional info type. - * + * * @return the type value. */ @Generated @@ -50,11 +49,11 @@ public String getType() { /** * Get the info property: The additional info. - * + * * @return the info value. */ @Generated - public Object getInfo() { + public Map getInfo() { return this.info; } @@ -70,7 +69,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseErrorAdditionalInfo from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseErrorAdditionalInfo if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -84,16 +83,15 @@ public static KnowledgeBaseErrorAdditionalInfo fromJson(JsonReader jsonReader) t while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("type".equals(fieldName)) { deserializedKnowledgeBaseErrorAdditionalInfo.type = reader.getString(); } else if ("info".equals(fieldName)) { - deserializedKnowledgeBaseErrorAdditionalInfo.info = reader.readUntyped(); + Map info = reader.readMap(reader1 -> reader1.readUntyped()); + deserializedKnowledgeBaseErrorAdditionalInfo.info = info; } else { reader.skipChildren(); } } - return deserializedKnowledgeBaseErrorAdditionalInfo; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorDetail.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorDetail.java index 364e18b861fc..3d220005725e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorDetail.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorDetail.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -20,6 +17,7 @@ */ @Immutable public final class KnowledgeBaseErrorDetail implements JsonSerializable { + /* * The error code. */ @@ -54,12 +52,12 @@ public final class KnowledgeBaseErrorDetail implements JsonSerializable getDetails() { /** * Get the additionalInfo property: The error additional info. - * + * * @return the additionalInfo value. */ @Generated @@ -119,7 +117,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseErrorDetail from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseErrorDetail if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -132,7 +130,6 @@ public static KnowledgeBaseErrorDetail fromJson(JsonReader jsonReader) throws IO while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("code".equals(fieldName)) { deserializedKnowledgeBaseErrorDetail.code = reader.getString(); } else if ("message".equals(fieldName)) { @@ -151,7 +148,6 @@ public static KnowledgeBaseErrorDetail fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - return deserializedKnowledgeBaseErrorDetail; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContentImage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseImageContent.java similarity index 60% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContentImage.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseImageContent.java index a907fe80585e..7886787b482d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContentImage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseImageContent.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -15,11 +12,11 @@ import java.io.IOException; /** - * The KnowledgeBaseMessageImageContentImage model. + * Image content. */ @Immutable -public final class KnowledgeBaseMessageImageContentImage - implements JsonSerializable { +public final class KnowledgeBaseImageContent implements JsonSerializable { + /* * The url of the image. */ @@ -27,18 +24,18 @@ public final class KnowledgeBaseMessageImageContentImage private final String url; /** - * Creates an instance of KnowledgeBaseMessageImageContentImage class. - * + * Creates an instance of KnowledgeBaseImageContent class. + * * @param url the url value to set. */ @Generated - public KnowledgeBaseMessageImageContentImage(String url) { + public KnowledgeBaseImageContent(String url) { this.url = url; } /** * Get the url property: The url of the image. - * + * * @return the url value. */ @Generated @@ -58,34 +55,28 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of KnowledgeBaseMessageImageContentImage from the JsonReader. - * + * Reads an instance of KnowledgeBaseImageContent from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseMessageImageContentImage if the JsonReader was pointing to an instance of it, - * or null if it was pointing to JSON null. + * @return An instance of KnowledgeBaseImageContent 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 KnowledgeBaseMessageImageContentImage. + * @throws IOException If an error occurs while reading the KnowledgeBaseImageContent. */ @Generated - public static KnowledgeBaseMessageImageContentImage fromJson(JsonReader jsonReader) throws IOException { + public static KnowledgeBaseImageContent fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean urlFound = false; String url = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("url".equals(fieldName)) { url = reader.getString(); - urlFound = true; } else { reader.skipChildren(); } } - if (urlFound) { - return new KnowledgeBaseMessageImageContentImage(url); - } - throw new IllegalStateException("Missing required property: url"); + return new KnowledgeBaseImageContent(url); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeActivityArguments.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeActivityArguments.java deleted file mode 100644 index 6f57ff005de5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeActivityArguments.java +++ /dev/null @@ -1,96 +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.knowledgebases.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; - -/** - * Represents the arguments the indexed OneLake retrieval activity was run with. - */ -@Fluent -public final class KnowledgeBaseIndexedOneLakeActivityArguments - implements JsonSerializable { - /* - * The search string used to query indexed OneLake contents. - */ - @Generated - private String search; - - /** - * Creates an instance of KnowledgeBaseIndexedOneLakeActivityArguments class. - */ - @Generated - public KnowledgeBaseIndexedOneLakeActivityArguments() { - } - - /** - * Get the search property: The search string used to query indexed OneLake contents. - * - * @return the search value. - */ - @Generated - public String getSearch() { - return this.search; - } - - /** - * Set the search property: The search string used to query indexed OneLake contents. - * - * @param search the search value to set. - * @return the KnowledgeBaseIndexedOneLakeActivityArguments object itself. - */ - @Generated - public KnowledgeBaseIndexedOneLakeActivityArguments setSearch(String search) { - this.search = search; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("search", this.search); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseIndexedOneLakeActivityArguments from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseIndexedOneLakeActivityArguments 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 KnowledgeBaseIndexedOneLakeActivityArguments. - */ - @Generated - public static KnowledgeBaseIndexedOneLakeActivityArguments fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeBaseIndexedOneLakeActivityArguments deserializedKnowledgeBaseIndexedOneLakeActivityArguments - = new KnowledgeBaseIndexedOneLakeActivityArguments(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("search".equals(fieldName)) { - deserializedKnowledgeBaseIndexedOneLakeActivityArguments.search = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeBaseIndexedOneLakeActivityArguments; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeActivityRecord.java deleted file mode 100644 index cc08054d064b..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeActivityRecord.java +++ /dev/null @@ -1,212 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a indexed OneLake retrieval activity record. - */ -@Fluent -public final class KnowledgeBaseIndexedOneLakeActivityRecord extends KnowledgeBaseRetrievalActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "indexedOneLake"; - - /* - * The indexed OneLake arguments for the retrieval activity. - */ - @Generated - private KnowledgeBaseIndexedOneLakeActivityArguments indexedOneLakeArguments; - - /** - * Creates an instance of KnowledgeBaseIndexedOneLakeActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseIndexedOneLakeActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the indexedOneLakeArguments property: The indexed OneLake arguments for the retrieval activity. - * - * @return the indexedOneLakeArguments value. - */ - @Generated - public KnowledgeBaseIndexedOneLakeActivityArguments getIndexedOneLakeArguments() { - return this.indexedOneLakeArguments; - } - - /** - * Set the indexedOneLakeArguments property: The indexed OneLake arguments for the retrieval activity. - * - * @param indexedOneLakeArguments the indexedOneLakeArguments value to set. - * @return the KnowledgeBaseIndexedOneLakeActivityRecord object itself. - */ - @Generated - public KnowledgeBaseIndexedOneLakeActivityRecord - setIndexedOneLakeArguments(KnowledgeBaseIndexedOneLakeActivityArguments indexedOneLakeArguments) { - this.indexedOneLakeArguments = indexedOneLakeArguments; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - super.setKnowledgeSourceName(knowledgeSourceName); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeActivityRecord setQueryTime(OffsetDateTime queryTime) { - super.setQueryTime(queryTime); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeActivityRecord setCount(Integer count) { - super.setCount(count); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("knowledgeSourceName", getKnowledgeSourceName()); - jsonWriter.writeStringField("queryTime", - getQueryTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getQueryTime())); - jsonWriter.writeNumberField("count", getCount()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("indexedOneLakeArguments", this.indexedOneLakeArguments); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseIndexedOneLakeActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseIndexedOneLakeActivityRecord 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 KnowledgeBaseIndexedOneLakeActivityRecord. - */ - @Generated - public static KnowledgeBaseIndexedOneLakeActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - String type = "indexedOneLake"; - KnowledgeBaseIndexedOneLakeActivityArguments indexedOneLakeArguments = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("indexedOneLakeArguments".equals(fieldName)) { - indexedOneLakeArguments = KnowledgeBaseIndexedOneLakeActivityArguments.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseIndexedOneLakeActivityRecord deserializedKnowledgeBaseIndexedOneLakeActivityRecord - = new KnowledgeBaseIndexedOneLakeActivityRecord(id); - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.setError(error); - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.setKnowledgeSourceName(knowledgeSourceName); - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.setQueryTime(queryTime); - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.setCount(count); - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.type = type; - deserializedKnowledgeBaseIndexedOneLakeActivityRecord.indexedOneLakeArguments = indexedOneLakeArguments; - - return deserializedKnowledgeBaseIndexedOneLakeActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeReference.java index bf831f40aeed..eb8599dc3953 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeReference.java @@ -1,31 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** - * Represents an Azure Blob Storage document reference. + * Represents an indexed OneLake document reference. */ -@Fluent +@Immutable public final class KnowledgeBaseIndexedOneLakeReference extends KnowledgeBaseReference { + /* * The type of the reference. */ @Generated - private String type = "indexedOneLake"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.INDEXED_ONE_LAKE; /* * The document URL for the reference. @@ -35,29 +31,29 @@ public final class KnowledgeBaseIndexedOneLakeReference extends KnowledgeBaseRef /** * Creates an instance of KnowledgeBaseIndexedOneLakeReference class. - * + * * @param id the id value to set. * @param activitySource the activitySource value to set. */ @Generated - public KnowledgeBaseIndexedOneLakeReference(String id, int activitySource) { + private KnowledgeBaseIndexedOneLakeReference(String id, int activitySource) { super(id, activitySource); } /** * Get the type property: The type of the reference. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseReferenceType getType() { return this.type; } /** * Get the docUrl property: The document URL for the reference. - * + * * @return the docUrl value. */ @Generated @@ -65,38 +61,6 @@ public String getDocUrl() { return this.docUrl; } - /** - * Set the docUrl property: The document URL for the reference. - * - * @param docUrl the docUrl value to set. - * @return the KnowledgeBaseIndexedOneLakeReference object itself. - */ - @Generated - public KnowledgeBaseIndexedOneLakeReference setDocUrl(String docUrl) { - this.docUrl = docUrl; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeReference setSourceData(Map sourceData) { - super.setSourceData(sourceData); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedOneLakeReference setRerankerScore(Float rerankerScore) { - super.setRerankerScore(rerankerScore); - return this; - } - /** * {@inheritDoc} */ @@ -108,14 +72,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("activitySource", getActivitySource()); jsonWriter.writeMapField("sourceData", getSourceData(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", getRerankerScore()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("docUrl", this.docUrl); return jsonWriter.writeEndObject(); } /** * Reads an instance of KnowledgeBaseIndexedOneLakeReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseIndexedOneLakeReference if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -125,56 +89,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseIndexedOneLakeReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; Map sourceData = null; Float rerankerScore = null; - String type = "indexedOneLake"; + KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.INDEXED_ONE_LAKE; String docUrl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getFloat); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("docUrl".equals(fieldName)) { docUrl = reader.getString(); } else { reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseIndexedOneLakeReference deserializedKnowledgeBaseIndexedOneLakeReference - = new KnowledgeBaseIndexedOneLakeReference(id, activitySource); - deserializedKnowledgeBaseIndexedOneLakeReference.setSourceData(sourceData); - deserializedKnowledgeBaseIndexedOneLakeReference.setRerankerScore(rerankerScore); - deserializedKnowledgeBaseIndexedOneLakeReference.type = type; - deserializedKnowledgeBaseIndexedOneLakeReference.docUrl = docUrl; - - return deserializedKnowledgeBaseIndexedOneLakeReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseIndexedOneLakeReference deserializedKnowledgeBaseIndexedOneLakeReference + = new KnowledgeBaseIndexedOneLakeReference(id, activitySource); + deserializedKnowledgeBaseIndexedOneLakeReference.setSourceData(sourceData); + deserializedKnowledgeBaseIndexedOneLakeReference.setRerankerScore(rerankerScore); + deserializedKnowledgeBaseIndexedOneLakeReference.type = type; + deserializedKnowledgeBaseIndexedOneLakeReference.docUrl = docUrl; + return deserializedKnowledgeBaseIndexedOneLakeReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointActivityArguments.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointActivityArguments.java deleted file mode 100644 index 40496fdbcc3d..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointActivityArguments.java +++ /dev/null @@ -1,96 +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.knowledgebases.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; - -/** - * Represents the arguments the indexed SharePoint retrieval activity was run with. - */ -@Fluent -public final class KnowledgeBaseIndexedSharePointActivityArguments - implements JsonSerializable { - /* - * The search string used to query indexed SharePoint contents. - */ - @Generated - private String search; - - /** - * Creates an instance of KnowledgeBaseIndexedSharePointActivityArguments class. - */ - @Generated - public KnowledgeBaseIndexedSharePointActivityArguments() { - } - - /** - * Get the search property: The search string used to query indexed SharePoint contents. - * - * @return the search value. - */ - @Generated - public String getSearch() { - return this.search; - } - - /** - * Set the search property: The search string used to query indexed SharePoint contents. - * - * @param search the search value to set. - * @return the KnowledgeBaseIndexedSharePointActivityArguments object itself. - */ - @Generated - public KnowledgeBaseIndexedSharePointActivityArguments setSearch(String search) { - this.search = search; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("search", this.search); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseIndexedSharePointActivityArguments from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseIndexedSharePointActivityArguments 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 KnowledgeBaseIndexedSharePointActivityArguments. - */ - @Generated - public static KnowledgeBaseIndexedSharePointActivityArguments fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeBaseIndexedSharePointActivityArguments deserializedKnowledgeBaseIndexedSharePointActivityArguments - = new KnowledgeBaseIndexedSharePointActivityArguments(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("search".equals(fieldName)) { - deserializedKnowledgeBaseIndexedSharePointActivityArguments.search = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeBaseIndexedSharePointActivityArguments; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointActivityRecord.java deleted file mode 100644 index eb4a895285a9..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointActivityRecord.java +++ /dev/null @@ -1,213 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a indexed SharePoint retrieval activity record. - */ -@Fluent -public final class KnowledgeBaseIndexedSharePointActivityRecord extends KnowledgeBaseRetrievalActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "indexedSharePoint"; - - /* - * The indexed SharePoint arguments for the retrieval activity. - */ - @Generated - private KnowledgeBaseIndexedSharePointActivityArguments indexedSharePointArguments; - - /** - * Creates an instance of KnowledgeBaseIndexedSharePointActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseIndexedSharePointActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the indexedSharePointArguments property: The indexed SharePoint arguments for the retrieval activity. - * - * @return the indexedSharePointArguments value. - */ - @Generated - public KnowledgeBaseIndexedSharePointActivityArguments getIndexedSharePointArguments() { - return this.indexedSharePointArguments; - } - - /** - * Set the indexedSharePointArguments property: The indexed SharePoint arguments for the retrieval activity. - * - * @param indexedSharePointArguments the indexedSharePointArguments value to set. - * @return the KnowledgeBaseIndexedSharePointActivityRecord object itself. - */ - @Generated - public KnowledgeBaseIndexedSharePointActivityRecord - setIndexedSharePointArguments(KnowledgeBaseIndexedSharePointActivityArguments indexedSharePointArguments) { - this.indexedSharePointArguments = indexedSharePointArguments; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - super.setKnowledgeSourceName(knowledgeSourceName); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointActivityRecord setQueryTime(OffsetDateTime queryTime) { - super.setQueryTime(queryTime); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointActivityRecord setCount(Integer count) { - super.setCount(count); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("knowledgeSourceName", getKnowledgeSourceName()); - jsonWriter.writeStringField("queryTime", - getQueryTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getQueryTime())); - jsonWriter.writeNumberField("count", getCount()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("indexedSharePointArguments", this.indexedSharePointArguments); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseIndexedSharePointActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseIndexedSharePointActivityRecord 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 KnowledgeBaseIndexedSharePointActivityRecord. - */ - @Generated - public static KnowledgeBaseIndexedSharePointActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - String type = "indexedSharePoint"; - KnowledgeBaseIndexedSharePointActivityArguments indexedSharePointArguments = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("indexedSharePointArguments".equals(fieldName)) { - indexedSharePointArguments = KnowledgeBaseIndexedSharePointActivityArguments.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseIndexedSharePointActivityRecord deserializedKnowledgeBaseIndexedSharePointActivityRecord - = new KnowledgeBaseIndexedSharePointActivityRecord(id); - deserializedKnowledgeBaseIndexedSharePointActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseIndexedSharePointActivityRecord.setError(error); - deserializedKnowledgeBaseIndexedSharePointActivityRecord.setKnowledgeSourceName(knowledgeSourceName); - deserializedKnowledgeBaseIndexedSharePointActivityRecord.setQueryTime(queryTime); - deserializedKnowledgeBaseIndexedSharePointActivityRecord.setCount(count); - deserializedKnowledgeBaseIndexedSharePointActivityRecord.type = type; - deserializedKnowledgeBaseIndexedSharePointActivityRecord.indexedSharePointArguments - = indexedSharePointArguments; - - return deserializedKnowledgeBaseIndexedSharePointActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointReference.java index e8e2da843b42..858f48b1e633 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointReference.java @@ -1,31 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** - * Represents an Azure Blob Storage document reference. + * Represents an indexed SharePoint document reference. */ -@Fluent +@Immutable public final class KnowledgeBaseIndexedSharePointReference extends KnowledgeBaseReference { + /* * The type of the reference. */ @Generated - private String type = "indexedSharePoint"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.INDEXED_SHARE_POINT; /* * The document URL for the reference. @@ -35,29 +31,29 @@ public final class KnowledgeBaseIndexedSharePointReference extends KnowledgeBase /** * Creates an instance of KnowledgeBaseIndexedSharePointReference class. - * + * * @param id the id value to set. * @param activitySource the activitySource value to set. */ @Generated - public KnowledgeBaseIndexedSharePointReference(String id, int activitySource) { + private KnowledgeBaseIndexedSharePointReference(String id, int activitySource) { super(id, activitySource); } /** * Get the type property: The type of the reference. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseReferenceType getType() { return this.type; } /** * Get the docUrl property: The document URL for the reference. - * + * * @return the docUrl value. */ @Generated @@ -65,38 +61,6 @@ public String getDocUrl() { return this.docUrl; } - /** - * Set the docUrl property: The document URL for the reference. - * - * @param docUrl the docUrl value to set. - * @return the KnowledgeBaseIndexedSharePointReference object itself. - */ - @Generated - public KnowledgeBaseIndexedSharePointReference setDocUrl(String docUrl) { - this.docUrl = docUrl; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointReference setSourceData(Map sourceData) { - super.setSourceData(sourceData); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseIndexedSharePointReference setRerankerScore(Float rerankerScore) { - super.setRerankerScore(rerankerScore); - return this; - } - /** * {@inheritDoc} */ @@ -108,14 +72,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("activitySource", getActivitySource()); jsonWriter.writeMapField("sourceData", getSourceData(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", getRerankerScore()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("docUrl", this.docUrl); return jsonWriter.writeEndObject(); } /** * Reads an instance of KnowledgeBaseIndexedSharePointReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseIndexedSharePointReference if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -125,56 +89,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseIndexedSharePointReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; Map sourceData = null; Float rerankerScore = null; - String type = "indexedSharePoint"; + KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.INDEXED_SHARE_POINT; String docUrl = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getFloat); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("docUrl".equals(fieldName)) { docUrl = reader.getString(); } else { reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseIndexedSharePointReference deserializedKnowledgeBaseIndexedSharePointReference - = new KnowledgeBaseIndexedSharePointReference(id, activitySource); - deserializedKnowledgeBaseIndexedSharePointReference.setSourceData(sourceData); - deserializedKnowledgeBaseIndexedSharePointReference.setRerankerScore(rerankerScore); - deserializedKnowledgeBaseIndexedSharePointReference.type = type; - deserializedKnowledgeBaseIndexedSharePointReference.docUrl = docUrl; - - return deserializedKnowledgeBaseIndexedSharePointReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseIndexedSharePointReference deserializedKnowledgeBaseIndexedSharePointReference + = new KnowledgeBaseIndexedSharePointReference(id, activitySource); + deserializedKnowledgeBaseIndexedSharePointReference.setSourceData(sourceData); + deserializedKnowledgeBaseIndexedSharePointReference.setRerankerScore(rerankerScore); + deserializedKnowledgeBaseIndexedSharePointReference.type = type; + deserializedKnowledgeBaseIndexedSharePointReference.docUrl = docUrl; + return deserializedKnowledgeBaseIndexedSharePointReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessage.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessage.java index 9f247ae887f5..59fad04622b3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessage.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessage.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @Fluent public final class KnowledgeBaseMessage implements JsonSerializable { + /* * The role of the tool response. */ @@ -27,14 +26,23 @@ public final class KnowledgeBaseMessage implements JsonSerializable content; /** * Creates an instance of KnowledgeBaseMessage class. - * + * + * @param content the content value to set. + */ + public KnowledgeBaseMessage(KnowledgeBaseMessageContent... content) { + this.content = (content == null) ? null : Arrays.asList(content); + } + + /** + * Creates an instance of KnowledgeBaseMessage class. + * * @param content the content value to set. */ @Generated @@ -44,7 +52,7 @@ public KnowledgeBaseMessage(List content) { /** * Get the role property: The role of the tool response. - * + * * @return the role value. */ @Generated @@ -54,7 +62,7 @@ public String getRole() { /** * Set the role property: The role of the tool response. - * + * * @param role the role value to set. * @return the KnowledgeBaseMessage object itself. */ @@ -65,8 +73,8 @@ public KnowledgeBaseMessage setRole(String role) { } /** - * Get the content property: The content property. - * + * Get the content property: The content of the message. + * * @return the content value. */ @Generated @@ -88,7 +96,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseMessage from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseMessage if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -98,29 +106,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseMessage fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean contentFound = false; List content = null; String role = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("content".equals(fieldName)) { content = reader.readArray(reader1 -> KnowledgeBaseMessageContent.fromJson(reader1)); - contentFound = true; } else if ("role".equals(fieldName)) { role = reader.getString(); } else { reader.skipChildren(); } } - if (contentFound) { - KnowledgeBaseMessage deserializedKnowledgeBaseMessage = new KnowledgeBaseMessage(content); - deserializedKnowledgeBaseMessage.role = role; - - return deserializedKnowledgeBaseMessage; - } - throw new IllegalStateException("Missing required property: content"); + KnowledgeBaseMessage deserializedKnowledgeBaseMessage = new KnowledgeBaseMessage(content); + deserializedKnowledgeBaseMessage.role = role; + return deserializedKnowledgeBaseMessage; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContent.java index ca66836dd74a..2d567e8b54ca 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContent.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContent.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -19,6 +16,7 @@ */ @Immutable public class KnowledgeBaseMessageContent implements JsonSerializable { + /* * The type of the message */ @@ -35,7 +33,7 @@ public KnowledgeBaseMessageContent() { /** * Get the type property: The type of the message. - * + * * @return the type value. */ @Generated @@ -56,7 +54,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseMessageContent from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseMessageContent if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -67,7 +65,8 @@ public static KnowledgeBaseMessageContent fromJson(JsonReader jsonReader) throws return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -97,7 +96,6 @@ static KnowledgeBaseMessageContent fromJsonKnownDiscriminator(JsonReader jsonRea while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("type".equals(fieldName)) { deserializedKnowledgeBaseMessageContent.type = KnowledgeBaseMessageContentType.fromString(reader.getString()); @@ -105,7 +103,6 @@ static KnowledgeBaseMessageContent fromJsonKnownDiscriminator(JsonReader jsonRea reader.skipChildren(); } } - return deserializedKnowledgeBaseMessageContent; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContentType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContentType.java index cd3f3f8ea34f..0995d598c2d2 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContentType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContentType.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The type of message content. */ public final class KnowledgeBaseMessageContentType extends ExpandableStringEnum { + /** * Text message content kind. */ @@ -28,7 +26,7 @@ public final class KnowledgeBaseMessageContentType extends ExpandableStringEnum< /** * Creates a new instance of KnowledgeBaseMessageContentType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -38,7 +36,7 @@ public KnowledgeBaseMessageContentType() { /** * Creates or finds a KnowledgeBaseMessageContentType from its string representation. - * + * * @param name a name to look for. * @return the corresponding KnowledgeBaseMessageContentType. */ @@ -49,7 +47,7 @@ public static KnowledgeBaseMessageContentType fromString(String name) { /** * Gets known KnowledgeBaseMessageContentType values. - * + * * @return known KnowledgeBaseMessageContentType values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContent.java index 67c625a2aa6f..69928c851bf4 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContent.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContent.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -14,10 +11,11 @@ import java.io.IOException; /** - * Text message type. + * Image message type. */ @Immutable public final class KnowledgeBaseMessageImageContent extends KnowledgeBaseMessageContent { + /* * The type of the message */ @@ -25,24 +23,24 @@ public final class KnowledgeBaseMessageImageContent extends KnowledgeBaseMessage private KnowledgeBaseMessageContentType type = KnowledgeBaseMessageContentType.IMAGE; /* - * The image property. + * The image content. */ @Generated - private final KnowledgeBaseMessageImageContentImage image; + private final KnowledgeBaseImageContent image; /** * Creates an instance of KnowledgeBaseMessageImageContent class. - * + * * @param image the image value to set. */ @Generated - public KnowledgeBaseMessageImageContent(KnowledgeBaseMessageImageContentImage image) { + public KnowledgeBaseMessageImageContent(KnowledgeBaseImageContent image) { this.image = image; } /** * Get the type property: The type of the message. - * + * * @return the type value. */ @Generated @@ -52,12 +50,12 @@ public KnowledgeBaseMessageContentType getType() { } /** - * Get the image property: The image property. - * + * Get the image property: The image content. + * * @return the image value. */ @Generated - public KnowledgeBaseMessageImageContentImage getImage() { + public KnowledgeBaseImageContent getImage() { return this.image; } @@ -75,7 +73,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseMessageImageContent from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseMessageImageContent if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -85,30 +83,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseMessageImageContent fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean imageFound = false; - KnowledgeBaseMessageImageContentImage image = null; + KnowledgeBaseImageContent image = null; KnowledgeBaseMessageContentType type = KnowledgeBaseMessageContentType.IMAGE; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("image".equals(fieldName)) { - image = KnowledgeBaseMessageImageContentImage.fromJson(reader); - imageFound = true; + image = KnowledgeBaseImageContent.fromJson(reader); } else if ("type".equals(fieldName)) { type = KnowledgeBaseMessageContentType.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (imageFound) { - KnowledgeBaseMessageImageContent deserializedKnowledgeBaseMessageImageContent - = new KnowledgeBaseMessageImageContent(image); - deserializedKnowledgeBaseMessageImageContent.type = type; - - return deserializedKnowledgeBaseMessageImageContent; - } - throw new IllegalStateException("Missing required property: image"); + KnowledgeBaseMessageImageContent deserializedKnowledgeBaseMessageImageContent + = new KnowledgeBaseMessageImageContent(image); + deserializedKnowledgeBaseMessageImageContent.type = type; + return deserializedKnowledgeBaseMessageImageContent; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageTextContent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageTextContent.java index 6866019e51a7..5ea17e4d820e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageTextContent.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageTextContent.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -18,6 +15,7 @@ */ @Immutable public final class KnowledgeBaseMessageTextContent extends KnowledgeBaseMessageContent { + /* * The type of the message */ @@ -25,14 +23,14 @@ public final class KnowledgeBaseMessageTextContent extends KnowledgeBaseMessageC private KnowledgeBaseMessageContentType type = KnowledgeBaseMessageContentType.TEXT; /* - * The text property. + * The text content. */ @Generated private final String text; /** * Creates an instance of KnowledgeBaseMessageTextContent class. - * + * * @param text the text value to set. */ @Generated @@ -42,7 +40,7 @@ public KnowledgeBaseMessageTextContent(String text) { /** * Get the type property: The type of the message. - * + * * @return the type value. */ @Generated @@ -52,8 +50,8 @@ public KnowledgeBaseMessageContentType getType() { } /** - * Get the text property: The text property. - * + * Get the text property: The text content. + * * @return the text value. */ @Generated @@ -75,7 +73,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseMessageTextContent from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseMessageTextContent if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -85,30 +83,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseMessageTextContent fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean textFound = false; String text = null; KnowledgeBaseMessageContentType type = KnowledgeBaseMessageContentType.TEXT; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("text".equals(fieldName)) { text = reader.getString(); - textFound = true; } else if ("type".equals(fieldName)) { type = KnowledgeBaseMessageContentType.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (textFound) { - KnowledgeBaseMessageTextContent deserializedKnowledgeBaseMessageTextContent - = new KnowledgeBaseMessageTextContent(text); - deserializedKnowledgeBaseMessageTextContent.type = type; - - return deserializedKnowledgeBaseMessageTextContent; - } - throw new IllegalStateException("Missing required property: text"); + KnowledgeBaseMessageTextContent deserializedKnowledgeBaseMessageTextContent + = new KnowledgeBaseMessageTextContent(text); + deserializedKnowledgeBaseMessageTextContent.type = type; + return deserializedKnowledgeBaseMessageTextContent; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelAnswerSynthesisActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelAnswerSynthesisActivityRecord.java index 7cc2fc6afb63..d4a1c0703836 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelAnswerSynthesisActivityRecord.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelAnswerSynthesisActivityRecord.java @@ -1,13 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; @@ -16,13 +13,14 @@ /** * Represents an LLM answer synthesis activity record. */ -@Fluent +@Immutable public final class KnowledgeBaseModelAnswerSynthesisActivityRecord extends KnowledgeBaseActivityRecord { + /* * The type of the activity record. */ @Generated - private String type = "modelAnswerSynthesis"; + private KnowledgeBaseActivityRecordType type = KnowledgeBaseActivityRecordType.MODEL_ANSWER_SYNTHESIS; /* * The number of input tokens for the LLM answer synthesis activity. @@ -38,28 +36,28 @@ public final class KnowledgeBaseModelAnswerSynthesisActivityRecord extends Knowl /** * Creates an instance of KnowledgeBaseModelAnswerSynthesisActivityRecord class. - * + * * @param id the id value to set. */ @Generated - public KnowledgeBaseModelAnswerSynthesisActivityRecord(int id) { + private KnowledgeBaseModelAnswerSynthesisActivityRecord(int id) { super(id); } /** * Get the type property: The type of the activity record. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseActivityRecordType getType() { return this.type; } /** * Get the inputTokens property: The number of input tokens for the LLM answer synthesis activity. - * + * * @return the inputTokens value. */ @Generated @@ -67,21 +65,9 @@ public Integer getInputTokens() { return this.inputTokens; } - /** - * Set the inputTokens property: The number of input tokens for the LLM answer synthesis activity. - * - * @param inputTokens the inputTokens value to set. - * @return the KnowledgeBaseModelAnswerSynthesisActivityRecord object itself. - */ - @Generated - public KnowledgeBaseModelAnswerSynthesisActivityRecord setInputTokens(Integer inputTokens) { - this.inputTokens = inputTokens; - return this; - } - /** * Get the outputTokens property: The number of output tokens for the LLM answer synthesis activity. - * + * * @return the outputTokens value. */ @Generated @@ -89,38 +75,6 @@ public Integer getOutputTokens() { return this.outputTokens; } - /** - * Set the outputTokens property: The number of output tokens for the LLM answer synthesis activity. - * - * @param outputTokens the outputTokens value to set. - * @return the KnowledgeBaseModelAnswerSynthesisActivityRecord object itself. - */ - @Generated - public KnowledgeBaseModelAnswerSynthesisActivityRecord setOutputTokens(Integer outputTokens) { - this.outputTokens = outputTokens; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseModelAnswerSynthesisActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseModelAnswerSynthesisActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - /** * {@inheritDoc} */ @@ -131,7 +85,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("id", getId()); jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeNumberField("inputTokens", this.inputTokens); jsonWriter.writeNumberField("outputTokens", this.outputTokens); return jsonWriter.writeEndObject(); @@ -139,7 +93,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseModelAnswerSynthesisActivityRecord from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseModelAnswerSynthesisActivityRecord if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -149,26 +103,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseModelAnswerSynthesisActivityRecord fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; int id = 0; Integer elapsedMs = null; KnowledgeBaseErrorDetail error = null; - String type = "modelAnswerSynthesis"; + KnowledgeBaseActivityRecordType type = KnowledgeBaseActivityRecordType.MODEL_ANSWER_SYNTHESIS; Integer inputTokens = null; Integer outputTokens = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getInt(); - idFound = true; } else if ("elapsedMs".equals(fieldName)) { elapsedMs = reader.getNullable(JsonReader::getInt); } else if ("error".equals(fieldName)) { error = KnowledgeBaseErrorDetail.fromJson(reader); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseActivityRecordType.fromString(reader.getString()); } else if ("inputTokens".equals(fieldName)) { inputTokens = reader.getNullable(JsonReader::getInt); } else if ("outputTokens".equals(fieldName)) { @@ -177,18 +128,14 @@ public static KnowledgeBaseModelAnswerSynthesisActivityRecord fromJson(JsonReade reader.skipChildren(); } } - if (idFound) { - KnowledgeBaseModelAnswerSynthesisActivityRecord deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord - = new KnowledgeBaseModelAnswerSynthesisActivityRecord(id); - deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.setError(error); - deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.type = type; - deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.inputTokens = inputTokens; - deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.outputTokens = outputTokens; - - return deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); + KnowledgeBaseModelAnswerSynthesisActivityRecord deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord + = new KnowledgeBaseModelAnswerSynthesisActivityRecord(id); + deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.setElapsedMs(elapsedMs); + deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.setError(error); + deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.type = type; + deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.inputTokens = inputTokens; + deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord.outputTokens = outputTokens; + return deserializedKnowledgeBaseModelAnswerSynthesisActivityRecord; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelQueryPlanningActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelQueryPlanningActivityRecord.java index b815715c871a..d29606c5f856 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelQueryPlanningActivityRecord.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelQueryPlanningActivityRecord.java @@ -1,13 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; @@ -16,13 +13,14 @@ /** * Represents an LLM query planning activity record. */ -@Fluent +@Immutable public final class KnowledgeBaseModelQueryPlanningActivityRecord extends KnowledgeBaseActivityRecord { + /* * The type of the activity record. */ @Generated - private String type = "modelQueryPlanning"; + private KnowledgeBaseActivityRecordType type = KnowledgeBaseActivityRecordType.MODEL_QUERY_PLANNING; /* * The number of input tokens for the LLM query planning activity. @@ -38,28 +36,28 @@ public final class KnowledgeBaseModelQueryPlanningActivityRecord extends Knowled /** * Creates an instance of KnowledgeBaseModelQueryPlanningActivityRecord class. - * + * * @param id the id value to set. */ @Generated - public KnowledgeBaseModelQueryPlanningActivityRecord(int id) { + private KnowledgeBaseModelQueryPlanningActivityRecord(int id) { super(id); } /** * Get the type property: The type of the activity record. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseActivityRecordType getType() { return this.type; } /** * Get the inputTokens property: The number of input tokens for the LLM query planning activity. - * + * * @return the inputTokens value. */ @Generated @@ -67,21 +65,9 @@ public Integer getInputTokens() { return this.inputTokens; } - /** - * Set the inputTokens property: The number of input tokens for the LLM query planning activity. - * - * @param inputTokens the inputTokens value to set. - * @return the KnowledgeBaseModelQueryPlanningActivityRecord object itself. - */ - @Generated - public KnowledgeBaseModelQueryPlanningActivityRecord setInputTokens(Integer inputTokens) { - this.inputTokens = inputTokens; - return this; - } - /** * Get the outputTokens property: The number of output tokens for the LLM query planning activity. - * + * * @return the outputTokens value. */ @Generated @@ -89,38 +75,6 @@ public Integer getOutputTokens() { return this.outputTokens; } - /** - * Set the outputTokens property: The number of output tokens for the LLM query planning activity. - * - * @param outputTokens the outputTokens value to set. - * @return the KnowledgeBaseModelQueryPlanningActivityRecord object itself. - */ - @Generated - public KnowledgeBaseModelQueryPlanningActivityRecord setOutputTokens(Integer outputTokens) { - this.outputTokens = outputTokens; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseModelQueryPlanningActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseModelQueryPlanningActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - /** * {@inheritDoc} */ @@ -131,7 +85,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("id", getId()); jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeNumberField("inputTokens", this.inputTokens); jsonWriter.writeNumberField("outputTokens", this.outputTokens); return jsonWriter.writeEndObject(); @@ -139,7 +93,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseModelQueryPlanningActivityRecord from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseModelQueryPlanningActivityRecord if the JsonReader was pointing to an * instance of it, or null if it was pointing to JSON null. @@ -149,26 +103,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseModelQueryPlanningActivityRecord fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; int id = 0; Integer elapsedMs = null; KnowledgeBaseErrorDetail error = null; - String type = "modelQueryPlanning"; + KnowledgeBaseActivityRecordType type = KnowledgeBaseActivityRecordType.MODEL_QUERY_PLANNING; Integer inputTokens = null; Integer outputTokens = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getInt(); - idFound = true; } else if ("elapsedMs".equals(fieldName)) { elapsedMs = reader.getNullable(JsonReader::getInt); } else if ("error".equals(fieldName)) { error = KnowledgeBaseErrorDetail.fromJson(reader); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseActivityRecordType.fromString(reader.getString()); } else if ("inputTokens".equals(fieldName)) { inputTokens = reader.getNullable(JsonReader::getInt); } else if ("outputTokens".equals(fieldName)) { @@ -177,18 +128,14 @@ public static KnowledgeBaseModelQueryPlanningActivityRecord fromJson(JsonReader reader.skipChildren(); } } - if (idFound) { - KnowledgeBaseModelQueryPlanningActivityRecord deserializedKnowledgeBaseModelQueryPlanningActivityRecord - = new KnowledgeBaseModelQueryPlanningActivityRecord(id); - deserializedKnowledgeBaseModelQueryPlanningActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseModelQueryPlanningActivityRecord.setError(error); - deserializedKnowledgeBaseModelQueryPlanningActivityRecord.type = type; - deserializedKnowledgeBaseModelQueryPlanningActivityRecord.inputTokens = inputTokens; - deserializedKnowledgeBaseModelQueryPlanningActivityRecord.outputTokens = outputTokens; - - return deserializedKnowledgeBaseModelQueryPlanningActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); + KnowledgeBaseModelQueryPlanningActivityRecord deserializedKnowledgeBaseModelQueryPlanningActivityRecord + = new KnowledgeBaseModelQueryPlanningActivityRecord(id); + deserializedKnowledgeBaseModelQueryPlanningActivityRecord.setElapsedMs(elapsedMs); + deserializedKnowledgeBaseModelQueryPlanningActivityRecord.setError(error); + deserializedKnowledgeBaseModelQueryPlanningActivityRecord.type = type; + deserializedKnowledgeBaseModelQueryPlanningActivityRecord.inputTokens = inputTokens; + deserializedKnowledgeBaseModelQueryPlanningActivityRecord.outputTokens = outputTokens; + return deserializedKnowledgeBaseModelQueryPlanningActivityRecord; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReference.java index 8cb319ca9fc5..70f670e3b31b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReference.java @@ -1,32 +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.knowledgebases.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; import java.util.Map; /** * Base type for references. */ -@Fluent +@Immutable public class KnowledgeBaseReference implements JsonSerializable { + /* * The type of the reference. */ @Generated - private String type = "KnowledgeBaseReference"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.fromString("KnowledgeBaseReference"); /* * The ID of the reference. @@ -41,7 +37,7 @@ public class KnowledgeBaseReference implements JsonSerializable + * The source data for the reference. */ @Generated private Map sourceData; @@ -54,29 +50,29 @@ public class KnowledgeBaseReference implements JsonSerializable getSourceData() { } /** - * Set the sourceData property: Dictionary of <any>. - * + * Set the sourceData property: The source data for the reference. + * * @param sourceData the sourceData value to set. * @return the KnowledgeBaseReference object itself. */ @Generated - public KnowledgeBaseReference setSourceData(Map sourceData) { + KnowledgeBaseReference setSourceData(Map sourceData) { this.sourceData = sourceData; return this; } /** * Get the rerankerScore property: The reranker score for the document reference. - * + * * @return the rerankerScore value. */ @Generated @@ -128,12 +124,12 @@ public Float getRerankerScore() { /** * Set the rerankerScore property: The reranker score for the document reference. - * + * * @param rerankerScore the rerankerScore value to set. * @return the KnowledgeBaseReference object itself. */ @Generated - public KnowledgeBaseReference setRerankerScore(Float rerankerScore) { + KnowledgeBaseReference setRerankerScore(Float rerankerScore) { this.rerankerScore = rerankerScore; return this; } @@ -147,7 +143,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); jsonWriter.writeStringField("id", this.id); jsonWriter.writeIntField("activitySource", this.activitySource); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeMapField("sourceData", this.sourceData, (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", this.rerankerScore); return jsonWriter.writeEndObject(); @@ -155,7 +151,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseReference if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -167,7 +163,8 @@ public static KnowledgeBaseReference fromJson(JsonReader jsonReader) throws IOEx return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -201,25 +198,20 @@ public static KnowledgeBaseReference fromJson(JsonReader jsonReader) throws IOEx @Generated static KnowledgeBaseReference fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; - String type = null; + KnowledgeBaseReferenceType type = null; Map sourceData = null; Float rerankerScore = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { @@ -228,25 +220,11 @@ static KnowledgeBaseReference fromJsonKnownDiscriminator(JsonReader jsonReader) reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseReference deserializedKnowledgeBaseReference - = new KnowledgeBaseReference(id, activitySource); - deserializedKnowledgeBaseReference.type = type; - deserializedKnowledgeBaseReference.sourceData = sourceData; - deserializedKnowledgeBaseReference.rerankerScore = rerankerScore; - - return deserializedKnowledgeBaseReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseReference deserializedKnowledgeBaseReference = new KnowledgeBaseReference(id, activitySource); + deserializedKnowledgeBaseReference.type = type; + deserializedKnowledgeBaseReference.sourceData = sourceData; + deserializedKnowledgeBaseReference.rerankerScore = rerankerScore; + return deserializedKnowledgeBaseReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReferenceType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReferenceType.java new file mode 100644 index 000000000000..293e0b1d17e6 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReferenceType.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.knowledgebases.models; + +import com.azure.core.annotation.Generated; +import com.azure.core.util.ExpandableStringEnum; +import java.util.Collection; + +/** + * The type of reference. + */ +public final class KnowledgeBaseReferenceType extends ExpandableStringEnum { + + /** + * Search index document reference. + */ + @Generated + public static final KnowledgeBaseReferenceType SEARCH_INDEX = fromString("searchIndex"); + + /** + * Azure Blob document reference. + */ + @Generated + public static final KnowledgeBaseReferenceType AZURE_BLOB = fromString("azureBlob"); + + /** + * Indexed SharePoint document reference. + */ + @Generated + public static final KnowledgeBaseReferenceType INDEXED_SHARE_POINT = fromString("indexedSharePoint"); + + /** + * Indexed OneLake document reference. + */ + @Generated + public static final KnowledgeBaseReferenceType INDEXED_ONE_LAKE = fromString("indexedOneLake"); + + /** + * Web document reference. + */ + @Generated + public static final KnowledgeBaseReferenceType WEB = fromString("web"); + + /** + * Remote SharePoint document reference. + */ + @Generated + public static final KnowledgeBaseReferenceType REMOTE_SHARE_POINT = fromString("remoteSharePoint"); + + /** + * Creates a new instance of KnowledgeBaseReferenceType value. + * + * @deprecated Use the {@link #fromString(String)} factory method. + */ + @Generated + @Deprecated + public KnowledgeBaseReferenceType() { + } + + /** + * Creates or finds a KnowledgeBaseReferenceType from its string representation. + * + * @param name a name to look for. + * @return the corresponding KnowledgeBaseReferenceType. + */ + @Generated + public static KnowledgeBaseReferenceType fromString(String name) { + return fromString(name, KnowledgeBaseReferenceType.class); + } + + /** + * Gets known KnowledgeBaseReferenceType values. + * + * @return known KnowledgeBaseReferenceType values. + */ + @Generated + public static Collection values() { + return values(KnowledgeBaseReferenceType.class); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointActivityArguments.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointActivityArguments.java deleted file mode 100644 index 9d4346e48a27..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointActivityArguments.java +++ /dev/null @@ -1,128 +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.knowledgebases.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; - -/** - * Represents the arguments the remote SharePoint retrieval activity was run with. - */ -@Fluent -public final class KnowledgeBaseRemoteSharePointActivityArguments - implements JsonSerializable { - /* - * The search string used to query the remote SharePoint knowledge source. - */ - @Generated - private String search; - - /* - * The filter expression add-on for the retrieval activity. - */ - @Generated - private String filterExpressionAddOn; - - /** - * Creates an instance of KnowledgeBaseRemoteSharePointActivityArguments class. - */ - @Generated - public KnowledgeBaseRemoteSharePointActivityArguments() { - } - - /** - * Get the search property: The search string used to query the remote SharePoint knowledge source. - * - * @return the search value. - */ - @Generated - public String getSearch() { - return this.search; - } - - /** - * Set the search property: The search string used to query the remote SharePoint knowledge source. - * - * @param search the search value to set. - * @return the KnowledgeBaseRemoteSharePointActivityArguments object itself. - */ - @Generated - public KnowledgeBaseRemoteSharePointActivityArguments setSearch(String search) { - this.search = search; - return this; - } - - /** - * Get the filterExpressionAddOn property: The filter expression add-on for the retrieval activity. - * - * @return the filterExpressionAddOn value. - */ - @Generated - public String getFilterExpressionAddOn() { - return this.filterExpressionAddOn; - } - - /** - * Set the filterExpressionAddOn property: The filter expression add-on for the retrieval activity. - * - * @param filterExpressionAddOn the filterExpressionAddOn value to set. - * @return the KnowledgeBaseRemoteSharePointActivityArguments object itself. - */ - @Generated - public KnowledgeBaseRemoteSharePointActivityArguments setFilterExpressionAddOn(String filterExpressionAddOn) { - this.filterExpressionAddOn = filterExpressionAddOn; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("search", this.search); - jsonWriter.writeStringField("filterExpressionAddOn", this.filterExpressionAddOn); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseRemoteSharePointActivityArguments from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseRemoteSharePointActivityArguments 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 KnowledgeBaseRemoteSharePointActivityArguments. - */ - @Generated - public static KnowledgeBaseRemoteSharePointActivityArguments fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeBaseRemoteSharePointActivityArguments deserializedKnowledgeBaseRemoteSharePointActivityArguments - = new KnowledgeBaseRemoteSharePointActivityArguments(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("search".equals(fieldName)) { - deserializedKnowledgeBaseRemoteSharePointActivityArguments.search = reader.getString(); - } else if ("filterExpressionAddOn".equals(fieldName)) { - deserializedKnowledgeBaseRemoteSharePointActivityArguments.filterExpressionAddOn - = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeBaseRemoteSharePointActivityArguments; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointActivityRecord.java deleted file mode 100644 index e02faf57b58e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointActivityRecord.java +++ /dev/null @@ -1,213 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a remote SharePoint retrieval activity record. - */ -@Fluent -public final class KnowledgeBaseRemoteSharePointActivityRecord extends KnowledgeBaseRetrievalActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "remoteSharePoint"; - - /* - * The remote SharePoint arguments for the retrieval activity. - */ - @Generated - private KnowledgeBaseRemoteSharePointActivityArguments remoteSharePointArguments; - - /** - * Creates an instance of KnowledgeBaseRemoteSharePointActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseRemoteSharePointActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the remoteSharePointArguments property: The remote SharePoint arguments for the retrieval activity. - * - * @return the remoteSharePointArguments value. - */ - @Generated - public KnowledgeBaseRemoteSharePointActivityArguments getRemoteSharePointArguments() { - return this.remoteSharePointArguments; - } - - /** - * Set the remoteSharePointArguments property: The remote SharePoint arguments for the retrieval activity. - * - * @param remoteSharePointArguments the remoteSharePointArguments value to set. - * @return the KnowledgeBaseRemoteSharePointActivityRecord object itself. - */ - @Generated - public KnowledgeBaseRemoteSharePointActivityRecord - setRemoteSharePointArguments(KnowledgeBaseRemoteSharePointActivityArguments remoteSharePointArguments) { - this.remoteSharePointArguments = remoteSharePointArguments; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - super.setKnowledgeSourceName(knowledgeSourceName); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointActivityRecord setQueryTime(OffsetDateTime queryTime) { - super.setQueryTime(queryTime); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointActivityRecord setCount(Integer count) { - super.setCount(count); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("knowledgeSourceName", getKnowledgeSourceName()); - jsonWriter.writeStringField("queryTime", - getQueryTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getQueryTime())); - jsonWriter.writeNumberField("count", getCount()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("remoteSharePointArguments", this.remoteSharePointArguments); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseRemoteSharePointActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseRemoteSharePointActivityRecord 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 KnowledgeBaseRemoteSharePointActivityRecord. - */ - @Generated - public static KnowledgeBaseRemoteSharePointActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - String type = "remoteSharePoint"; - KnowledgeBaseRemoteSharePointActivityArguments remoteSharePointArguments = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("remoteSharePointArguments".equals(fieldName)) { - remoteSharePointArguments = KnowledgeBaseRemoteSharePointActivityArguments.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseRemoteSharePointActivityRecord deserializedKnowledgeBaseRemoteSharePointActivityRecord - = new KnowledgeBaseRemoteSharePointActivityRecord(id); - deserializedKnowledgeBaseRemoteSharePointActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseRemoteSharePointActivityRecord.setError(error); - deserializedKnowledgeBaseRemoteSharePointActivityRecord.setKnowledgeSourceName(knowledgeSourceName); - deserializedKnowledgeBaseRemoteSharePointActivityRecord.setQueryTime(queryTime); - deserializedKnowledgeBaseRemoteSharePointActivityRecord.setCount(count); - deserializedKnowledgeBaseRemoteSharePointActivityRecord.type = type; - deserializedKnowledgeBaseRemoteSharePointActivityRecord.remoteSharePointArguments - = remoteSharePointArguments; - - return deserializedKnowledgeBaseRemoteSharePointActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointReference.java index ff62e6e10700..1d856d088882 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointReference.java @@ -1,31 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** * Represents a remote SharePoint document reference. */ -@Fluent +@Immutable public final class KnowledgeBaseRemoteSharePointReference extends KnowledgeBaseReference { + /* * The type of the reference. */ @Generated - private String type = "remoteSharePoint"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.REMOTE_SHARE_POINT; /* * The url the reference data originated from. @@ -34,36 +30,36 @@ public final class KnowledgeBaseRemoteSharePointReference extends KnowledgeBaseR private String webUrl; /* - * Information about the sensitivity label applied to a SharePoint document. + * Information about the sensitivity label applied to the SharePoint document. */ @Generated private SharePointSensitivityLabelInfo searchSensitivityLabelInfo; /** * Creates an instance of KnowledgeBaseRemoteSharePointReference class. - * + * * @param id the id value to set. * @param activitySource the activitySource value to set. */ @Generated - public KnowledgeBaseRemoteSharePointReference(String id, int activitySource) { + private KnowledgeBaseRemoteSharePointReference(String id, int activitySource) { super(id, activitySource); } /** * Get the type property: The type of the reference. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseReferenceType getType() { return this.type; } /** * Get the webUrl property: The url the reference data originated from. - * + * * @return the webUrl value. */ @Generated @@ -72,21 +68,9 @@ public String getWebUrl() { } /** - * Set the webUrl property: The url the reference data originated from. - * - * @param webUrl the webUrl value to set. - * @return the KnowledgeBaseRemoteSharePointReference object itself. - */ - @Generated - public KnowledgeBaseRemoteSharePointReference setWebUrl(String webUrl) { - this.webUrl = webUrl; - return this; - } - - /** - * Get the searchSensitivityLabelInfo property: Information about the sensitivity label applied to a SharePoint + * Get the searchSensitivityLabelInfo property: Information about the sensitivity label applied to the SharePoint * document. - * + * * @return the searchSensitivityLabelInfo value. */ @Generated @@ -94,40 +78,6 @@ public SharePointSensitivityLabelInfo getSearchSensitivityLabelInfo() { return this.searchSensitivityLabelInfo; } - /** - * Set the searchSensitivityLabelInfo property: Information about the sensitivity label applied to a SharePoint - * document. - * - * @param searchSensitivityLabelInfo the searchSensitivityLabelInfo value to set. - * @return the KnowledgeBaseRemoteSharePointReference object itself. - */ - @Generated - public KnowledgeBaseRemoteSharePointReference - setSearchSensitivityLabelInfo(SharePointSensitivityLabelInfo searchSensitivityLabelInfo) { - this.searchSensitivityLabelInfo = searchSensitivityLabelInfo; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointReference setSourceData(Map sourceData) { - super.setSourceData(sourceData); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRemoteSharePointReference setRerankerScore(Float rerankerScore) { - super.setRerankerScore(rerankerScore); - return this; - } - /** * {@inheritDoc} */ @@ -139,7 +89,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("activitySource", getActivitySource()); jsonWriter.writeMapField("sourceData", getSourceData(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", getRerankerScore()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("webUrl", this.webUrl); jsonWriter.writeJsonField("searchSensitivityLabelInfo", this.searchSensitivityLabelInfo); return jsonWriter.writeEndObject(); @@ -147,7 +97,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseRemoteSharePointReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseRemoteSharePointReference if the JsonReader was pointing to an instance of * it, or null if it was pointing to JSON null. @@ -157,31 +107,26 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseRemoteSharePointReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; Map sourceData = null; Float rerankerScore = null; - String type = "remoteSharePoint"; + KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.REMOTE_SHARE_POINT; String webUrl = null; SharePointSensitivityLabelInfo searchSensitivityLabelInfo = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getFloat); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("webUrl".equals(fieldName)) { webUrl = reader.getString(); } else if ("searchSensitivityLabelInfo".equals(fieldName)) { @@ -190,28 +135,14 @@ public static KnowledgeBaseRemoteSharePointReference fromJson(JsonReader jsonRea reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseRemoteSharePointReference deserializedKnowledgeBaseRemoteSharePointReference - = new KnowledgeBaseRemoteSharePointReference(id, activitySource); - deserializedKnowledgeBaseRemoteSharePointReference.setSourceData(sourceData); - deserializedKnowledgeBaseRemoteSharePointReference.setRerankerScore(rerankerScore); - deserializedKnowledgeBaseRemoteSharePointReference.type = type; - deserializedKnowledgeBaseRemoteSharePointReference.webUrl = webUrl; - deserializedKnowledgeBaseRemoteSharePointReference.searchSensitivityLabelInfo - = searchSensitivityLabelInfo; - - return deserializedKnowledgeBaseRemoteSharePointReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseRemoteSharePointReference deserializedKnowledgeBaseRemoteSharePointReference + = new KnowledgeBaseRemoteSharePointReference(id, activitySource); + deserializedKnowledgeBaseRemoteSharePointReference.setSourceData(sourceData); + deserializedKnowledgeBaseRemoteSharePointReference.setRerankerScore(rerankerScore); + deserializedKnowledgeBaseRemoteSharePointReference.type = type; + deserializedKnowledgeBaseRemoteSharePointReference.webUrl = webUrl; + deserializedKnowledgeBaseRemoteSharePointReference.searchSensitivityLabelInfo = searchSensitivityLabelInfo; + return deserializedKnowledgeBaseRemoteSharePointReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalActivityRecord.java deleted file mode 100644 index 787719f10d0e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalActivityRecord.java +++ /dev/null @@ -1,270 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a retrieval activity record. - */ -@Fluent -public class KnowledgeBaseRetrievalActivityRecord extends KnowledgeBaseActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "KnowledgeBaseRetrievalActivityRecord"; - - /* - * The knowledge source for the retrieval activity. - */ - @Generated - private String knowledgeSourceName; - - /* - * The query time for this retrieval activity. - */ - @Generated - private OffsetDateTime queryTime; - - /* - * The count of documents retrieved that were sufficiently relevant to pass the reranker threshold. - */ - @Generated - private Integer count; - - /** - * Creates an instance of KnowledgeBaseRetrievalActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseRetrievalActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the knowledgeSourceName property: The knowledge source for the retrieval activity. - * - * @return the knowledgeSourceName value. - */ - @Generated - public String getKnowledgeSourceName() { - return this.knowledgeSourceName; - } - - /** - * Set the knowledgeSourceName property: The knowledge source for the retrieval activity. - * - * @param knowledgeSourceName the knowledgeSourceName value to set. - * @return the KnowledgeBaseRetrievalActivityRecord object itself. - */ - @Generated - public KnowledgeBaseRetrievalActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - this.knowledgeSourceName = knowledgeSourceName; - return this; - } - - /** - * Get the queryTime property: The query time for this retrieval activity. - * - * @return the queryTime value. - */ - @Generated - public OffsetDateTime getQueryTime() { - return this.queryTime; - } - - /** - * Set the queryTime property: The query time for this retrieval activity. - * - * @param queryTime the queryTime value to set. - * @return the KnowledgeBaseRetrievalActivityRecord object itself. - */ - @Generated - public KnowledgeBaseRetrievalActivityRecord setQueryTime(OffsetDateTime queryTime) { - this.queryTime = queryTime; - return this; - } - - /** - * Get the count property: The count of documents retrieved that were sufficiently relevant to pass the reranker - * threshold. - * - * @return the count value. - */ - @Generated - public Integer getCount() { - return this.count; - } - - /** - * Set the count property: The count of documents retrieved that were sufficiently relevant to pass the reranker - * threshold. - * - * @param count the count value to set. - * @return the KnowledgeBaseRetrievalActivityRecord object itself. - */ - @Generated - public KnowledgeBaseRetrievalActivityRecord setCount(Integer count) { - this.count = count; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRetrievalActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseRetrievalActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeStringField("knowledgeSourceName", this.knowledgeSourceName); - jsonWriter.writeStringField("queryTime", - this.queryTime == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.queryTime)); - jsonWriter.writeNumberField("count", this.count); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseRetrievalActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseRetrievalActivityRecord 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 KnowledgeBaseRetrievalActivityRecord. - */ - @Generated - public static KnowledgeBaseRetrievalActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - String discriminatorValue = null; - try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading - while (readerToUse.nextToken() != JsonToken.END_OBJECT) { - String fieldName = readerToUse.getFieldName(); - readerToUse.nextToken(); - if ("type".equals(fieldName)) { - discriminatorValue = readerToUse.getString(); - break; - } else { - readerToUse.skipChildren(); - } - } - // Use the discriminator value to determine which subtype should be deserialized. - if ("searchIndex".equals(discriminatorValue)) { - return KnowledgeBaseSearchIndexActivityRecord.fromJson(readerToUse.reset()); - } else if ("azureBlob".equals(discriminatorValue)) { - return KnowledgeBaseAzureBlobActivityRecord.fromJson(readerToUse.reset()); - } else if ("indexedSharePoint".equals(discriminatorValue)) { - return KnowledgeBaseIndexedSharePointActivityRecord.fromJson(readerToUse.reset()); - } else if ("indexedOneLake".equals(discriminatorValue)) { - return KnowledgeBaseIndexedOneLakeActivityRecord.fromJson(readerToUse.reset()); - } else if ("web".equals(discriminatorValue)) { - return KnowledgeBaseWebActivityRecord.fromJson(readerToUse.reset()); - } else if ("remoteSharePoint".equals(discriminatorValue)) { - return KnowledgeBaseRemoteSharePointActivityRecord.fromJson(readerToUse.reset()); - } else { - return fromJsonKnownDiscriminator(readerToUse.reset()); - } - } - }); - } - - @Generated - static KnowledgeBaseRetrievalActivityRecord fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String type = "KnowledgeBaseRetrievalActivityRecord"; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseRetrievalActivityRecord deserializedKnowledgeBaseRetrievalActivityRecord - = new KnowledgeBaseRetrievalActivityRecord(id); - deserializedKnowledgeBaseRetrievalActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseRetrievalActivityRecord.setError(error); - deserializedKnowledgeBaseRetrievalActivityRecord.type = type; - deserializedKnowledgeBaseRetrievalActivityRecord.knowledgeSourceName = knowledgeSourceName; - deserializedKnowledgeBaseRetrievalActivityRecord.queryTime = queryTime; - deserializedKnowledgeBaseRetrievalActivityRecord.count = count; - - return deserializedKnowledgeBaseRetrievalActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalRequest.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalRequest.java index d70277aed09c..44c53c0b1786 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalRequest.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalRequest.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -13,6 +10,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +18,7 @@ */ @Fluent public final class KnowledgeBaseRetrievalRequest implements JsonSerializable { + /* * A list of chat message style input. */ @@ -45,7 +44,7 @@ public final class KnowledgeBaseRetrievalRequest implements JsonSerializable getMessages() { /** * Set the messages property: A list of chat message style input. - * + * + * @param messages the messages value to set. + * @return the KnowledgeBaseRetrievalRequest object itself. + */ + public KnowledgeBaseRetrievalRequest setMessages(KnowledgeBaseMessage... messages) { + this.messages = (messages == null) ? null : Arrays.asList(messages); + return this; + } + + /** + * Set the messages property: A list of chat message style input. + * * @param messages the messages value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -99,7 +109,7 @@ public KnowledgeBaseRetrievalRequest setMessages(List mess /** * Get the intents property: A list of intended queries to execute without model query planning. - * + * * @return the intents value. */ @Generated @@ -109,7 +119,18 @@ public List getIntents() { /** * Set the intents property: A list of intended queries to execute without model query planning. - * + * + * @param intents the intents value to set. + * @return the KnowledgeBaseRetrievalRequest object itself. + */ + public KnowledgeBaseRetrievalRequest setIntents(KnowledgeRetrievalIntent... intents) { + this.intents = (intents == null) ? null : Arrays.asList(intents); + return this; + } + + /** + * Set the intents property: A list of intended queries to execute without model query planning. + * * @param intents the intents value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -121,7 +142,7 @@ public KnowledgeBaseRetrievalRequest setIntents(List i /** * Get the maxRuntimeInSeconds property: The maximum runtime in seconds. - * + * * @return the maxRuntimeInSeconds value. */ @Generated @@ -131,7 +152,7 @@ public Integer getMaxRuntimeInSeconds() { /** * Set the maxRuntimeInSeconds property: The maximum runtime in seconds. - * + * * @param maxRuntimeInSeconds the maxRuntimeInSeconds value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -143,7 +164,7 @@ public KnowledgeBaseRetrievalRequest setMaxRuntimeInSeconds(Integer maxRuntimeIn /** * Get the maxOutputSize property: Limits the maximum size of the content in the output. - * + * * @return the maxOutputSize value. */ @Generated @@ -153,7 +174,7 @@ public Integer getMaxOutputSize() { /** * Set the maxOutputSize property: Limits the maximum size of the content in the output. - * + * * @param maxOutputSize the maxOutputSize value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -164,8 +185,8 @@ public KnowledgeBaseRetrievalRequest setMaxOutputSize(Integer maxOutputSize) { } /** - * Get the retrievalReasoningEffort property: The retrievalReasoningEffort property. - * + * Get the retrievalReasoningEffort property: The retrieval reasoning effort configuration. + * * @return the retrievalReasoningEffort value. */ @Generated @@ -174,8 +195,8 @@ public KnowledgeRetrievalReasoningEffort getRetrievalReasoningEffort() { } /** - * Set the retrievalReasoningEffort property: The retrievalReasoningEffort property. - * + * Set the retrievalReasoningEffort property: The retrieval reasoning effort configuration. + * * @param retrievalReasoningEffort the retrievalReasoningEffort value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -188,7 +209,7 @@ public KnowledgeRetrievalReasoningEffort getRetrievalReasoningEffort() { /** * Get the includeActivity property: Indicates retrieval results should include activity information. - * + * * @return the includeActivity value. */ @Generated @@ -198,7 +219,7 @@ public Boolean isIncludeActivity() { /** * Set the includeActivity property: Indicates retrieval results should include activity information. - * + * * @param includeActivity the includeActivity value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -210,7 +231,7 @@ public KnowledgeBaseRetrievalRequest setIncludeActivity(Boolean includeActivity) /** * Get the outputMode property: The output configuration for this retrieval. - * + * * @return the outputMode value. */ @Generated @@ -220,7 +241,7 @@ public KnowledgeRetrievalOutputMode getOutputMode() { /** * Set the outputMode property: The output configuration for this retrieval. - * + * * @param outputMode the outputMode value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -232,7 +253,7 @@ public KnowledgeBaseRetrievalRequest setOutputMode(KnowledgeRetrievalOutputMode /** * Get the knowledgeSourceParams property: A list of runtime parameters for the knowledge sources. - * + * * @return the knowledgeSourceParams value. */ @Generated @@ -242,7 +263,7 @@ public List getKnowledgeSourceParams() { /** * Set the knowledgeSourceParams property: A list of runtime parameters for the knowledge sources. - * + * * @param knowledgeSourceParams the knowledgeSourceParams value to set. * @return the KnowledgeBaseRetrievalRequest object itself. */ @@ -273,7 +294,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseRetrievalRequest from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseRetrievalRequest if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -287,7 +308,6 @@ public static KnowledgeBaseRetrievalRequest fromJson(JsonReader jsonReader) thro while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("messages".equals(fieldName)) { List messages = reader.readArray(reader1 -> KnowledgeBaseMessage.fromJson(reader1)); @@ -318,7 +338,6 @@ public static KnowledgeBaseRetrievalRequest fromJson(JsonReader jsonReader) thro reader.skipChildren(); } } - return deserializedKnowledgeBaseRetrievalRequest; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalResponse.java index ae6afe0c2aaf..5a80fef6338a 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalResponse.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalResponse.java @@ -1,13 +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.knowledgebases.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; @@ -18,10 +15,11 @@ /** * The output contract for the retrieval response. */ -@Fluent +@Immutable public final class KnowledgeBaseRetrievalResponse implements JsonSerializable { + /* - * The response property. + * The response messages. */ @Generated private List response; @@ -42,12 +40,12 @@ public final class KnowledgeBaseRetrievalResponse implements JsonSerializable getResponse() { return this.response; } - /** - * Set the response property: The response property. - * - * @param response the response value to set. - * @return the KnowledgeBaseRetrievalResponse object itself. - */ - @Generated - public KnowledgeBaseRetrievalResponse setResponse(List response) { - this.response = response; - return this; - } - /** * Get the activity property: The activity records for tracking progress and billing implications. - * + * * @return the activity value. */ @Generated @@ -77,21 +63,9 @@ public List getActivity() { return this.activity; } - /** - * Set the activity property: The activity records for tracking progress and billing implications. - * - * @param activity the activity value to set. - * @return the KnowledgeBaseRetrievalResponse object itself. - */ - @Generated - public KnowledgeBaseRetrievalResponse setActivity(List activity) { - this.activity = activity; - return this; - } - /** * Get the references property: The references for the retrieval data used in the response. - * + * * @return the references value. */ @Generated @@ -99,18 +73,6 @@ public List getReferences() { return this.references; } - /** - * Set the references property: The references for the retrieval data used in the response. - * - * @param references the references value to set. - * @return the KnowledgeBaseRetrievalResponse object itself. - */ - @Generated - public KnowledgeBaseRetrievalResponse setReferences(List references) { - this.references = references; - return this; - } - /** * {@inheritDoc} */ @@ -126,7 +88,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseRetrievalResponse from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseRetrievalResponse if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -140,7 +102,6 @@ public static KnowledgeBaseRetrievalResponse fromJson(JsonReader jsonReader) thr while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("response".equals(fieldName)) { List response = reader.readArray(reader1 -> KnowledgeBaseMessage.fromJson(reader1)); @@ -157,7 +118,6 @@ public static KnowledgeBaseRetrievalResponse fromJson(JsonReader jsonReader) thr reader.skipChildren(); } } - return deserializedKnowledgeBaseRetrievalResponse; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexActivityArguments.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexActivityArguments.java deleted file mode 100644 index fb9da0f78574..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexActivityArguments.java +++ /dev/null @@ -1,228 +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.knowledgebases.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 the arguments the search index retrieval activity was run with. - */ -@Fluent -public final class KnowledgeBaseSearchIndexActivityArguments - implements JsonSerializable { - /* - * The search string used to query the search index. - */ - @Generated - private String search; - - /* - * The filter string. - */ - @Generated - private String filter; - - /* - * What fields were selected for search. - */ - @Generated - private List sourceDataFields; - - /* - * What fields were searched against. - */ - @Generated - private List searchFields; - - /* - * What semantic configuration was used from the search index. - */ - @Generated - private String semanticConfigurationName; - - /** - * Creates an instance of KnowledgeBaseSearchIndexActivityArguments class. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments() { - } - - /** - * Get the search property: The search string used to query the search index. - * - * @return the search value. - */ - @Generated - public String getSearch() { - return this.search; - } - - /** - * Set the search property: The search string used to query the search index. - * - * @param search the search value to set. - * @return the KnowledgeBaseSearchIndexActivityArguments object itself. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments setSearch(String search) { - this.search = search; - return this; - } - - /** - * Get the filter property: The filter string. - * - * @return the filter value. - */ - @Generated - public String getFilter() { - return this.filter; - } - - /** - * Set the filter property: The filter string. - * - * @param filter the filter value to set. - * @return the KnowledgeBaseSearchIndexActivityArguments object itself. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments setFilter(String filter) { - this.filter = filter; - return this; - } - - /** - * Get the sourceDataFields property: What fields were selected for search. - * - * @return the sourceDataFields value. - */ - @Generated - public List getSourceDataFields() { - return this.sourceDataFields; - } - - /** - * Set the sourceDataFields property: What fields were selected for search. - * - * @param sourceDataFields the sourceDataFields value to set. - * @return the KnowledgeBaseSearchIndexActivityArguments object itself. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments - setSourceDataFields(List sourceDataFields) { - this.sourceDataFields = sourceDataFields; - return this; - } - - /** - * Get the searchFields property: What fields were searched against. - * - * @return the searchFields value. - */ - @Generated - public List getSearchFields() { - return this.searchFields; - } - - /** - * Set the searchFields property: What fields were searched against. - * - * @param searchFields the searchFields value to set. - * @return the KnowledgeBaseSearchIndexActivityArguments object itself. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments setSearchFields(List searchFields) { - this.searchFields = searchFields; - return this; - } - - /** - * Get the semanticConfigurationName property: What semantic configuration was used from the search index. - * - * @return the semanticConfigurationName value. - */ - @Generated - public String getSemanticConfigurationName() { - return this.semanticConfigurationName; - } - - /** - * Set the semanticConfigurationName property: What semantic configuration was used from the search index. - * - * @param semanticConfigurationName the semanticConfigurationName value to set. - * @return the KnowledgeBaseSearchIndexActivityArguments object itself. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments setSemanticConfigurationName(String semanticConfigurationName) { - this.semanticConfigurationName = semanticConfigurationName; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("search", this.search); - jsonWriter.writeStringField("filter", this.filter); - jsonWriter.writeArrayField("sourceDataFields", this.sourceDataFields, - (writer, element) -> writer.writeJson(element)); - jsonWriter.writeArrayField("searchFields", this.searchFields, (writer, element) -> writer.writeJson(element)); - jsonWriter.writeStringField("semanticConfigurationName", this.semanticConfigurationName); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseSearchIndexActivityArguments from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseSearchIndexActivityArguments 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 KnowledgeBaseSearchIndexActivityArguments. - */ - @Generated - public static KnowledgeBaseSearchIndexActivityArguments fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeBaseSearchIndexActivityArguments deserializedKnowledgeBaseSearchIndexActivityArguments - = new KnowledgeBaseSearchIndexActivityArguments(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("search".equals(fieldName)) { - deserializedKnowledgeBaseSearchIndexActivityArguments.search = reader.getString(); - } else if ("filter".equals(fieldName)) { - deserializedKnowledgeBaseSearchIndexActivityArguments.filter = reader.getString(); - } else if ("sourceDataFields".equals(fieldName)) { - List sourceDataFields - = reader.readArray(reader1 -> SearchIndexFieldReference.fromJson(reader1)); - deserializedKnowledgeBaseSearchIndexActivityArguments.sourceDataFields = sourceDataFields; - } else if ("searchFields".equals(fieldName)) { - List searchFields - = reader.readArray(reader1 -> SearchIndexFieldReference.fromJson(reader1)); - deserializedKnowledgeBaseSearchIndexActivityArguments.searchFields = searchFields; - } else if ("semanticConfigurationName".equals(fieldName)) { - deserializedKnowledgeBaseSearchIndexActivityArguments.semanticConfigurationName - = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeBaseSearchIndexActivityArguments; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexActivityRecord.java deleted file mode 100644 index de93e5830c86..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexActivityRecord.java +++ /dev/null @@ -1,212 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a search index retrieval activity record. - */ -@Fluent -public final class KnowledgeBaseSearchIndexActivityRecord extends KnowledgeBaseRetrievalActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "searchIndex"; - - /* - * The search index arguments for the retrieval activity. - */ - @Generated - private KnowledgeBaseSearchIndexActivityArguments searchIndexArguments; - - /** - * Creates an instance of KnowledgeBaseSearchIndexActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseSearchIndexActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the searchIndexArguments property: The search index arguments for the retrieval activity. - * - * @return the searchIndexArguments value. - */ - @Generated - public KnowledgeBaseSearchIndexActivityArguments getSearchIndexArguments() { - return this.searchIndexArguments; - } - - /** - * Set the searchIndexArguments property: The search index arguments for the retrieval activity. - * - * @param searchIndexArguments the searchIndexArguments value to set. - * @return the KnowledgeBaseSearchIndexActivityRecord object itself. - */ - @Generated - public KnowledgeBaseSearchIndexActivityRecord - setSearchIndexArguments(KnowledgeBaseSearchIndexActivityArguments searchIndexArguments) { - this.searchIndexArguments = searchIndexArguments; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - super.setKnowledgeSourceName(knowledgeSourceName); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexActivityRecord setQueryTime(OffsetDateTime queryTime) { - super.setQueryTime(queryTime); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexActivityRecord setCount(Integer count) { - super.setCount(count); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("knowledgeSourceName", getKnowledgeSourceName()); - jsonWriter.writeStringField("queryTime", - getQueryTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getQueryTime())); - jsonWriter.writeNumberField("count", getCount()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("searchIndexArguments", this.searchIndexArguments); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseSearchIndexActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseSearchIndexActivityRecord 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 KnowledgeBaseSearchIndexActivityRecord. - */ - @Generated - public static KnowledgeBaseSearchIndexActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - String type = "searchIndex"; - KnowledgeBaseSearchIndexActivityArguments searchIndexArguments = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("searchIndexArguments".equals(fieldName)) { - searchIndexArguments = KnowledgeBaseSearchIndexActivityArguments.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseSearchIndexActivityRecord deserializedKnowledgeBaseSearchIndexActivityRecord - = new KnowledgeBaseSearchIndexActivityRecord(id); - deserializedKnowledgeBaseSearchIndexActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseSearchIndexActivityRecord.setError(error); - deserializedKnowledgeBaseSearchIndexActivityRecord.setKnowledgeSourceName(knowledgeSourceName); - deserializedKnowledgeBaseSearchIndexActivityRecord.setQueryTime(queryTime); - deserializedKnowledgeBaseSearchIndexActivityRecord.setCount(count); - deserializedKnowledgeBaseSearchIndexActivityRecord.type = type; - deserializedKnowledgeBaseSearchIndexActivityRecord.searchIndexArguments = searchIndexArguments; - - return deserializedKnowledgeBaseSearchIndexActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexReference.java index c46cfdd9ca45..520592aec95d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexReference.java @@ -1,31 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** * Represents an Azure Search document reference. */ -@Fluent +@Immutable public final class KnowledgeBaseSearchIndexReference extends KnowledgeBaseReference { + /* * The type of the reference. */ @Generated - private String type = "searchIndex"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.SEARCH_INDEX; /* * The document key for the reference. @@ -35,29 +31,29 @@ public final class KnowledgeBaseSearchIndexReference extends KnowledgeBaseRefere /** * Creates an instance of KnowledgeBaseSearchIndexReference class. - * + * * @param id the id value to set. * @param activitySource the activitySource value to set. */ @Generated - public KnowledgeBaseSearchIndexReference(String id, int activitySource) { + private KnowledgeBaseSearchIndexReference(String id, int activitySource) { super(id, activitySource); } /** * Get the type property: The type of the reference. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseReferenceType getType() { return this.type; } /** * Get the docKey property: The document key for the reference. - * + * * @return the docKey value. */ @Generated @@ -65,38 +61,6 @@ public String getDocKey() { return this.docKey; } - /** - * Set the docKey property: The document key for the reference. - * - * @param docKey the docKey value to set. - * @return the KnowledgeBaseSearchIndexReference object itself. - */ - @Generated - public KnowledgeBaseSearchIndexReference setDocKey(String docKey) { - this.docKey = docKey; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexReference setSourceData(Map sourceData) { - super.setSourceData(sourceData); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseSearchIndexReference setRerankerScore(Float rerankerScore) { - super.setRerankerScore(rerankerScore); - return this; - } - /** * {@inheritDoc} */ @@ -108,14 +72,14 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("activitySource", getActivitySource()); jsonWriter.writeMapField("sourceData", getSourceData(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", getRerankerScore()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("docKey", this.docKey); return jsonWriter.writeEndObject(); } /** * Reads an instance of KnowledgeBaseSearchIndexReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseSearchIndexReference if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -125,56 +89,38 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseSearchIndexReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; Map sourceData = null; Float rerankerScore = null; - String type = "searchIndex"; + KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.SEARCH_INDEX; String docKey = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getFloat); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("docKey".equals(fieldName)) { docKey = reader.getString(); } else { reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseSearchIndexReference deserializedKnowledgeBaseSearchIndexReference - = new KnowledgeBaseSearchIndexReference(id, activitySource); - deserializedKnowledgeBaseSearchIndexReference.setSourceData(sourceData); - deserializedKnowledgeBaseSearchIndexReference.setRerankerScore(rerankerScore); - deserializedKnowledgeBaseSearchIndexReference.type = type; - deserializedKnowledgeBaseSearchIndexReference.docKey = docKey; - - return deserializedKnowledgeBaseSearchIndexReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseSearchIndexReference deserializedKnowledgeBaseSearchIndexReference + = new KnowledgeBaseSearchIndexReference(id, activitySource); + deserializedKnowledgeBaseSearchIndexReference.setSourceData(sourceData); + deserializedKnowledgeBaseSearchIndexReference.setRerankerScore(rerankerScore); + deserializedKnowledgeBaseSearchIndexReference.type = type; + deserializedKnowledgeBaseSearchIndexReference.docKey = docKey; + return deserializedKnowledgeBaseSearchIndexReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebActivityArguments.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebActivityArguments.java deleted file mode 100644 index 6913ad0a4d09..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebActivityArguments.java +++ /dev/null @@ -1,219 +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.knowledgebases.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; - -/** - * Represents the arguments the web retrieval activity was run with. - */ -@Fluent -public final class KnowledgeBaseWebActivityArguments implements JsonSerializable { - /* - * The search string used to query the web. - */ - @Generated - private String search; - - /* - * The language for the retrieval activity. - */ - @Generated - private String language; - - /* - * The market for the retrieval activity. - */ - @Generated - private String market; - - /* - * The number of web results returned. - */ - @Generated - private Integer count; - - /* - * The freshness for the retrieval activity. - */ - @Generated - private String freshness; - - /** - * Creates an instance of KnowledgeBaseWebActivityArguments class. - */ - @Generated - public KnowledgeBaseWebActivityArguments() { - } - - /** - * Get the search property: The search string used to query the web. - * - * @return the search value. - */ - @Generated - public String getSearch() { - return this.search; - } - - /** - * Set the search property: The search string used to query the web. - * - * @param search the search value to set. - * @return the KnowledgeBaseWebActivityArguments object itself. - */ - @Generated - public KnowledgeBaseWebActivityArguments setSearch(String search) { - this.search = search; - return this; - } - - /** - * Get the language property: The language for the retrieval activity. - * - * @return the language value. - */ - @Generated - public String getLanguage() { - return this.language; - } - - /** - * Set the language property: The language for the retrieval activity. - * - * @param language the language value to set. - * @return the KnowledgeBaseWebActivityArguments object itself. - */ - @Generated - public KnowledgeBaseWebActivityArguments setLanguage(String language) { - this.language = language; - return this; - } - - /** - * Get the market property: The market for the retrieval activity. - * - * @return the market value. - */ - @Generated - public String getMarket() { - return this.market; - } - - /** - * Set the market property: The market for the retrieval activity. - * - * @param market the market value to set. - * @return the KnowledgeBaseWebActivityArguments object itself. - */ - @Generated - public KnowledgeBaseWebActivityArguments setMarket(String market) { - this.market = market; - return this; - } - - /** - * Get the count property: The number of web results returned. - * - * @return the count value. - */ - @Generated - public Integer getCount() { - return this.count; - } - - /** - * Set the count property: The number of web results returned. - * - * @param count the count value to set. - * @return the KnowledgeBaseWebActivityArguments object itself. - */ - @Generated - public KnowledgeBaseWebActivityArguments setCount(Integer count) { - this.count = count; - return this; - } - - /** - * Get the freshness property: The freshness for the retrieval activity. - * - * @return the freshness value. - */ - @Generated - public String getFreshness() { - return this.freshness; - } - - /** - * Set the freshness property: The freshness for the retrieval activity. - * - * @param freshness the freshness value to set. - * @return the KnowledgeBaseWebActivityArguments object itself. - */ - @Generated - public KnowledgeBaseWebActivityArguments setFreshness(String freshness) { - this.freshness = freshness; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("search", this.search); - jsonWriter.writeStringField("language", this.language); - jsonWriter.writeStringField("market", this.market); - jsonWriter.writeNumberField("count", this.count); - jsonWriter.writeStringField("freshness", this.freshness); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseWebActivityArguments from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseWebActivityArguments 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 KnowledgeBaseWebActivityArguments. - */ - @Generated - public static KnowledgeBaseWebActivityArguments fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - KnowledgeBaseWebActivityArguments deserializedKnowledgeBaseWebActivityArguments - = new KnowledgeBaseWebActivityArguments(); - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("search".equals(fieldName)) { - deserializedKnowledgeBaseWebActivityArguments.search = reader.getString(); - } else if ("language".equals(fieldName)) { - deserializedKnowledgeBaseWebActivityArguments.language = reader.getString(); - } else if ("market".equals(fieldName)) { - deserializedKnowledgeBaseWebActivityArguments.market = reader.getString(); - } else if ("count".equals(fieldName)) { - deserializedKnowledgeBaseWebActivityArguments.count = reader.getNullable(JsonReader::getInt); - } else if ("freshness".equals(fieldName)) { - deserializedKnowledgeBaseWebActivityArguments.freshness = reader.getString(); - } else { - reader.skipChildren(); - } - } - - return deserializedKnowledgeBaseWebActivityArguments; - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebActivityRecord.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebActivityRecord.java deleted file mode 100644 index 29efcdf59d28..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebActivityRecord.java +++ /dev/null @@ -1,211 +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.knowledgebases.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.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -/** - * Represents a web retrieval activity record. - */ -@Fluent -public final class KnowledgeBaseWebActivityRecord extends KnowledgeBaseRetrievalActivityRecord { - /* - * The type of the activity record. - */ - @Generated - private String type = "web"; - - /* - * The web arguments for the retrieval activity. - */ - @Generated - private KnowledgeBaseWebActivityArguments webArguments; - - /** - * Creates an instance of KnowledgeBaseWebActivityRecord class. - * - * @param id the id value to set. - */ - @Generated - public KnowledgeBaseWebActivityRecord(int id) { - super(id); - } - - /** - * Get the type property: The type of the activity record. - * - * @return the type value. - */ - @Generated - @Override - public String getType() { - return this.type; - } - - /** - * Get the webArguments property: The web arguments for the retrieval activity. - * - * @return the webArguments value. - */ - @Generated - public KnowledgeBaseWebActivityArguments getWebArguments() { - return this.webArguments; - } - - /** - * Set the webArguments property: The web arguments for the retrieval activity. - * - * @param webArguments the webArguments value to set. - * @return the KnowledgeBaseWebActivityRecord object itself. - */ - @Generated - public KnowledgeBaseWebActivityRecord setWebArguments(KnowledgeBaseWebActivityArguments webArguments) { - this.webArguments = webArguments; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebActivityRecord setKnowledgeSourceName(String knowledgeSourceName) { - super.setKnowledgeSourceName(knowledgeSourceName); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebActivityRecord setQueryTime(OffsetDateTime queryTime) { - super.setQueryTime(queryTime); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebActivityRecord setCount(Integer count) { - super.setCount(count); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebActivityRecord setElapsedMs(Integer elapsedMs) { - super.setElapsedMs(elapsedMs); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebActivityRecord setError(KnowledgeBaseErrorDetail error) { - super.setError(error); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeIntField("id", getId()); - jsonWriter.writeNumberField("elapsedMs", getElapsedMs()); - jsonWriter.writeJsonField("error", getError()); - jsonWriter.writeStringField("knowledgeSourceName", getKnowledgeSourceName()); - jsonWriter.writeStringField("queryTime", - getQueryTime() == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(getQueryTime())); - jsonWriter.writeNumberField("count", getCount()); - jsonWriter.writeStringField("type", this.type); - jsonWriter.writeJsonField("webArguments", this.webArguments); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of KnowledgeBaseWebActivityRecord from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of KnowledgeBaseWebActivityRecord 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 KnowledgeBaseWebActivityRecord. - */ - @Generated - public static KnowledgeBaseWebActivityRecord fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean idFound = false; - int id = 0; - Integer elapsedMs = null; - KnowledgeBaseErrorDetail error = null; - String knowledgeSourceName = null; - OffsetDateTime queryTime = null; - Integer count = null; - String type = "web"; - KnowledgeBaseWebActivityArguments webArguments = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("id".equals(fieldName)) { - id = reader.getInt(); - idFound = true; - } else if ("elapsedMs".equals(fieldName)) { - elapsedMs = reader.getNullable(JsonReader::getInt); - } else if ("error".equals(fieldName)) { - error = KnowledgeBaseErrorDetail.fromJson(reader); - } else if ("knowledgeSourceName".equals(fieldName)) { - knowledgeSourceName = reader.getString(); - } else if ("queryTime".equals(fieldName)) { - queryTime = reader - .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - } else if ("count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getInt); - } else if ("type".equals(fieldName)) { - type = reader.getString(); - } else if ("webArguments".equals(fieldName)) { - webArguments = KnowledgeBaseWebActivityArguments.fromJson(reader); - } else { - reader.skipChildren(); - } - } - if (idFound) { - KnowledgeBaseWebActivityRecord deserializedKnowledgeBaseWebActivityRecord - = new KnowledgeBaseWebActivityRecord(id); - deserializedKnowledgeBaseWebActivityRecord.setElapsedMs(elapsedMs); - deserializedKnowledgeBaseWebActivityRecord.setError(error); - deserializedKnowledgeBaseWebActivityRecord.setKnowledgeSourceName(knowledgeSourceName); - deserializedKnowledgeBaseWebActivityRecord.setQueryTime(queryTime); - deserializedKnowledgeBaseWebActivityRecord.setCount(count); - deserializedKnowledgeBaseWebActivityRecord.type = type; - deserializedKnowledgeBaseWebActivityRecord.webArguments = webArguments; - - return deserializedKnowledgeBaseWebActivityRecord; - } - throw new IllegalStateException("Missing required property: id"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebReference.java index 851354fb1908..5900a0b80e59 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebReference.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebReference.java @@ -1,31 +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.knowledgebases.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.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import java.util.Map; /** * Represents a web document reference. */ -@Fluent +@Immutable public final class KnowledgeBaseWebReference extends KnowledgeBaseReference { + /* * The type of the reference. */ @Generated - private String type = "web"; + private KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.WEB; /* * The url the reference data originated from. @@ -41,29 +37,29 @@ public final class KnowledgeBaseWebReference extends KnowledgeBaseReference { /** * Creates an instance of KnowledgeBaseWebReference class. - * + * * @param id the id value to set. * @param activitySource the activitySource value to set. */ @Generated - public KnowledgeBaseWebReference(String id, int activitySource) { + private KnowledgeBaseWebReference(String id, int activitySource) { super(id, activitySource); } /** * Get the type property: The type of the reference. - * + * * @return the type value. */ @Generated @Override - public String getType() { + public KnowledgeBaseReferenceType getType() { return this.type; } /** * Get the url property: The url the reference data originated from. - * + * * @return the url value. */ @Generated @@ -71,21 +67,9 @@ public String getUrl() { return this.url; } - /** - * Set the url property: The url the reference data originated from. - * - * @param url the url value to set. - * @return the KnowledgeBaseWebReference object itself. - */ - @Generated - public KnowledgeBaseWebReference setUrl(String url) { - this.url = url; - return this; - } - /** * Get the title property: The title of the web document. - * + * * @return the title value. */ @Generated @@ -93,38 +77,6 @@ public String getTitle() { return this.title; } - /** - * Set the title property: The title of the web document. - * - * @param title the title value to set. - * @return the KnowledgeBaseWebReference object itself. - */ - @Generated - public KnowledgeBaseWebReference setTitle(String title) { - this.title = title; - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebReference setSourceData(Map sourceData) { - super.setSourceData(sourceData); - return this; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public KnowledgeBaseWebReference setRerankerScore(Float rerankerScore) { - super.setRerankerScore(rerankerScore); - return this; - } - /** * {@inheritDoc} */ @@ -136,7 +88,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeIntField("activitySource", getActivitySource()); jsonWriter.writeMapField("sourceData", getSourceData(), (writer, element) -> writer.writeUntyped(element)); jsonWriter.writeNumberField("rerankerScore", getRerankerScore()); - jsonWriter.writeStringField("type", this.type); + jsonWriter.writeStringField("type", this.type == null ? null : this.type.toString()); jsonWriter.writeStringField("url", this.url); jsonWriter.writeStringField("title", this.title); return jsonWriter.writeEndObject(); @@ -144,7 +96,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeBaseWebReference from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeBaseWebReference if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -154,31 +106,26 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeBaseWebReference fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean idFound = false; String id = null; - boolean activitySourceFound = false; int activitySource = 0; Map sourceData = null; Float rerankerScore = null; - String type = "web"; + KnowledgeBaseReferenceType type = KnowledgeBaseReferenceType.WEB; String url = null; String title = null; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("id".equals(fieldName)) { id = reader.getString(); - idFound = true; } else if ("activitySource".equals(fieldName)) { activitySource = reader.getInt(); - activitySourceFound = true; } else if ("sourceData".equals(fieldName)) { sourceData = reader.readMap(reader1 -> reader1.readUntyped()); } else if ("rerankerScore".equals(fieldName)) { rerankerScore = reader.getNullable(JsonReader::getFloat); } else if ("type".equals(fieldName)) { - type = reader.getString(); + type = KnowledgeBaseReferenceType.fromString(reader.getString()); } else if ("url".equals(fieldName)) { url = reader.getString(); } else if ("title".equals(fieldName)) { @@ -187,27 +134,14 @@ public static KnowledgeBaseWebReference fromJson(JsonReader jsonReader) throws I reader.skipChildren(); } } - if (idFound && activitySourceFound) { - KnowledgeBaseWebReference deserializedKnowledgeBaseWebReference - = new KnowledgeBaseWebReference(id, activitySource); - deserializedKnowledgeBaseWebReference.setSourceData(sourceData); - deserializedKnowledgeBaseWebReference.setRerankerScore(rerankerScore); - deserializedKnowledgeBaseWebReference.type = type; - deserializedKnowledgeBaseWebReference.url = url; - deserializedKnowledgeBaseWebReference.title = title; - - return deserializedKnowledgeBaseWebReference; - } - List missingProperties = new ArrayList<>(); - if (!idFound) { - missingProperties.add("id"); - } - if (!activitySourceFound) { - missingProperties.add("activitySource"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + KnowledgeBaseWebReference deserializedKnowledgeBaseWebReference + = new KnowledgeBaseWebReference(id, activitySource); + deserializedKnowledgeBaseWebReference.setSourceData(sourceData); + deserializedKnowledgeBaseWebReference.setRerankerScore(rerankerScore); + deserializedKnowledgeBaseWebReference.type = type; + deserializedKnowledgeBaseWebReference.url = url; + deserializedKnowledgeBaseWebReference.title = title; + return deserializedKnowledgeBaseWebReference; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntent.java index 192547955044..7168a6829825 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntent.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntent.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -19,6 +16,7 @@ */ @Immutable public class KnowledgeRetrievalIntent implements JsonSerializable { + /* * The type of the intent. */ @@ -34,7 +32,7 @@ public KnowledgeRetrievalIntent() { /** * Get the type property: The type of the intent. - * + * * @return the type value. */ @Generated @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeRetrievalIntent from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeRetrievalIntent if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -66,7 +64,8 @@ public static KnowledgeRetrievalIntent fromJson(JsonReader jsonReader) throws IO return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -94,7 +93,6 @@ static KnowledgeRetrievalIntent fromJsonKnownDiscriminator(JsonReader jsonReader while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("type".equals(fieldName)) { deserializedKnowledgeRetrievalIntent.type = KnowledgeRetrievalIntentType.fromString(reader.getString()); @@ -102,7 +100,6 @@ static KnowledgeRetrievalIntent fromJsonKnownDiscriminator(JsonReader jsonReader reader.skipChildren(); } } - return deserializedKnowledgeRetrievalIntent; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntentType.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntentType.java index 963de3dfba20..1ed0c8d1ac10 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntentType.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntentType.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -14,6 +11,7 @@ * The kind of knowledge base configuration to use. */ public final class KnowledgeRetrievalIntentType extends ExpandableStringEnum { + /** * A natural language semantic query intent. */ @@ -22,7 +20,7 @@ public final class KnowledgeRetrievalIntentType extends ExpandableStringEnum { + /** * Return data from the knowledge sources directly without generative alteration. */ @@ -28,7 +26,7 @@ public final class KnowledgeRetrievalOutputMode extends ExpandableStringEnum { + /* * The kind of reasoning effort. */ @@ -35,7 +33,7 @@ public KnowledgeRetrievalReasoningEffort() { /** * Get the kind property: The kind of reasoning effort. - * + * * @return the kind value. */ @Generated @@ -56,7 +54,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeRetrievalReasoningEffort from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeRetrievalReasoningEffort if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -67,7 +65,8 @@ public static KnowledgeRetrievalReasoningEffort fromJson(JsonReader jsonReader) return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -100,7 +99,6 @@ static KnowledgeRetrievalReasoningEffort fromJsonKnownDiscriminator(JsonReader j while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kind".equals(fieldName)) { deserializedKnowledgeRetrievalReasoningEffort.kind = KnowledgeRetrievalReasoningEffortKind.fromString(reader.getString()); @@ -108,7 +106,6 @@ static KnowledgeRetrievalReasoningEffort fromJsonKnownDiscriminator(JsonReader j reader.skipChildren(); } } - return deserializedKnowledgeRetrievalReasoningEffort; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalReasoningEffortKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalReasoningEffortKind.java index 525a72329931..5daaeddf1cf0 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalReasoningEffortKind.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalReasoningEffortKind.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -15,6 +12,7 @@ */ public final class KnowledgeRetrievalReasoningEffortKind extends ExpandableStringEnum { + /** * Does not perform any source selections, query planning, or iterative search. */ @@ -35,7 +33,7 @@ public final class KnowledgeRetrievalReasoningEffortKind /** * Creates a new instance of KnowledgeRetrievalReasoningEffortKind value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -45,7 +43,7 @@ public KnowledgeRetrievalReasoningEffortKind() { /** * Creates or finds a KnowledgeRetrievalReasoningEffortKind from its string representation. - * + * * @param name a name to look for. * @return the corresponding KnowledgeRetrievalReasoningEffortKind. */ @@ -56,7 +54,7 @@ public static KnowledgeRetrievalReasoningEffortKind fromString(String name) { /** * Gets known KnowledgeRetrievalReasoningEffortKind values. - * + * * @return known KnowledgeRetrievalReasoningEffortKind values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalSemanticIntent.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalSemanticIntent.java index f872fd287aa0..d088a6150096 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalSemanticIntent.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalSemanticIntent.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Generated; @@ -14,10 +11,11 @@ import java.io.IOException; /** - * The KnowledgeRetrievalSemanticIntent model. + * A semantic query intent. */ @Immutable public final class KnowledgeRetrievalSemanticIntent extends KnowledgeRetrievalIntent { + /* * The type of the intent. */ @@ -32,7 +30,7 @@ public final class KnowledgeRetrievalSemanticIntent extends KnowledgeRetrievalIn /** * Creates an instance of KnowledgeRetrievalSemanticIntent class. - * + * * @param search the search value to set. */ @Generated @@ -42,7 +40,7 @@ public KnowledgeRetrievalSemanticIntent(String search) { /** * Get the type property: The type of the intent. - * + * * @return the type value. */ @Generated @@ -53,7 +51,7 @@ public KnowledgeRetrievalIntentType getType() { /** * Get the search property: The semantic query to execute. - * + * * @return the search value. */ @Generated @@ -75,7 +73,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeRetrievalSemanticIntent from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeRetrievalSemanticIntent if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -85,30 +83,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeRetrievalSemanticIntent fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean searchFound = false; String search = null; KnowledgeRetrievalIntentType type = KnowledgeRetrievalIntentType.SEMANTIC; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("search".equals(fieldName)) { search = reader.getString(); - searchFound = true; } else if ("type".equals(fieldName)) { type = KnowledgeRetrievalIntentType.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (searchFound) { - KnowledgeRetrievalSemanticIntent deserializedKnowledgeRetrievalSemanticIntent - = new KnowledgeRetrievalSemanticIntent(search); - deserializedKnowledgeRetrievalSemanticIntent.type = type; - - return deserializedKnowledgeRetrievalSemanticIntent; - } - throw new IllegalStateException("Missing required property: search"); + KnowledgeRetrievalSemanticIntent deserializedKnowledgeRetrievalSemanticIntent + = new KnowledgeRetrievalSemanticIntent(search); + deserializedKnowledgeRetrievalSemanticIntent.type = type; + return deserializedKnowledgeRetrievalSemanticIntent; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceAzureOpenAIVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceAzureOpenAIVectorizer.java similarity index 93% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceAzureOpenAIVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceAzureOpenAIVectorizer.java index ebf8a10b6b5b..e0d20cd9f2d9 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceAzureOpenAIVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceAzureOpenAIVectorizer.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.knowledgebases.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.AzureOpenAIVectorizerParameters; +import com.azure.search.documents.indexes.models.VectorSearchVectorizerKind; import java.io.IOException; /** @@ -18,6 +17,7 @@ */ @Fluent public final class KnowledgeSourceAzureOpenAIVectorizer extends KnowledgeSourceVectorizer { + /* * The name of the kind of vectorization method being configured for use with vector search. */ @@ -39,7 +39,7 @@ public KnowledgeSourceAzureOpenAIVectorizer() { /** * Get the kind property: The name of the kind of vectorization method being configured for use with vector search. - * + * * @return the kind value. */ @Generated @@ -50,7 +50,7 @@ public VectorSearchVectorizerKind getKind() { /** * Get the azureOpenAIParameters property: Contains the parameters specific to Azure OpenAI embedding vectorization. - * + * * @return the azureOpenAIParameters value. */ @Generated @@ -60,7 +60,7 @@ public AzureOpenAIVectorizerParameters getAzureOpenAIParameters() { /** * Set the azureOpenAIParameters property: Contains the parameters specific to Azure OpenAI embedding vectorization. - * + * * @param azureOpenAIParameters the azureOpenAIParameters value to set. * @return the KnowledgeSourceAzureOpenAIVectorizer object itself. */ @@ -85,7 +85,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeSourceAzureOpenAIVectorizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeSourceAzureOpenAIVectorizer if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -99,7 +99,6 @@ public static KnowledgeSourceAzureOpenAIVectorizer fromJson(JsonReader jsonReade while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kind".equals(fieldName)) { deserializedKnowledgeSourceAzureOpenAIVectorizer.kind = VectorSearchVectorizerKind.fromString(reader.getString()); @@ -110,7 +109,6 @@ public static KnowledgeSourceAzureOpenAIVectorizer fromJson(JsonReader jsonReade reader.skipChildren(); } } - return deserializedKnowledgeSourceAzureOpenAIVectorizer; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionParameters.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceIngestionParameters.java similarity index 90% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionParameters.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceIngestionParameters.java index 0ae36facf54b..c7dcd0bfb9fb 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionParameters.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceIngestionParameters.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.knowledgebases.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -12,7 +9,13 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.IndexingSchedule; +import com.azure.search.documents.indexes.models.KnowledgeBaseModel; +import com.azure.search.documents.indexes.models.KnowledgeSourceContentExtractionMode; +import com.azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption; +import com.azure.search.documents.indexes.models.SearchIndexerDataIdentity; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** @@ -20,6 +23,7 @@ */ @Fluent public final class KnowledgeSourceIngestionParameters implements JsonSerializable { + /* * An explicit identity to use for this knowledge source. */ @@ -78,7 +82,7 @@ public KnowledgeSourceIngestionParameters() { /** * Get the identity property: An explicit identity to use for this knowledge source. - * + * * @return the identity value. */ @Generated @@ -88,7 +92,7 @@ public SearchIndexerDataIdentity getIdentity() { /** * Set the identity property: An explicit identity to use for this knowledge source. - * + * * @param identity the identity value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -100,7 +104,7 @@ public KnowledgeSourceIngestionParameters setIdentity(SearchIndexerDataIdentity /** * Get the embeddingModel property: Optional vectorizer configuration for vectorizing content. - * + * * @return the embeddingModel value. */ @Generated @@ -110,7 +114,7 @@ public KnowledgeSourceVectorizer getEmbeddingModel() { /** * Set the embeddingModel property: Optional vectorizer configuration for vectorizing content. - * + * * @param embeddingModel the embeddingModel value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -123,7 +127,7 @@ public KnowledgeSourceIngestionParameters setEmbeddingModel(KnowledgeSourceVecto /** * Get the chatCompletionModel property: Optional chat completion model for image verbalization or context * extraction. - * + * * @return the chatCompletionModel value. */ @Generated @@ -134,7 +138,7 @@ public KnowledgeBaseModel getChatCompletionModel() { /** * Set the chatCompletionModel property: Optional chat completion model for image verbalization or context * extraction. - * + * * @param chatCompletionModel the chatCompletionModel value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -147,7 +151,7 @@ public KnowledgeSourceIngestionParameters setChatCompletionModel(KnowledgeBaseMo /** * Get the disableImageVerbalization property: Indicates whether image verbalization should be disabled. Default is * false. - * + * * @return the disableImageVerbalization value. */ @Generated @@ -158,7 +162,7 @@ public Boolean isDisableImageVerbalization() { /** * Set the disableImageVerbalization property: Indicates whether image verbalization should be disabled. Default is * false. - * + * * @param disableImageVerbalization the disableImageVerbalization value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -170,7 +174,7 @@ public KnowledgeSourceIngestionParameters setDisableImageVerbalization(Boolean d /** * Get the ingestionSchedule property: Optional schedule for data ingestion. - * + * * @return the ingestionSchedule value. */ @Generated @@ -180,7 +184,7 @@ public IndexingSchedule getIngestionSchedule() { /** * Set the ingestionSchedule property: Optional schedule for data ingestion. - * + * * @param ingestionSchedule the ingestionSchedule value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -193,7 +197,7 @@ public KnowledgeSourceIngestionParameters setIngestionSchedule(IndexingSchedule /** * Get the ingestionPermissionOptions property: Optional list of permission types to ingest together with document * content. If specified, it will set the indexer permission options for the data source. - * + * * @return the ingestionPermissionOptions value. */ @Generated @@ -204,7 +208,21 @@ public List getIngestionPermissionOpti /** * Set the ingestionPermissionOptions property: Optional list of permission types to ingest together with document * content. If specified, it will set the indexer permission options for the data source. - * + * + * @param ingestionPermissionOptions the ingestionPermissionOptions value to set. + * @return the KnowledgeSourceIngestionParameters object itself. + */ + public KnowledgeSourceIngestionParameters + setIngestionPermissionOptions(KnowledgeSourceIngestionPermissionOption... ingestionPermissionOptions) { + this.ingestionPermissionOptions + = (ingestionPermissionOptions == null) ? null : Arrays.asList(ingestionPermissionOptions); + return this; + } + + /** + * Set the ingestionPermissionOptions property: Optional list of permission types to ingest together with document + * content. If specified, it will set the indexer permission options for the data source. + * * @param ingestionPermissionOptions the ingestionPermissionOptions value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -217,7 +235,7 @@ public List getIngestionPermissionOpti /** * Get the contentExtractionMode property: Optional content extraction mode. Default is 'minimal'. - * + * * @return the contentExtractionMode value. */ @Generated @@ -227,7 +245,7 @@ public KnowledgeSourceContentExtractionMode getContentExtractionMode() { /** * Set the contentExtractionMode property: Optional content extraction mode. Default is 'minimal'. - * + * * @param contentExtractionMode the contentExtractionMode value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -240,7 +258,7 @@ public KnowledgeSourceContentExtractionMode getContentExtractionMode() { /** * Get the aiServices property: Optional AI Services configuration for content processing. - * + * * @return the aiServices value. */ @Generated @@ -250,7 +268,7 @@ public AIServices getAiServices() { /** * Set the aiServices property: Optional AI Services configuration for content processing. - * + * * @param aiServices the aiServices value to set. * @return the KnowledgeSourceIngestionParameters object itself. */ @@ -282,7 +300,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeSourceIngestionParameters from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeSourceIngestionParameters if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -296,7 +314,6 @@ public static KnowledgeSourceIngestionParameters fromJson(JsonReader jsonReader) while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("identity".equals(fieldName)) { deserializedKnowledgeSourceIngestionParameters.identity = SearchIndexerDataIdentity.fromJson(reader); @@ -326,7 +343,6 @@ public static KnowledgeSourceIngestionParameters fromJson(JsonReader jsonReader) reader.skipChildren(); } } - return deserializedKnowledgeSourceIngestionParameters; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceKind.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceKind.java deleted file mode 100644 index ff232058b584..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceKind.java +++ /dev/null @@ -1,83 +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.knowledgebases.models; - -import com.azure.core.annotation.Generated; -import com.azure.core.util.ExpandableStringEnum; -import java.util.Collection; - -/** - * The kind of the knowledge source. - */ -public final class KnowledgeSourceKind extends ExpandableStringEnum { - /** - * A knowledge source that retrieves data from a Search Index. - */ - @Generated - public static final KnowledgeSourceKind SEARCH_INDEX = fromString("searchIndex"); - - /** - * A knowledge source that retrieves and ingests data from Azure Blob Storage to a Search Index. - */ - @Generated - public static final KnowledgeSourceKind AZURE_BLOB = fromString("azureBlob"); - - /** - * A knowledge source that retrieves data from the web. - */ - @Generated - public static final KnowledgeSourceKind WEB = fromString("web"); - - /** - * A knowledge source that retrieves data from a remote SharePoint endpoint. - */ - @Generated - public static final KnowledgeSourceKind REMOTE_SHARE_POINT = fromString("remoteSharePoint"); - - /** - * A knowledge source that retrieves and ingests data from SharePoint to a Search Index. - */ - @Generated - public static final KnowledgeSourceKind INDEXED_SHARE_POINT = fromString("indexedSharePoint"); - - /** - * A knowledge source that retrieves and ingests data from OneLake to a Search Index. - */ - @Generated - public static final KnowledgeSourceKind INDEXED_ONE_LAKE = fromString("indexedOneLake"); - - /** - * Creates a new instance of KnowledgeSourceKind value. - * - * @deprecated Use the {@link #fromString(String)} factory method. - */ - @Generated - @Deprecated - public KnowledgeSourceKind() { - } - - /** - * Creates or finds a KnowledgeSourceKind from its string representation. - * - * @param name a name to look for. - * @return the corresponding KnowledgeSourceKind. - */ - @Generated - public static KnowledgeSourceKind fromString(String name) { - return fromString(name, KnowledgeSourceKind.class); - } - - /** - * Gets known KnowledgeSourceKind values. - * - * @return known KnowledgeSourceKind values. - */ - @Generated - public static Collection values() { - return values(KnowledgeSourceKind.class); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceParams.java index cdae42290b24..d18f30e03db6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -12,13 +9,15 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** - * The KnowledgeSourceParams model. + * Base type for knowledge source runtime parameters. */ @Fluent public class KnowledgeSourceParams implements JsonSerializable { + /* * The type of the knowledge source. */ @@ -57,7 +56,7 @@ public class KnowledgeSourceParams implements JsonSerializable { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -245,7 +245,6 @@ public static KnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOExc @Generated static KnowledgeSourceParams fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; KnowledgeSourceKind kind = null; Boolean includeReferences = null; @@ -255,10 +254,8 @@ static KnowledgeSourceParams fromJsonKnownDiscriminator(JsonReader jsonReader) t while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("kind".equals(fieldName)) { kind = KnowledgeSourceKind.fromString(reader.getString()); } else if ("includeReferences".equals(fieldName)) { @@ -273,18 +270,13 @@ static KnowledgeSourceParams fromJsonKnownDiscriminator(JsonReader jsonReader) t reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - KnowledgeSourceParams deserializedKnowledgeSourceParams - = new KnowledgeSourceParams(knowledgeSourceName); - deserializedKnowledgeSourceParams.kind = kind; - deserializedKnowledgeSourceParams.includeReferences = includeReferences; - deserializedKnowledgeSourceParams.includeReferenceSourceData = includeReferenceSourceData; - deserializedKnowledgeSourceParams.alwaysQuerySource = alwaysQuerySource; - deserializedKnowledgeSourceParams.rerankerThreshold = rerankerThreshold; - - return deserializedKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + KnowledgeSourceParams deserializedKnowledgeSourceParams = new KnowledgeSourceParams(knowledgeSourceName); + deserializedKnowledgeSourceParams.kind = kind; + deserializedKnowledgeSourceParams.includeReferences = includeReferences; + deserializedKnowledgeSourceParams.includeReferenceSourceData = includeReferenceSourceData; + deserializedKnowledgeSourceParams.alwaysQuerySource = alwaysQuerySource; + deserializedKnowledgeSourceParams.rerankerThreshold = rerankerThreshold; + return deserializedKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceStatistics.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatistics.java similarity index 67% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceStatistics.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatistics.java index 207cd0fba99f..4ce27638f345 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceStatistics.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatistics.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.knowledgebases.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -13,35 +10,34 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; /** * Statistical information about knowledge source synchronization history. */ @Immutable public final class KnowledgeSourceStatistics implements JsonSerializable { + /* - * The total number of synchronizations completed. + * Total number of synchronizations. */ @Generated private final int totalSynchronization; /* - * The average duration of synchronizations in HH:MM:SS format. + * Average synchronization duration in HH:MM:SS format. */ @Generated private final String averageSynchronizationDuration; /* - * The average number of items processed per synchronization. + * Average items processed per synchronization. */ @Generated private final int averageItemsProcessedPerSynchronization; /** * Creates an instance of KnowledgeSourceStatistics class. - * + * * @param totalSynchronization the totalSynchronization value to set. * @param averageSynchronizationDuration the averageSynchronizationDuration value to set. * @param averageItemsProcessedPerSynchronization the averageItemsProcessedPerSynchronization value to set. @@ -55,8 +51,8 @@ public KnowledgeSourceStatistics(int totalSynchronization, String averageSynchro } /** - * Get the totalSynchronization property: The total number of synchronizations completed. - * + * Get the totalSynchronization property: Total number of synchronizations. + * * @return the totalSynchronization value. */ @Generated @@ -65,8 +61,8 @@ public int getTotalSynchronization() { } /** - * Get the averageSynchronizationDuration property: The average duration of synchronizations in HH:MM:SS format. - * + * Get the averageSynchronizationDuration property: Average synchronization duration in HH:MM:SS format. + * * @return the averageSynchronizationDuration value. */ @Generated @@ -75,9 +71,8 @@ public String getAverageSynchronizationDuration() { } /** - * Get the averageItemsProcessedPerSynchronization property: The average number of items processed per - * synchronization. - * + * Get the averageItemsProcessedPerSynchronization property: Average items processed per synchronization. + * * @return the averageItemsProcessedPerSynchronization value. */ @Generated @@ -101,7 +96,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeSourceStatistics from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeSourceStatistics if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -111,48 +106,24 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static KnowledgeSourceStatistics fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean totalSynchronizationFound = false; int totalSynchronization = 0; - boolean averageSynchronizationDurationFound = false; String averageSynchronizationDuration = null; - boolean averageItemsProcessedPerSynchronizationFound = false; int averageItemsProcessedPerSynchronization = 0; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("totalSynchronization".equals(fieldName)) { totalSynchronization = reader.getInt(); - totalSynchronizationFound = true; } else if ("averageSynchronizationDuration".equals(fieldName)) { averageSynchronizationDuration = reader.getString(); - averageSynchronizationDurationFound = true; } else if ("averageItemsProcessedPerSynchronization".equals(fieldName)) { averageItemsProcessedPerSynchronization = reader.getInt(); - averageItemsProcessedPerSynchronizationFound = true; } else { reader.skipChildren(); } } - if (totalSynchronizationFound - && averageSynchronizationDurationFound - && averageItemsProcessedPerSynchronizationFound) { - return new KnowledgeSourceStatistics(totalSynchronization, averageSynchronizationDuration, - averageItemsProcessedPerSynchronization); - } - List missingProperties = new ArrayList<>(); - if (!totalSynchronizationFound) { - missingProperties.add("totalSynchronization"); - } - if (!averageSynchronizationDurationFound) { - missingProperties.add("averageSynchronizationDuration"); - } - if (!averageItemsProcessedPerSynchronizationFound) { - missingProperties.add("averageItemsProcessedPerSynchronization"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new KnowledgeSourceStatistics(totalSynchronization, averageSynchronizationDuration, + averageItemsProcessedPerSynchronization); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceStatus.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatus.java similarity index 86% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceStatus.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatus.java index 809797fab769..aaa29bc29bc7 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceStatus.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatus.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.knowledgebases.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.Generated; @@ -12,6 +9,7 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus; import java.io.IOException; /** @@ -19,8 +17,9 @@ */ @Fluent public final class KnowledgeSourceStatus implements JsonSerializable { + /* - * The current synchronization status of the knowledge source. + * The current synchronization status. */ @Generated private final KnowledgeSourceSynchronizationStatus synchronizationStatus; @@ -51,7 +50,7 @@ public final class KnowledgeSourceStatus implements JsonSerializable { - boolean synchronizationStatusFound = false; KnowledgeSourceSynchronizationStatus synchronizationStatus = null; String synchronizationInterval = null; SynchronizationState currentSynchronizationState = null; @@ -198,10 +196,8 @@ public static KnowledgeSourceStatus fromJson(JsonReader jsonReader) throws IOExc while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("synchronizationStatus".equals(fieldName)) { synchronizationStatus = KnowledgeSourceSynchronizationStatus.fromString(reader.getString()); - synchronizationStatusFound = true; } else if ("synchronizationInterval".equals(fieldName)) { synchronizationInterval = reader.getString(); } else if ("currentSynchronizationState".equals(fieldName)) { @@ -214,17 +210,12 @@ public static KnowledgeSourceStatus fromJson(JsonReader jsonReader) throws IOExc reader.skipChildren(); } } - if (synchronizationStatusFound) { - KnowledgeSourceStatus deserializedKnowledgeSourceStatus - = new KnowledgeSourceStatus(synchronizationStatus); - deserializedKnowledgeSourceStatus.synchronizationInterval = synchronizationInterval; - deserializedKnowledgeSourceStatus.currentSynchronizationState = currentSynchronizationState; - deserializedKnowledgeSourceStatus.lastSynchronizationState = lastSynchronizationState; - deserializedKnowledgeSourceStatus.statistics = statistics; - - return deserializedKnowledgeSourceStatus; - } - throw new IllegalStateException("Missing required property: synchronizationStatus"); + KnowledgeSourceStatus deserializedKnowledgeSourceStatus = new KnowledgeSourceStatus(synchronizationStatus); + deserializedKnowledgeSourceStatus.synchronizationInterval = synchronizationInterval; + deserializedKnowledgeSourceStatus.currentSynchronizationState = currentSynchronizationState; + deserializedKnowledgeSourceStatus.lastSynchronizationState = lastSynchronizationState; + deserializedKnowledgeSourceStatus.statistics = statistics; + return deserializedKnowledgeSourceStatus; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceVectorizer.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceVectorizer.java similarity index 92% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceVectorizer.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceVectorizer.java index b37af09e53f5..fc74417ba172 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceVectorizer.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceVectorizer.java @@ -1,10 +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. - -package com.azure.search.documents.indexes.models; +// Code generated by Microsoft (R) TypeSpec Code Generator. +package com.azure.search.documents.knowledgebases.models; import com.azure.core.annotation.Generated; import com.azure.core.annotation.Immutable; @@ -12,13 +9,15 @@ import com.azure.json.JsonSerializable; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.VectorSearchVectorizerKind; import java.io.IOException; /** - * Specifies the vectorization method to be used for knowledge source embedding model, with optional name. + * Specifies the vectorization method to be used for knowledge source embedding model. */ @Immutable public class KnowledgeSourceVectorizer implements JsonSerializable { + /* * The name of the kind of vectorization method being configured for use with vector search. */ @@ -34,7 +33,7 @@ public KnowledgeSourceVectorizer() { /** * Get the kind property: The name of the kind of vectorization method being configured for use with vector search. - * + * * @return the kind value. */ @Generated @@ -55,7 +54,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of KnowledgeSourceVectorizer from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of KnowledgeSourceVectorizer if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -66,7 +65,8 @@ public static KnowledgeSourceVectorizer fromJson(JsonReader jsonReader) throws I return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -94,7 +94,6 @@ static KnowledgeSourceVectorizer fromJsonKnownDiscriminator(JsonReader jsonReade while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kind".equals(fieldName)) { deserializedKnowledgeSourceVectorizer.kind = VectorSearchVectorizerKind.fromString(reader.getString()); @@ -102,7 +101,6 @@ static KnowledgeSourceVectorizer fromJsonKnownDiscriminator(JsonReader jsonReade reader.skipChildren(); } } - return deserializedKnowledgeSourceVectorizer; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/RemoteSharePointKnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/RemoteSharePointKnowledgeSourceParams.java index bc12e70df561..63a18f9a1725 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/RemoteSharePointKnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/RemoteSharePointKnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -11,6 +8,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** @@ -18,6 +16,7 @@ */ @Fluent public final class RemoteSharePointKnowledgeSourceParams extends KnowledgeSourceParams { + /* * The type of the knowledge source. */ @@ -34,7 +33,7 @@ public final class RemoteSharePointKnowledgeSourceParams extends KnowledgeSource /** * Creates an instance of RemoteSharePointKnowledgeSourceParams class. - * + * * @param knowledgeSourceName the knowledgeSourceName value to set. */ @Generated @@ -44,7 +43,7 @@ public RemoteSharePointKnowledgeSourceParams(String knowledgeSourceName) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -57,7 +56,7 @@ public KnowledgeSourceKind getKind() { * Get the filterExpressionAddOn property: A filter condition applied to the SharePoint data source. It must be * specified in the Keyword Query Language syntax. It will be combined as a conjunction with the filter expression * specified in the knowledge source definition. - * + * * @return the filterExpressionAddOn value. */ @Generated @@ -69,7 +68,7 @@ public String getFilterExpressionAddOn() { * Set the filterExpressionAddOn property: A filter condition applied to the SharePoint data source. It must be * specified in the Keyword Query Language syntax. It will be combined as a conjunction with the filter expression * specified in the knowledge source definition. - * + * * @param filterExpressionAddOn the filterExpressionAddOn value to set. * @return the RemoteSharePointKnowledgeSourceParams object itself. */ @@ -138,7 +137,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of RemoteSharePointKnowledgeSourceParams from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of RemoteSharePointKnowledgeSourceParams if the JsonReader was pointing to an instance of it, * or null if it was pointing to JSON null. @@ -148,7 +147,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static RemoteSharePointKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; Boolean includeReferences = null; Boolean includeReferenceSourceData = null; @@ -159,10 +157,8 @@ public static RemoteSharePointKnowledgeSourceParams fromJson(JsonReader jsonRead while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("includeReferences".equals(fieldName)) { includeReferences = reader.getNullable(JsonReader::getBoolean); } else if ("includeReferenceSourceData".equals(fieldName)) { @@ -179,20 +175,15 @@ public static RemoteSharePointKnowledgeSourceParams fromJson(JsonReader jsonRead reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - RemoteSharePointKnowledgeSourceParams deserializedRemoteSharePointKnowledgeSourceParams - = new RemoteSharePointKnowledgeSourceParams(knowledgeSourceName); - deserializedRemoteSharePointKnowledgeSourceParams.setIncludeReferences(includeReferences); - deserializedRemoteSharePointKnowledgeSourceParams - .setIncludeReferenceSourceData(includeReferenceSourceData); - deserializedRemoteSharePointKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); - deserializedRemoteSharePointKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); - deserializedRemoteSharePointKnowledgeSourceParams.kind = kind; - deserializedRemoteSharePointKnowledgeSourceParams.filterExpressionAddOn = filterExpressionAddOn; - - return deserializedRemoteSharePointKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + RemoteSharePointKnowledgeSourceParams deserializedRemoteSharePointKnowledgeSourceParams + = new RemoteSharePointKnowledgeSourceParams(knowledgeSourceName); + deserializedRemoteSharePointKnowledgeSourceParams.setIncludeReferences(includeReferences); + deserializedRemoteSharePointKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); + deserializedRemoteSharePointKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); + deserializedRemoteSharePointKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); + deserializedRemoteSharePointKnowledgeSourceParams.kind = kind; + deserializedRemoteSharePointKnowledgeSourceParams.filterExpressionAddOn = filterExpressionAddOn; + return deserializedRemoteSharePointKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexFieldReference.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexFieldReference.java deleted file mode 100644 index b52359e22b2e..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexFieldReference.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.knowledgebases.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; - -/** - * The SearchIndexFieldReference model. - */ -@Immutable -public final class SearchIndexFieldReference implements JsonSerializable { - /* - * The name property. - */ - @Generated - private final String name; - - /** - * Creates an instance of SearchIndexFieldReference class. - * - * @param name the name value to set. - */ - @Generated - public SearchIndexFieldReference(String name) { - this.name = name; - } - - /** - * Get the name property: The name property. - * - * @return the name value. - */ - @Generated - public String getName() { - return this.name; - } - - /** - * {@inheritDoc} - */ - @Generated - @Override - public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { - jsonWriter.writeStartObject(); - jsonWriter.writeStringField("name", this.name); - return jsonWriter.writeEndObject(); - } - - /** - * Reads an instance of SearchIndexFieldReference from the JsonReader. - * - * @param jsonReader The JsonReader being read. - * @return An instance of SearchIndexFieldReference 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 SearchIndexFieldReference. - */ - @Generated - public static SearchIndexFieldReference fromJson(JsonReader jsonReader) throws IOException { - return jsonReader.readObject(reader -> { - boolean nameFound = false; - String name = null; - while (reader.nextToken() != JsonToken.END_OBJECT) { - String fieldName = reader.getFieldName(); - reader.nextToken(); - - if ("name".equals(fieldName)) { - name = reader.getString(); - nameFound = true; - } else { - reader.skipChildren(); - } - } - if (nameFound) { - return new SearchIndexFieldReference(name); - } - throw new IllegalStateException("Missing required property: name"); - }); - } -} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexKnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexKnowledgeSourceParams.java index d10ddc1584be..069621b5b9b6 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexKnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexKnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -11,6 +8,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** @@ -18,6 +16,7 @@ */ @Fluent public final class SearchIndexKnowledgeSourceParams extends KnowledgeSourceParams { + /* * The type of the knowledge source. */ @@ -32,7 +31,7 @@ public final class SearchIndexKnowledgeSourceParams extends KnowledgeSourceParam /** * Creates an instance of SearchIndexKnowledgeSourceParams class. - * + * * @param knowledgeSourceName the knowledgeSourceName value to set. */ @Generated @@ -42,7 +41,7 @@ public SearchIndexKnowledgeSourceParams(String knowledgeSourceName) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -53,7 +52,7 @@ public KnowledgeSourceKind getKind() { /** * Get the filterAddOn property: A filter condition applied to the index (e.g., 'State eq VA'). - * + * * @return the filterAddOn value. */ @Generated @@ -63,7 +62,7 @@ public String getFilterAddOn() { /** * Set the filterAddOn property: A filter condition applied to the index (e.g., 'State eq VA'). - * + * * @param filterAddOn the filterAddOn value to set. * @return the SearchIndexKnowledgeSourceParams object itself. */ @@ -132,7 +131,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchIndexKnowledgeSourceParams from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchIndexKnowledgeSourceParams if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -142,7 +141,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SearchIndexKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; Boolean includeReferences = null; Boolean includeReferenceSourceData = null; @@ -153,10 +151,8 @@ public static SearchIndexKnowledgeSourceParams fromJson(JsonReader jsonReader) t while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("includeReferences".equals(fieldName)) { includeReferences = reader.getNullable(JsonReader::getBoolean); } else if ("includeReferenceSourceData".equals(fieldName)) { @@ -173,19 +169,15 @@ public static SearchIndexKnowledgeSourceParams fromJson(JsonReader jsonReader) t reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - SearchIndexKnowledgeSourceParams deserializedSearchIndexKnowledgeSourceParams - = new SearchIndexKnowledgeSourceParams(knowledgeSourceName); - deserializedSearchIndexKnowledgeSourceParams.setIncludeReferences(includeReferences); - deserializedSearchIndexKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); - deserializedSearchIndexKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); - deserializedSearchIndexKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); - deserializedSearchIndexKnowledgeSourceParams.kind = kind; - deserializedSearchIndexKnowledgeSourceParams.filterAddOn = filterAddOn; - - return deserializedSearchIndexKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + SearchIndexKnowledgeSourceParams deserializedSearchIndexKnowledgeSourceParams + = new SearchIndexKnowledgeSourceParams(knowledgeSourceName); + deserializedSearchIndexKnowledgeSourceParams.setIncludeReferences(includeReferences); + deserializedSearchIndexKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); + deserializedSearchIndexKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); + deserializedSearchIndexKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); + deserializedSearchIndexKnowledgeSourceParams.kind = kind; + deserializedSearchIndexKnowledgeSourceParams.filterAddOn = filterAddOn; + return deserializedSearchIndexKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SharePointSensitivityLabelInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SharePointSensitivityLabelInfo.java index 681e47e3d449..212ef68692e3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SharePointSensitivityLabelInfo.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/SharePointSensitivityLabelInfo.java @@ -1,13 +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.knowledgebases.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; @@ -17,8 +14,9 @@ /** * Information about the sensitivity label applied to a SharePoint document. */ -@Fluent +@Immutable public final class SharePointSensitivityLabelInfo implements JsonSerializable { + /* * The display name for the sensitivity label. */ @@ -59,12 +57,12 @@ public final class SharePointSensitivityLabelInfo implements JsonSerializable { + /* * The start time of the current synchronization. */ @@ -50,7 +46,7 @@ public final class SynchronizationState implements JsonSerializable { - boolean startTimeFound = false; OffsetDateTime startTime = null; - boolean itemsUpdatesProcessedFound = false; int itemsUpdatesProcessed = 0; - boolean itemsUpdatesFailedFound = false; int itemsUpdatesFailed = 0; - boolean itemsSkippedFound = false; int itemsSkipped = 0; while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("startTime".equals(fieldName)) { startTime = reader .getNullable(nonNullReader -> CoreUtils.parseBestOffsetDateTime(nonNullReader.getString())); - startTimeFound = true; } else if ("itemsUpdatesProcessed".equals(fieldName)) { itemsUpdatesProcessed = reader.getInt(); - itemsUpdatesProcessedFound = true; } else if ("itemsUpdatesFailed".equals(fieldName)) { itemsUpdatesFailed = reader.getInt(); - itemsUpdatesFailedFound = true; } else if ("itemsSkipped".equals(fieldName)) { itemsSkipped = reader.getInt(); - itemsSkippedFound = true; } else { reader.skipChildren(); } } - if (startTimeFound && itemsUpdatesProcessedFound && itemsUpdatesFailedFound && itemsSkippedFound) { - return new SynchronizationState(startTime, itemsUpdatesProcessed, itemsUpdatesFailed, itemsSkipped); - } - List missingProperties = new ArrayList<>(); - if (!startTimeFound) { - missingProperties.add("startTime"); - } - if (!itemsUpdatesProcessedFound) { - missingProperties.add("itemsUpdatesProcessed"); - } - if (!itemsUpdatesFailedFound) { - missingProperties.add("itemsUpdatesFailed"); - } - if (!itemsSkippedFound) { - missingProperties.add("itemsSkipped"); - } - - throw new IllegalStateException( - "Missing required property/properties: " + String.join(", ", missingProperties)); + return new SynchronizationState(startTime, itemsUpdatesProcessed, itemsUpdatesFailed, itemsSkipped); }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/WebKnowledgeSourceParams.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/WebKnowledgeSourceParams.java index 4a63c6dfe5a1..a525c1fd32b8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/WebKnowledgeSourceParams.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/WebKnowledgeSourceParams.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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.knowledgebases.models; import com.azure.core.annotation.Fluent; @@ -11,6 +8,7 @@ import com.azure.json.JsonReader; import com.azure.json.JsonToken; import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.models.KnowledgeSourceKind; import java.io.IOException; /** @@ -18,6 +16,7 @@ */ @Fluent public final class WebKnowledgeSourceParams extends KnowledgeSourceParams { + /* * The type of the knowledge source. */ @@ -50,7 +49,7 @@ public final class WebKnowledgeSourceParams extends KnowledgeSourceParams { /** * Creates an instance of WebKnowledgeSourceParams class. - * + * * @param knowledgeSourceName the knowledgeSourceName value to set. */ @Generated @@ -60,7 +59,7 @@ public WebKnowledgeSourceParams(String knowledgeSourceName) { /** * Get the kind property: The type of the knowledge source. - * + * * @return the kind value. */ @Generated @@ -71,7 +70,7 @@ public KnowledgeSourceKind getKind() { /** * Get the language property: The language of the web results. - * + * * @return the language value. */ @Generated @@ -81,7 +80,7 @@ public String getLanguage() { /** * Set the language property: The language of the web results. - * + * * @param language the language value to set. * @return the WebKnowledgeSourceParams object itself. */ @@ -93,7 +92,7 @@ public WebKnowledgeSourceParams setLanguage(String language) { /** * Get the market property: The market of the web results. - * + * * @return the market value. */ @Generated @@ -103,7 +102,7 @@ public String getMarket() { /** * Set the market property: The market of the web results. - * + * * @param market the market value to set. * @return the WebKnowledgeSourceParams object itself. */ @@ -115,7 +114,7 @@ public WebKnowledgeSourceParams setMarket(String market) { /** * Get the count property: The number of web results to return. - * + * * @return the count value. */ @Generated @@ -125,7 +124,7 @@ public Integer getCount() { /** * Set the count property: The number of web results to return. - * + * * @param count the count value to set. * @return the WebKnowledgeSourceParams object itself. */ @@ -137,7 +136,7 @@ public WebKnowledgeSourceParams setCount(Integer count) { /** * Get the freshness property: The freshness of web results. - * + * * @return the freshness value. */ @Generated @@ -147,7 +146,7 @@ public String getFreshness() { /** * Set the freshness property: The freshness of web results. - * + * * @param freshness the freshness value to set. * @return the WebKnowledgeSourceParams object itself. */ @@ -219,7 +218,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of WebKnowledgeSourceParams from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of WebKnowledgeSourceParams if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -229,7 +228,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static WebKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean knowledgeSourceNameFound = false; String knowledgeSourceName = null; Boolean includeReferences = null; Boolean includeReferenceSourceData = null; @@ -243,10 +241,8 @@ public static WebKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IO while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("knowledgeSourceName".equals(fieldName)) { knowledgeSourceName = reader.getString(); - knowledgeSourceNameFound = true; } else if ("includeReferences".equals(fieldName)) { includeReferences = reader.getNullable(JsonReader::getBoolean); } else if ("includeReferenceSourceData".equals(fieldName)) { @@ -269,22 +265,18 @@ public static WebKnowledgeSourceParams fromJson(JsonReader jsonReader) throws IO reader.skipChildren(); } } - if (knowledgeSourceNameFound) { - WebKnowledgeSourceParams deserializedWebKnowledgeSourceParams - = new WebKnowledgeSourceParams(knowledgeSourceName); - deserializedWebKnowledgeSourceParams.setIncludeReferences(includeReferences); - deserializedWebKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); - deserializedWebKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); - deserializedWebKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); - deserializedWebKnowledgeSourceParams.kind = kind; - deserializedWebKnowledgeSourceParams.language = language; - deserializedWebKnowledgeSourceParams.market = market; - deserializedWebKnowledgeSourceParams.count = count; - deserializedWebKnowledgeSourceParams.freshness = freshness; - - return deserializedWebKnowledgeSourceParams; - } - throw new IllegalStateException("Missing required property: knowledgeSourceName"); + WebKnowledgeSourceParams deserializedWebKnowledgeSourceParams + = new WebKnowledgeSourceParams(knowledgeSourceName); + deserializedWebKnowledgeSourceParams.setIncludeReferences(includeReferences); + deserializedWebKnowledgeSourceParams.setIncludeReferenceSourceData(includeReferenceSourceData); + deserializedWebKnowledgeSourceParams.setAlwaysQuerySource(alwaysQuerySource); + deserializedWebKnowledgeSourceParams.setRerankerThreshold(rerankerThreshold); + deserializedWebKnowledgeSourceParams.kind = kind; + deserializedWebKnowledgeSourceParams.language = language; + deserializedWebKnowledgeSourceParams.market = market; + deserializedWebKnowledgeSourceParams.count = count; + deserializedWebKnowledgeSourceParams.freshness = freshness; + return deserializedWebKnowledgeSourceParams; }); } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/package-info.java index 1a386e95a2dc..5d2546ac7341 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/package-info.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/models/package-info.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 containing the data models for KnowledgeBaseRetrievalClient. - * Client that can be used to query an knowledge base. + * + * 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.knowledgebases.models; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/package-info.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/package-info.java index 50309bd1646c..f0cef44f8233 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/package-info.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/knowledgebases/package-info.java @@ -1,8 +1,11 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - +// Code generated by Microsoft (R) TypeSpec Code Generator. /** - * For more information about Azure AI Search KnowledgeBases, supported features, and usage guidelines, see the Azure documentation and the Azure SDK for Java guidelines. - * + * + * Package containing the classes for KnowledgeBaseRetrievalClient. + * 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.knowledgebases; 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 cd2070431b2b..1d998355ff5d 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -13,41 +10,35 @@ 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. */ @Immutable public final class AutocompleteItem implements JsonSerializable { + /* * The completed term. */ @Generated - private final String text; + private String text; /* * The query along with the completed term. */ @Generated - private final String queryPlusText; + private String queryPlusText; /** * Creates an instance of AutocompleteItem class. - * - * @param text the text value to set. - * @param queryPlusText the queryPlusText value to set. */ @Generated - public AutocompleteItem(String text, String queryPlusText) { - this.text = text; - this.queryPlusText = queryPlusText; + public AutocompleteItem() { } /** * Get the text property: The completed term. - * + * * @return the text value. */ @Generated @@ -57,7 +48,7 @@ public String getText() { /** * Get the queryPlusText property: The query along with the completed term. - * + * * @return the queryPlusText value. */ @Generated @@ -77,7 +68,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AutocompleteItem from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AutocompleteItem if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -87,37 +78,19 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static AutocompleteItem fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean textFound = false; - String text = null; - boolean queryPlusTextFound = false; - String queryPlusText = null; + AutocompleteItem deserializedAutocompleteItem = new AutocompleteItem(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("text".equals(fieldName)) { - text = reader.getString(); - textFound = true; + deserializedAutocompleteItem.text = reader.getString(); } else if ("queryPlusText".equals(fieldName)) { - queryPlusText = reader.getString(); - queryPlusTextFound = true; + deserializedAutocompleteItem.queryPlusText = reader.getString(); } 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 deserializedAutocompleteItem; }); } } 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..f4f211e82bd9 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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 index 76abf3db0781..36884183134e 100644 --- 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 @@ -1,25 +1,24 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; -import com.azure.json.JsonWriter; -import java.io.IOException; import java.util.Arrays; import java.util.List; /** - * Parameter group. + * Options for autocomplete API. */ @Fluent -public final class AutocompleteOptions implements JsonSerializable { +public final class AutocompleteOptions { + + /* + * The search text on which to base autocomplete results. + */ + @Generated + private final String searchText; /* * Specifies the mode for Autocomplete. The default is 'oneTerm'. Use 'twoTerms' to get shingles and @@ -36,9 +35,9 @@ public final class AutocompleteOptions implements JsonSerializable searchFields; + /* + * 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 auto-completed terms to retrieve. This must be a value between 1 and 100. The default is 5. */ @@ -80,9 +85,24 @@ public final class AutocompleteOptions implements JsonSerializable getSearchFields() { } /** - * 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. + * Set the searchFields property: The comma-separated 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; + } + + /** + * Set the searchFields property: The comma-separated 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. @@ -259,6 +291,17 @@ public AutocompleteOptions setSearchFields(List searchFields) { return this; } + /** + * Get the suggesterName property: The name of the suggester as specified in the suggesters collection that's part + * of the index definition. + * + * @return the suggesterName value. + */ + @Generated + public String getSuggesterName() { + return this.suggesterName; + } + /** * 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. @@ -282,73 +325,4 @@ 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/models/AutocompleteResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/AutocompleteResult.java index 8eda3860c6fd..267e0b809f07 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -20,6 +17,7 @@ */ @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. @@ -31,22 +29,19 @@ public final class AutocompleteResult implements JsonSerializable results; + private List results; /** * Creates an instance of AutocompleteResult class. - * - * @param results the results value to set. */ @Generated - public AutocompleteResult(List results) { - this.results = results; + private AutocompleteResult() { } /** * 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 @@ -56,7 +51,7 @@ public Double getCoverage() { /** * Get the results property: The list of returned Autocompleted items. - * + * * @return the results value. */ @Generated @@ -76,7 +71,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of AutocompleteResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of AutocompleteResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -86,29 +81,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static AutocompleteResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; - List results = null; - Double coverage = null; + AutocompleteResult deserializedAutocompleteResult = new AutocompleteResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - results = reader.readArray(reader1 -> AutocompleteItem.fromJson(reader1)); - resultsFound = true; + List results = reader.readArray(reader1 -> AutocompleteItem.fromJson(reader1)); + deserializedAutocompleteResult.results = results; } else if ("@search.coverage".equals(fieldName)) { - coverage = reader.getNullable(JsonReader::getDouble); + deserializedAutocompleteResult.coverage = reader.getNullable(JsonReader::getDouble); } else { reader.skipChildren(); } } - if (resultsFound) { - 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/models/DebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/DebugInfo.java index 81945231a042..30f833c19590 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -19,6 +16,7 @@ */ @Immutable public final class DebugInfo implements JsonSerializable { + /* * Contains debugging information specific to query rewrites. */ @@ -34,7 +32,7 @@ public DebugInfo() { /** * Get the queryRewrites property: Contains debugging information specific to query rewrites. - * + * * @return the queryRewrites value. */ @Generated @@ -54,7 +52,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of DebugInfo from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of DebugInfo if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. @@ -67,14 +65,12 @@ public static DebugInfo fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("queryRewrites".equals(fieldName)) { deserializedDebugInfo.queryRewrites = QueryRewritesDebugInfo.fromJson(reader); } else { reader.skipChildren(); } } - return deserializedDebugInfo; }); } 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 66a2bf91b078..3dd80d331772 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -21,6 +18,7 @@ */ @Immutable public final class DocumentDebugInfo implements JsonSerializable { + /* * Contains debugging information specific to semantic ranking requests. */ @@ -43,12 +41,12 @@ public final class DocumentDebugInfo implements JsonSerializable { + /* * The approximate count of documents falling within the bucket described by this facet. */ @@ -82,7 +80,7 @@ public FacetResult() { /** * Get the count property: The approximate count of documents falling within the bucket described by this facet. - * + * * @return the count value. */ @Generated @@ -92,7 +90,7 @@ public Long getCount() { /** * Get the avg property: The resulting total avg for the facet when a avg metric is requested. - * + * * @return the avg value. */ @Generated @@ -102,7 +100,7 @@ public Double getAvg() { /** * Get the min property: The resulting total min for the facet when a min metric is requested. - * + * * @return the min value. */ @Generated @@ -112,7 +110,7 @@ public Double getMin() { /** * Get the max property: The resulting total max for the facet when a max metric is requested. - * + * * @return the max value. */ @Generated @@ -122,7 +120,7 @@ public Double getMax() { /** * Get the sum property: The resulting total sum for the facet when a sum metric is requested. - * + * * @return the sum value. */ @Generated @@ -133,7 +131,7 @@ public Double getSum() { /** * Get the cardinality property: The resulting total cardinality for the facet when a cardinality metric is * requested. - * + * * @return the cardinality value. */ @Generated @@ -144,7 +142,7 @@ public Long getCardinality() { /** * 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 @@ -155,7 +153,7 @@ public Map> getFacets() { /** * 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. - * + * * @return the additionalProperties value. */ @Generated @@ -166,7 +164,7 @@ public Map getAdditionalProperties() { /** * 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. - * + * * @param additionalProperties the additionalProperties value to set. * @return the FacetResult object itself. */ @@ -193,7 +191,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of FacetResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of FacetResult if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -207,7 +205,6 @@ public static FacetResult fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("count".equals(fieldName)) { deserializedFacetResult.count = reader.getNullable(JsonReader::getLong); } else if ("avg".equals(fieldName)) { @@ -228,12 +225,10 @@ public static FacetResult fromJson(JsonReader jsonReader) throws IOException { if (additionalProperties == null) { additionalProperties = new LinkedHashMap<>(); } - additionalProperties.put(fieldName, reader.readUntyped()); } } deserializedFacetResult.additionalProperties = additionalProperties; - return deserializedFacetResult; }); } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/GetDocumentOptions.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/GetDocumentOptions.java deleted file mode 100644 index 1dd90f5d1e52..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/GetDocumentOptions.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.annotation.Fluent; - -import java.util.Arrays; -import java.util.List; - -/** - * Additional parameters for getDocument operation. - * - * @param The type of the document to retrieve. - */ -@Fluent -public final class GetDocumentOptions { - /* - * The key of the document to retrieve. - */ - private final String key; - - /* - * The model class converts search result. - */ - private final Class modelClass; - - /* - * The list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema are included. - */ - private List selectedFields; - - /* - * A value that specifies whether to enable elevated read for the document retrieval. - * Elevated read allows the request to read the latest committed index changes and bypass standard ACL filtering. - */ - private Boolean enableElevatedRead; - - /** - * Creates an instance of {@link GetDocumentOptions} with required parameters. - * - * @param key The key of the document to retrieve. - * @param modelClass The model class converts search result. - */ - public GetDocumentOptions(String key, Class modelClass) { - this.key = key; - this.modelClass = modelClass; - } - - /** - * Get the key property: The key of the document to retrieve. - * - * @return the key value. - */ - public String getKey() { - return this.key; - } - - /** - * Get the modelClass property: The model class converts search result. - * - * @return the modelClass value. - */ - public Class getModelClass() { - return this.modelClass; - } - - /** - * Get the selectedFields property: The list of fields to retrieve. If unspecified, all fields marked as - * retrievable in the schema are included. - * - * @return the selectedFields value. - */ - public List getSelectedFields() { - return this.selectedFields; - } - - /** - * Set the selectedFields property: The list of fields to retrieve. If unspecified, all fields marked as - * retrievable in the schema are included. - * - * @param selectedFields the selectedFields value to set. - * @return the GetDocumentOptions object itself. - */ - public GetDocumentOptions setSelectedFields(String... selectedFields) { - this.selectedFields = (selectedFields == null) ? null : Arrays.asList(selectedFields); - return this; - } - - /** - * Set the selectedFields property: The list of fields to retrieve. If unspecified, all fields marked as - * retrievable in the schema are included. - * - * @param selectedFields the selectedFields value to set. - * @return the GetDocumentOptions object itself. - */ - public GetDocumentOptions setSelectedFields(List selectedFields) { - this.selectedFields = selectedFields; - return this; - } - - /** - * Get the enableElevatedRead property: A value that specifies whether to enable elevated read for the document - * retrieval. Elevated read allows the request to read the latest committed index changes and bypass standard ACL filtering. - * - * @return the enableElevatedRead value. - */ - public Boolean isElevatedReadEnabled() { - return this.enableElevatedRead; - } - - /** - * Set the enableElevatedRead property: A value that specifies whether to enable elevated read for the document - * retrieval. Elevated read allows the request to read the latest committed index changes and bypass standard ACL filtering. - * - * @param enableElevatedRead the enableElevatedRead value to set. - * @return the GetDocumentOptions object itself. - */ - public GetDocumentOptions setElevatedReadEnabled(Boolean enableElevatedRead) { - this.enableElevatedRead = enableElevatedRead; - return this; - } -} 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 8f111ba6844c..985054fec167 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -15,6 +12,7 @@ * 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'. @@ -31,7 +29,7 @@ public final class HybridCountAndFacetMode extends ExpandableStringEnum { + /* * 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 @@ -49,7 +47,7 @@ public HybridSearch() { * 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 @@ -63,7 +61,7 @@ public Integer getMaxTextRecallSize() { * 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. */ @@ -76,7 +74,7 @@ public HybridSearch setMaxTextRecallSize(Integer maxTextRecallSize) { /** * Get the countAndFacetMode property: 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. - * + * * @return the countAndFacetMode value. */ @Generated @@ -87,7 +85,7 @@ public HybridCountAndFacetMode getCountAndFacetMode() { /** * Set the countAndFacetMode property: 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. - * + * * @param countAndFacetMode the countAndFacetMode value to set. * @return the HybridSearch object itself. */ @@ -112,7 +110,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of HybridSearch from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of HybridSearch if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -125,7 +123,6 @@ public static HybridSearch fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("maxTextRecallSize".equals(fieldName)) { deserializedHybridSearch.maxTextRecallSize = reader.getNullable(JsonReader::getInt); } else if ("countAndFacetMode".equals(fieldName)) { @@ -134,7 +131,6 @@ public static HybridSearch fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedHybridSearch; }); } 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..8c6b0915d307 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,130 @@ // 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.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. + * Get the actionType property: The operation to perform on a document in an indexing batch. * - * @return the document value. + * @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. + * Set the actionType property: The operation to perform on a document in an indexing batch. * - * @param document the document value to set. + * @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. + * Get the additionalProperties property: Represents an index action that operates on a document. * - * @return the actionType value. + * @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. + * Set the additionalProperties property: Represents an index action that operates on a document. * - * @param actionType the actionType value to set. + * @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.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); } /** - * The private getter to get the properties via {@link IndexActionHelper.IndexActionAccessor}. + * Reads an instance of IndexAction from the JsonReader. * - * @return The properties + * @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.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..7dc29a6ad3d8 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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 index 7e4b4a7f9f28..ba04f3242eeb 100644 --- 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 @@ -4,12 +4,11 @@ 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.Objects; import java.util.Set; -import java.util.function.Function; import java.util.stream.Collectors; /** @@ -24,7 +23,7 @@ public final class IndexBatchException extends AzureException { /** * Indexing results. */ - private final ArrayList results; + private final List results; /** * Constructs an {@code IndexBatchException} from the given {@link IndexDocumentsResult}. @@ -43,23 +42,15 @@ public IndexBatchException(IndexDocumentsResult result) { * @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); + public IndexDocumentsBatch findFailedActionsToRetry(IndexDocumentsBatch originalBatch, String keyFieldName) { + Set uniqueRetriableKeys = getIndexingResults().stream() + .filter(result -> isRetriableStatusCode(result.getStatusCode())) + .map(IndexingResult::getKey) + .collect(Collectors.toSet()); + return new IndexDocumentsBatch(originalBatch.getActions() + .stream() + .filter(action -> isActionIncluded(action, uniqueRetriableKeys, keyFieldName)) + .collect(Collectors.toList())); } /** @@ -76,24 +67,9 @@ private static String createMessage(IndexDocumentsResult result) { 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; + private static boolean isActionIncluded(IndexAction action, Set uniqueRetriableKeys, String keyFieldName) { + return action.getAdditionalProperties() != null + && uniqueRetriableKeys.contains(Objects.toString(action.getAdditionalProperties().get(keyFieldName), null)); } /** 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/IndexDocumentsBatch.java similarity index 66% 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/IndexDocumentsBatch.java index b69a847f5590..79e8eb42f6a2 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/IndexDocumentsBatch.java @@ -1,10 +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. - -package com.azure.search.documents.implementation.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.annotation.Immutable; @@ -13,13 +10,15 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Arrays; import java.util.List; /** * Contains a batch of document write actions to send to the index. */ @Immutable -public final class IndexBatch implements JsonSerializable { +public final class IndexDocumentsBatch implements JsonSerializable { + /* * The actions in the batch. */ @@ -27,18 +26,27 @@ public final class IndexBatch implements JsonSerializable { private final List actions; /** - * Creates an instance of IndexBatch class. - * + * Creates an instance of IndexDocumentsBatch class. + * + * @param actions the actions value to set. + */ + public IndexDocumentsBatch(IndexAction... actions) { + this.actions = (actions == null) ? null : Arrays.asList(actions); + } + + /** + * Creates an instance of IndexDocumentsBatch class. + * * @param actions the actions value to set. */ @Generated - public IndexBatch(List actions) { + public IndexDocumentsBatch(List actions) { this.actions = actions; } /** * Get the actions property: The actions in the batch. - * + * * @return the actions value. */ @Generated @@ -58,34 +66,28 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { } /** - * Reads an instance of IndexBatch from the JsonReader. - * + * Reads an instance of IndexDocumentsBatch from the JsonReader. + * * @param jsonReader The JsonReader being read. - * @return An instance of IndexBatch if the JsonReader was pointing to an instance of it, or null if it was pointing - * to JSON null. + * @return An instance of IndexDocumentsBatch 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 IndexBatch. + * @throws IOException If an error occurs while reading the IndexDocumentsBatch. */ @Generated - public static IndexBatch fromJson(JsonReader jsonReader) throws IOException { + public static IndexDocumentsBatch 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(); reader.nextToken(); - 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 IndexDocumentsBatch(actions); }); } } 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 383cdce0ae2e..84521a04ae6c 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -20,25 +17,23 @@ */ @Immutable public final class IndexDocumentsResult implements JsonSerializable { + /* * The list of status information for each document in the indexing request. */ @Generated - private final List results; + private List results; /** * Creates an instance of IndexDocumentsResult class. - * - * @param results the results value to set. */ @Generated - public IndexDocumentsResult(List results) { - this.results = results; + private IndexDocumentsResult() { } /** * Get the results property: The list of status information for each document in the indexing request. - * + * * @return the results value. */ @Generated @@ -58,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of IndexDocumentsResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of IndexDocumentsResult if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -68,23 +63,18 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static IndexDocumentsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; - List results = null; + IndexDocumentsResult deserializedIndexDocumentsResult = new IndexDocumentsResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - results = reader.readArray(reader1 -> IndexingResult.fromJson(reader1)); - resultsFound = true; + List results = reader.readArray(reader1 -> IndexingResult.fromJson(reader1)); + deserializedIndexDocumentsResult.results = results; } else { reader.skipChildren(); } } - if (resultsFound) { - return new IndexDocumentsResult(results); - } - throw new IllegalStateException("Missing required property: value"); + return deserializedIndexDocumentsResult; }); } } 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 582f1919269f..a8b51e10767b 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -12,55 +10,45 @@ 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; + private String key; - /** + /* * 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. */ @Generated - private final boolean succeeded; + private 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. */ @Generated - private final int statusCode; + private 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. */ @Generated - public IndexingResult(String key, boolean succeeded, int statusCode) { - this.key = key; - this.succeeded = succeeded; - this.statusCode = statusCode; + public IndexingResult() { } /** @@ -130,50 +118,23 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; + IndexingResult deserializedIndexingResult = new IndexingResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); if ("key".equals(fieldName)) { - key = reader.getString(); - keyFound = true; + deserializedIndexingResult.key = reader.getString(); } else if ("status".equals(fieldName)) { - succeeded = reader.getBoolean(); - succeededFound = true; + deserializedIndexingResult.succeeded = reader.getBoolean(); } else if ("statusCode".equals(fieldName)) { - statusCode = reader.getInt(); - statusCodeFound = true; + deserializedIndexingResult.statusCode = reader.getInt(); } else if ("errorMessage".equals(fieldName)) { - errorMessage = reader.getString(); + deserializedIndexingResult.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)); + return deserializedIndexingResult; }); } - - private static final long serialVersionUID = -8604424005271188140L; } 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..9b6e36cd3965 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/LookupDocument.java @@ -0,0 +1,85 @@ +// 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; +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.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + 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.readUntyped()); + } + deserializedLookupDocument.additionalProperties = additionalProperties; + return deserializedLookupDocument; + }); + } +} 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 11e15d14129e..2adac3c57ea3 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -115,6 +113,20 @@ public Map getAdditionalProperties() { return this.additionalProperties; } + /** + * Set 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. + * + * @param additionalProperties the additionalProperties value to set. + * @return the QueryAnswerResult object itself. + */ + @Generated + public QueryAnswerResult setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + /** * {@inheritDoc} */ 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 377b7fd09414..20862f5efa7c 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -21,6 +18,7 @@ * 'extractive|maxcharlength-600'. */ public final class QueryAnswerType extends ExpandableStringEnum { + /** * Do not return answers for the query. */ @@ -36,7 +34,7 @@ public final class QueryAnswerType extends ExpandableStringEnum /** * Creates a new instance of QueryAnswerType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -46,7 +44,7 @@ public QueryAnswerType() { /** * Creates or finds a QueryAnswerType from its string representation. - * + * * @param name a name to look for. * @return the corresponding QueryAnswerType. */ @@ -57,7 +55,7 @@ public static QueryAnswerType fromString(String name) { /** * Gets known QueryAnswerType values. - * + * * @return known QueryAnswerType values. */ @Generated 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 c1cff2dcafb0..1edad98f0367 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,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.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; @@ -19,7 +17,7 @@ * 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 { /* @@ -45,7 +43,7 @@ public final class QueryCaptionResult implements JsonSerializable { + /** * Do not return captions for the query. */ @@ -33,7 +31,7 @@ public final class QueryCaptionType extends ExpandableStringEnum { + /** * No query debugging information will be returned. */ @@ -53,7 +51,7 @@ public final class QueryDebugMode extends ExpandableStringEnum { /** * Creates a new instance of QueryDebugMode value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -63,7 +61,7 @@ public QueryDebugMode() { /** * Creates or finds a QueryDebugMode from its string representation. - * + * * @param name a name to look for. * @return the corresponding QueryDebugMode. */ @@ -74,7 +72,7 @@ public static QueryDebugMode fromString(String name) { /** * Gets known QueryDebugMode values. - * + * * @return known QueryDebugMode values. */ @Generated 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 2b5beab0fd4f..4229b9855cab 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -14,6 +11,7 @@ * The language of the query. */ public final class QueryLanguage extends ExpandableStringEnum { + /** * Query language not specified. */ @@ -448,7 +446,7 @@ public final class QueryLanguage extends ExpandableStringEnum { /** * Creates a new instance of QueryLanguage value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -458,7 +456,7 @@ public QueryLanguage() { /** * Creates or finds a QueryLanguage from its string representation. - * + * * @param name a name to look for. * @return the corresponding QueryLanguage. */ @@ -469,7 +467,7 @@ public static QueryLanguage fromString(String name) { /** * Gets known QueryLanguage values. - * + * * @return known QueryLanguage values. */ @Generated diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java index 21ffc8ed963e..8f877c9b7160 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java @@ -1,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -21,6 +18,7 @@ */ @Immutable public final class QueryResultDocumentInnerHit implements JsonSerializable { + /* * Position of this specific matching element within it's original collection. Position starts at 0. */ @@ -37,13 +35,13 @@ public final class QueryResultDocumentInnerHit implements JsonSerializable { + /* * The raw string for the title field that was used for semantic enrichment. */ @@ -41,12 +39,12 @@ public final class QueryResultDocumentRerankerInput implements JsonSerializable< * Creates an instance of QueryResultDocumentRerankerInput class. */ @Generated - public QueryResultDocumentRerankerInput() { + private QueryResultDocumentRerankerInput() { } /** * Get the title property: The raw string for the title field that was used for semantic enrichment. - * + * * @return the title value. */ @Generated @@ -57,7 +55,7 @@ public String getTitle() { /** * Get the content property: The raw concatenated strings for the content fields that were used for semantic * enrichment. - * + * * @return the content value. */ @Generated @@ -68,7 +66,7 @@ public String getContent() { /** * Get the keywords property: The raw concatenated strings for the keyword fields that were used for semantic * enrichment. - * + * * @return the keywords value. */ @Generated @@ -88,7 +86,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of QueryResultDocumentRerankerInput from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of QueryResultDocumentRerankerInput if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -102,7 +100,6 @@ public static QueryResultDocumentRerankerInput fromJson(JsonReader jsonReader) t while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("title".equals(fieldName)) { deserializedQueryResultDocumentRerankerInput.title = reader.getString(); } else if ("content".equals(fieldName)) { @@ -113,7 +110,6 @@ public static QueryResultDocumentRerankerInput fromJson(JsonReader jsonReader) t reader.skipChildren(); } } - return 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 3cfecfe7f609..966051909abf 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -19,6 +16,7 @@ */ @Immutable public final class QueryResultDocumentSemanticField implements JsonSerializable { + /* * The name of the field that was sent to the semantic enrichment process */ @@ -35,12 +33,12 @@ public final class QueryResultDocumentSemanticField implements JsonSerializable< * Creates an instance of QueryResultDocumentSemanticField class. */ @Generated - public QueryResultDocumentSemanticField() { + private QueryResultDocumentSemanticField() { } /** * Get the name property: The name of the field that was sent to the semantic enrichment process. - * + * * @return the name value. */ @Generated @@ -51,7 +49,7 @@ public String getName() { /** * 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 @@ -71,7 +69,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of QueryResultDocumentSemanticField from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of QueryResultDocumentSemanticField if the JsonReader was pointing to an instance of it, or * null if it was pointing to JSON null. @@ -85,7 +83,6 @@ public static QueryResultDocumentSemanticField fromJson(JsonReader jsonReader) t while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("name".equals(fieldName)) { deserializedQueryResultDocumentSemanticField.name = reader.getString(); } else if ("state".equals(fieldName)) { @@ -95,7 +92,6 @@ public static QueryResultDocumentSemanticField fromJson(JsonReader jsonReader) t reader.skipChildren(); } } - return 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 85cd2ad7d052..407d67f8a42f 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -22,6 +19,7 @@ */ @Immutable public final class QueryResultDocumentSubscores implements JsonSerializable { + /* * The BM25 or Classic score for the text portion of the query. */ @@ -29,7 +27,7 @@ public final class QueryResultDocumentSubscores implements JsonSerializable> vectors; @@ -44,12 +42,12 @@ public final class QueryResultDocumentSubscores implements JsonSerializable> getVectors() { /** * Get the documentBoost property: The BM25 or Classic score for the text portion of the query. - * + * * @return the documentBoost value. */ @Generated @@ -89,7 +87,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of QueryResultDocumentSubscores from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of QueryResultDocumentSubscores if the JsonReader was pointing to an instance of it, or null * if it was pointing to JSON null. @@ -102,7 +100,6 @@ public static QueryResultDocumentSubscores fromJson(JsonReader jsonReader) throw while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("text".equals(fieldName)) { deserializedQueryResultDocumentSubscores.text = TextResult.fromJson(reader); } else if ("vectors".equals(fieldName)) { @@ -115,7 +112,6 @@ public static QueryResultDocumentSubscores fromJson(JsonReader jsonReader) throw reader.skipChildren(); } } - return deserializedQueryResultDocumentSubscores; }); } 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 dc7f9590c4c2..7a59a6f5c842 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -20,6 +17,7 @@ */ @Immutable public final class QueryRewritesDebugInfo implements JsonSerializable { + /* * List of query rewrites generated for the text query. */ @@ -36,12 +34,12 @@ public final class QueryRewritesDebugInfo implements JsonSerializable { + /** * Do not generate additional query rewrites for this query. */ @@ -31,7 +29,7 @@ public final class QueryRewritesType extends ExpandableStringEnum { + /* * 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. @@ -37,13 +35,13 @@ public final class QueryRewritesValuesDebugInfo implements JsonSerializable { + /** * Speller not enabled. */ @@ -29,7 +27,7 @@ public final class QuerySpellerType 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. */ - 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. */ - 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. */ - 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. - * - * @param value the serialized value to parse. - * @return the parsed QueryType object, or null if unable to parse. + * Creates or finds a QueryType from its string representation. + * + * @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/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/models/ScoringStatistics.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/ScoringStatistics.java index de1aac30cf37..fec642f2ec4b 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchContinuationToken.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchContinuationToken.java new file mode 100644 index 000000000000..0a162becba6b --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchContinuationToken.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.models; + +import com.azure.json.JsonSerializable; +import com.azure.json.JsonWriter; +import com.azure.search.documents.SearchServiceVersion; + +import java.io.IOException; + +/** + * Continuation token used when searching documents to iterate through REST API pages. + */ +public final class SearchContinuationToken implements JsonSerializable { + private final SearchRequest nextPageParameters; + private final SearchServiceVersion apiVersion; + + /** + * Creates a new {@link SearchContinuationToken}. + * + * @param nextPageParameters The {@link SearchRequest} to use when retrieving the next page of search results. + * @param apiVersion The {@link SearchServiceVersion} used when searching, subsequent page requests must use the + * same {@link SearchServiceVersion}. + */ + public SearchContinuationToken(SearchRequest nextPageParameters, SearchServiceVersion apiVersion) { + this.nextPageParameters = nextPageParameters; + this.apiVersion = apiVersion; + } + + /** + * 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. + * + * @return the nextPageParameters value. + */ + public SearchRequest getNextPageParameters() { + return this.nextPageParameters; + } + + /** + * Gets the apiVersion property: API version used when sending the query request. Must remain consistent for all + * requests in the paged operation. + * + * @return the apiVersion value. + */ + public SearchServiceVersion getApiVersion() { + return this.apiVersion; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeJsonField("nextPageParameters", nextPageParameters) + .writeStringField("apiVersion", apiVersion.getVersion()) + .writeEndObject(); + } +} 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 69% 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 5c5a68990a74..8c8282a080c3 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,10 +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. - -package com.azure.search.documents.implementation.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.annotation.Immutable; @@ -12,12 +9,6 @@ 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,6 +18,7 @@ */ @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 @@ -64,8 +56,7 @@ public final class SearchDocumentsResult implements JsonSerializable results; + private List results; /* * Continuation URL returned when the query can't return all the requested results in a single response. You can use @@ -104,12 +95,9 @@ public final class SearchDocumentsResult implements JsonSerializable results) { - this.results = results; + public SearchDocumentsResult() { } /** @@ -117,7 +105,7 @@ public SearchDocumentsResult(List results) { * 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 @@ -128,7 +116,7 @@ public Long getCount() { /** * 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 @@ -139,7 +127,7 @@ public Double getCoverage() { /** * 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 @@ -150,7 +138,7 @@ public Map> getFacets() { /** * 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 @@ -160,7 +148,7 @@ public List getAnswers() { /** * Get the debugInfo property: Debug information that applies to the search results as a whole. - * + * * @return the debugInfo value. */ @Generated @@ -170,9 +158,8 @@ public DebugInfo getDebugInfo() { /** * 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 @@ -182,7 +169,7 @@ public SearchRequest getNextPageParameters() { /** * Get the results property: The sequence of results returned by the query. - * + * * @return the results value. */ @Generated @@ -194,7 +181,7 @@ public List getResults() { * 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 @@ -205,7 +192,7 @@ public String getNextLink() { /** * Get the semanticPartialResponseReason property: Reason that a partial response was returned for a semantic * ranking request. - * + * * @return the semanticPartialResponseReason value. */ @Generated @@ -216,7 +203,7 @@ public SemanticErrorReason getSemanticPartialResponseReason() { /** * Get the semanticPartialResponseType property: Type of partial response that was returned for a semantic ranking * request. - * + * * @return the semanticPartialResponseType value. */ @Generated @@ -226,7 +213,7 @@ public SemanticSearchResultsType getSemanticPartialResponseType() { /** * Get the semanticQueryRewritesResultType property: Type of query rewrite that was used to retrieve documents. - * + * * @return the semanticQueryRewritesResultType value. */ @Generated @@ -246,7 +233,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchDocumentsResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchDocumentsResult if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -256,65 +243,44 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; + SearchDocumentsResult deserializedSearchDocumentsResult = new SearchDocumentsResult(); 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; + List results = reader.readArray(reader1 -> SearchResult.fromJson(reader1)); + deserializedSearchDocumentsResult.results = results; } else if ("@odata.count".equals(fieldName)) { - count = reader.getNullable(JsonReader::getLong); + deserializedSearchDocumentsResult.count = reader.getNullable(JsonReader::getLong); } else if ("@search.coverage".equals(fieldName)) { - coverage = reader.getNullable(JsonReader::getDouble); + deserializedSearchDocumentsResult.coverage = reader.getNullable(JsonReader::getDouble); } else if ("@search.facets".equals(fieldName)) { - facets = reader.readMap(reader1 -> reader1.readArray(reader2 -> FacetResult.fromJson(reader2))); + Map> facets + = reader.readMap(reader1 -> reader1.readArray(reader2 -> FacetResult.fromJson(reader2))); + deserializedSearchDocumentsResult.facets = facets; } else if ("@search.answers".equals(fieldName)) { - answers = reader.readArray(reader1 -> QueryAnswerResult.fromJson(reader1)); + List answers = reader.readArray(reader1 -> QueryAnswerResult.fromJson(reader1)); + deserializedSearchDocumentsResult.answers = answers; } else if ("@search.debug".equals(fieldName)) { - debugInfo = DebugInfo.fromJson(reader); + deserializedSearchDocumentsResult.debugInfo = DebugInfo.fromJson(reader); } else if ("@search.nextPageParameters".equals(fieldName)) { - nextPageParameters = SearchRequest.fromJson(reader); + deserializedSearchDocumentsResult.nextPageParameters = SearchRequest.fromJson(reader); } else if ("@odata.nextLink".equals(fieldName)) { - nextLink = reader.getString(); + deserializedSearchDocumentsResult.nextLink = reader.getString(); } else if ("@search.semanticPartialResponseReason".equals(fieldName)) { - semanticPartialResponseReason = SemanticErrorReason.fromString(reader.getString()); + deserializedSearchDocumentsResult.semanticPartialResponseReason + = SemanticErrorReason.fromString(reader.getString()); } else if ("@search.semanticPartialResponseType".equals(fieldName)) { - semanticPartialResponseType = SemanticSearchResultsType.fromString(reader.getString()); + deserializedSearchDocumentsResult.semanticPartialResponseType + = SemanticSearchResultsType.fromString(reader.getString()); } else if ("@search.semanticQueryRewritesResultType".equals(fieldName)) { - semanticQueryRewritesResultType = SemanticQueryRewritesResultType.fromString(reader.getString()); + deserializedSearchDocumentsResult.semanticQueryRewritesResultType + = SemanticQueryRewritesResultType.fromString(reader.getString()); } else { reader.skipChildren(); } } - if (resultsFound) { - 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/SearchMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchMode.java index 992764eb1ec7..7aa49c934050 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; 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 index 001b21a8d50e..4204e9e0c04c 100644 --- 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 @@ -1,48 +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.Fluent; - +import com.azure.core.annotation.Generated; import java.util.Arrays; import java.util.List; /** - * Additional parameters for searchGet operation. + * Options for search API. */ @Fluent public final class SearchOptions { + + /* + * Token identifying the user for which the query is being executed. This token is used to enforce security + * restrictions on documents. + */ + @Generated + private String querySourceAuthorization; + + /* + * A value that enables elevated read that bypass document level permission checks for the query operation. + */ + @Generated + private Boolean enableElevatedRead; + /* * 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 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. */ + @Generated private List facets; /* * The OData $filter expression to apply to the search query. */ + @Generated private String filter; /* - * The 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 List highlightFields; /* * 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>. */ + @Generated private String highlightPreTag; /* @@ -50,73 +71,110 @@ public final class SearchOptions { * 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 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. + * 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 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. */ + @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. + */ + @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. + */ + @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). */ - private List scoringParameters; + @Generated + private List scoringParameters; /* * The name of a scoring profile to evaluate match scores for matching documents in order to sort the results. */ + @Generated 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. + * 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. + */ + @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. + */ + @Generated 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. */ + @Generated 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. + * A value that specifies the language of the search query. */ - private ScoringStatistics scoringStatistics; + @Generated + private QueryLanguage queryLanguage; /* - * 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. + * A value that specifies the type of the speller to use to spell-correct individual search query terms. */ - private String sessionId; + @Generated + private QuerySpellerType querySpeller; /* - * The 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 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. + * 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; /* @@ -124,40 +182,135 @@ public final class SearchOptions { * 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; /* - * Enables a debugging tool that can be used to further explore your search results. + * The name of a semantic configuration that will be used when processing documents for queries of type semantic. */ - private QueryDebugMode debug; + @Generated + private String semanticConfigurationName; /* - * The language of the query. + * Allows the user to choose whether a semantic call should fail completely (default / current behavior), or to + * return partial results. */ - private QueryLanguage queryLanguage; + @Generated + private SemanticErrorMode semanticErrorHandling; /* - * Improve search recall by spell-correcting individual search query terms. + * 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 QuerySpellerType speller; + @Generated + private Integer semanticMaxWaitInMilliseconds; - private SemanticSearchOptions semanticSearchOptions; - private VectorSearchOptions vectorSearchOptions; + /* + * 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; /* - * Specifies whether to enable elevated read for search requests. When enabled, and when the caller has the required RBAC role, - * elevated read allows the search request to access all documents in the index, including those with restricted ACLs. - * This feature is intended for administrative and investigative scenarios and should be used with care, as it bypasses standard ACL filtering. - * Standard queries (without elevated read) only return public documents or those the caller is authorized to access. - */ - private Boolean enableElevatedRead; + * A value that specifies whether answers should be returned as part of the search response. + */ + @Generated + private QueryAnswerType answers; + + /* + * A value that specifies whether captions should be returned as part of the search response. + */ + @Generated + private QueryCaptionType captions; + + /* + * A value that specifies whether query rewrites should be generated to augment the search query. + */ + @Generated + private QueryRewritesType queryRewrites; + + /* + * The comma-separated list of field names used for semantic ranking. + */ + @Generated + private List 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. + */ + @Generated + private VectorFilterMode vectorFilterMode; + + /* + * The query parameters to configure hybrid search behaviors. + */ + @Generated + private HybridSearch hybridSearch; /** - * Creates an instance of {@link SearchOptions}. + * Creates an instance of SearchOptions class. */ + @Generated public SearchOptions() { } + /** + * Get the querySourceAuthorization property: Token identifying the user for which the query is being executed. This + * token is used to enforce security restrictions on documents. + * + * @return the querySourceAuthorization value. + */ + @Generated + public String getQuerySourceAuthorization() { + return this.querySourceAuthorization; + } + + /** + * Set the querySourceAuthorization property: Token identifying the user for which the query is being executed. This + * token is used to enforce security restrictions on documents. + * + * @param querySourceAuthorization the querySourceAuthorization value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setQuerySourceAuthorization(String querySourceAuthorization) { + this.querySourceAuthorization = querySourceAuthorization; + return this; + } + + /** + * Get the enableElevatedRead property: A value that enables elevated read that bypass document level permission + * checks for the query operation. + * + * @return the enableElevatedRead value. + */ + @Generated + public Boolean isEnableElevatedRead() { + return this.enableElevatedRead; + } + + /** + * Set the enableElevatedRead property: A value that enables elevated read that bypass document level permission + * checks for the query operation. + * + * @param enableElevatedRead the enableElevatedRead value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setEnableElevatedRead(Boolean enableElevatedRead) { + this.enableElevatedRead = enableElevatedRead; + return this; + } + /** * 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 @@ -165,7 +318,8 @@ public SearchOptions() { * * @return the includeTotalCount value. */ - public Boolean isTotalCountIncluded() { + @Generated + public Boolean isIncludeTotalCount() { return this.includeTotalCount; } @@ -177,6 +331,7 @@ public Boolean isTotalCountIncluded() { * @param includeTotalCount the includeTotalCount value to set. * @return the SearchOptions object itself. */ + @Generated public SearchOptions setIncludeTotalCount(Boolean includeTotalCount) { this.includeTotalCount = includeTotalCount; return this; @@ -188,6 +343,7 @@ public SearchOptions setIncludeTotalCount(Boolean includeTotalCount) { * * @return the facets value. */ + @Generated public List getFacets() { return this.facets; } @@ -200,7 +356,20 @@ public List getFacets() { * @return the SearchOptions object itself. */ public SearchOptions setFacets(String... facets) { - this.facets = (facets == null) ? null : java.util.Arrays.asList(facets); + this.facets = (facets == null) ? null : Arrays.asList(facets); + 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. + */ + @Generated + public SearchOptions setFacets(List facets) { + this.facets = facets; return this; } @@ -209,6 +378,7 @@ public SearchOptions setFacets(String... facets) { * * @return the filter value. */ + @Generated public String getFilter() { return this.filter; } @@ -219,24 +389,26 @@ public String getFilter() { * @param filter the filter value to set. * @return the SearchOptions object itself. */ + @Generated 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. + * Get the highlightFields property: The comma-separated list of field names to use for hit highlights. Only + * searchable fields can be used for hit highlighting. * * @return the highlightFields value. */ + @Generated 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. + * Set the highlightFields property: The comma-separated 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. @@ -246,12 +418,26 @@ public SearchOptions setHighlightFields(String... highlightFields) { return this; } + /** + * Set the highlightFields property: The comma-separated 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. + */ + @Generated + 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. */ + @Generated public String getHighlightPostTag() { return this.highlightPostTag; } @@ -263,6 +449,7 @@ public String getHighlightPostTag() { * @param highlightPostTag the highlightPostTag value to set. * @return the SearchOptions object itself. */ + @Generated public SearchOptions setHighlightPostTag(String highlightPostTag) { this.highlightPostTag = highlightPostTag; return this; @@ -274,6 +461,7 @@ public SearchOptions setHighlightPostTag(String highlightPostTag) { * * @return the highlightPreTag value. */ + @Generated public String getHighlightPreTag() { return this.highlightPreTag; } @@ -285,6 +473,7 @@ public String getHighlightPreTag() { * @param highlightPreTag the highlightPreTag value to set. * @return the SearchOptions object itself. */ + @Generated public SearchOptions setHighlightPreTag(String highlightPreTag) { this.highlightPreTag = highlightPreTag; return this; @@ -297,6 +486,7 @@ public SearchOptions setHighlightPreTag(String highlightPreTag) { * * @return the minimumCoverage value. */ + @Generated public Double getMinimumCoverage() { return this.minimumCoverage; } @@ -309,36 +499,54 @@ public Double getMinimumCoverage() { * @param minimumCoverage the minimumCoverage value to set. * @return the SearchOptions object itself. */ + @Generated 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. + * 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 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. + * 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 SearchOptions object itself. */ public SearchOptions setOrderBy(String... orderBy) { - this.orderBy = (orderBy == null) ? null : java.util.Arrays.asList(orderBy); + this.orderBy = (orderBy == null) ? null : Arrays.asList(orderBy); + return this; + } + + /** + * 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 SearchOptions object itself. + */ + @Generated + public SearchOptions setOrderBy(List orderBy) { + this.orderBy = orderBy; return this; } @@ -348,6 +556,7 @@ public SearchOptions setOrderBy(String... orderBy) { * * @return the queryType value. */ + @Generated public QueryType getQueryType() { return this.queryType; } @@ -359,43 +568,116 @@ public QueryType getQueryType() { * @param queryType the queryType value to set. * @return the SearchOptions object itself. */ + @Generated public SearchOptions setQueryType(QueryType queryType) { this.queryType = queryType; 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. 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. + * + * @param scoringStatistics the scoringStatistics value to set. + * @return the SearchOptions object itself. + */ + @Generated + 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 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. + * + * @param sessionId the sessionId value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setSessionId(String sessionId) { + this.sessionId = sessionId; + 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). + * 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() { + @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). + * 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) { + public SearchOptions setScoringParameters(String... scoringParameters) { this.scoringParameters = (scoringParameters == null) ? null : Arrays.asList(scoringParameters); return this; } + /** + * 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. + */ + @Generated + 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. */ + @Generated public String getScoringProfile() { return this.scoringProfile; } @@ -407,32 +689,94 @@ public String getScoringProfile() { * @param scoringProfile the scoringProfile value to set. * @return the SearchOptions object itself. */ + @Generated 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. + * 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. + * + * @param debug the debug value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions 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. + * + * @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. + * + * @param searchText the searchText value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setSearchText(String searchText) { + this.searchText = searchText; + return this; + } + + /** + * 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. * * @return the searchFields value. */ + @Generated 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. + * 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. * * @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); + this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); + return this; + } + + /** + * 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. + * + * @param searchFields the searchFields value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setSearchFields(List searchFields) { + this.searchFields = searchFields; return this; } @@ -442,6 +786,7 @@ public SearchOptions setSearchFields(String... searchFields) { * * @return the searchMode value. */ + @Generated public SearchMode getSearchMode() { return this.searchMode; } @@ -453,102 +798,115 @@ public SearchMode getSearchMode() { * @param searchMode the searchMode value to set. * @return the SearchOptions object itself. */ + @Generated 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. + * Get the queryLanguage property: A value that specifies the language of the search query. * - * @return the scoringStatistics value. + * @return the queryLanguage value. */ - public ScoringStatistics getScoringStatistics() { - return this.scoringStatistics; + @Generated + public QueryLanguage getQueryLanguage() { + return this.queryLanguage; } /** - * 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. + * Set the queryLanguage property: A value that specifies the language of the search query. * - * @param scoringStatistics the scoringStatistics value to set. + * @param queryLanguage the queryLanguage value to set. * @return the SearchOptions object itself. */ - public SearchOptions setScoringStatistics(ScoringStatistics scoringStatistics) { - this.scoringStatistics = scoringStatistics; + @Generated + public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) { + this.queryLanguage = queryLanguage; 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. + * Get the querySpeller property: A value that specifies the type of the speller to use to spell-correct individual + * search query terms. * - * @return the sessionId value. + * @return the querySpeller value. */ - public String getSessionId() { - return this.sessionId; + @Generated + public QuerySpellerType getQuerySpeller() { + return this.querySpeller; } /** - * 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. + * Set the querySpeller property: A value that specifies the type of the speller to use to spell-correct individual + * search query terms. * - * @param sessionId the sessionId value to set. + * @param querySpeller the querySpeller value to set. * @return the SearchOptions object itself. */ - public SearchOptions setSessionId(String sessionId) { - this.sessionId = sessionId; + @Generated + public SearchOptions setQuerySpeller(QuerySpellerType querySpeller) { + this.querySpeller = querySpeller; return this; } /** - * Get the select property: The 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 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. + * 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 SearchOptions object itself. */ public SearchOptions setSelect(String... select) { - this.select = (select == null) ? null : java.util.Arrays.asList(select); + this.select = (select == null) ? null : Arrays.asList(select); + return this; + } + + /** + * 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 SearchOptions object itself. + */ + @Generated + 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. + * 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. + * 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. */ + @Generated public SearchOptions setSkip(Integer skip) { this.skip = skip; return this; @@ -561,6 +919,7 @@ public SearchOptions setSkip(Integer skip) { * * @return the top value. */ + @Generated public Integer getTop() { return this.top; } @@ -573,135 +932,291 @@ public Integer getTop() { * @param top the top value to set. * @return the SearchOptions object itself. */ + @Generated 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. + * Get the semanticConfigurationName property: The name of a semantic configuration that will be used when + * processing documents for queries of type semantic. * - * @return the debug value. + * @return the semanticConfigurationName value. */ - public QueryDebugMode getDebugMode() { - return this.debug; + @Generated + public String getSemanticConfigurationName() { + return this.semanticConfigurationName; } /** - * Set the debug property: Enables a debugging tool that can be used to further explore your search results. + * Set the semanticConfigurationName property: The name of a semantic configuration that will be used when + * processing documents for queries of type semantic. * - * @param debug the debug value to set. + * @param semanticConfigurationName the semanticConfigurationName value to set. * @return the SearchOptions object itself. */ - public SearchOptions setDebugMode(QueryDebugMode debug) { - this.debug = debug; + @Generated + public SearchOptions setSemanticConfigurationName(String semanticConfigurationName) { + this.semanticConfigurationName = semanticConfigurationName; return this; } /** - * Get the queryLanguage property: The language of the query. + * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely + * (default / current behavior), or to return partial results. * - * @return the queryLanguage value. + * @return the semanticErrorHandling value. */ - public QueryLanguage getQueryLanguage() { - return this.queryLanguage; + @Generated + public SemanticErrorMode getSemanticErrorHandling() { + return this.semanticErrorHandling; } /** - * Set the queryLanguage property: The language of the query. + * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely + * (default / current behavior), or to return partial results. * - * @param queryLanguage the queryLanguage value to set. + * @param semanticErrorHandling the semanticErrorHandling value to set. * @return the SearchOptions object itself. */ - public SearchOptions setQueryLanguage(QueryLanguage queryLanguage) { - this.queryLanguage = queryLanguage; + @Generated + public SearchOptions setSemanticErrorHandling(SemanticErrorMode semanticErrorHandling) { + this.semanticErrorHandling = semanticErrorHandling; return this; } /** - * Get the speller property: Improve search recall by spell-correcting individual search query terms. + * 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 speller value. + * @return the semanticMaxWaitInMilliseconds value. */ - public QuerySpellerType getSpeller() { - return this.speller; + @Generated + public Integer getSemanticMaxWaitInMilliseconds() { + return this.semanticMaxWaitInMilliseconds; } /** - * Set the speller property: Improve search recall by spell-correcting individual search query terms. + * 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 speller the speller value to set. + * @param semanticMaxWaitInMilliseconds the semanticMaxWaitInMilliseconds value to set. * @return the SearchOptions object itself. */ - public SearchOptions setSpeller(QuerySpellerType speller) { - this.speller = speller; + @Generated + public SearchOptions setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { + this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; return this; } /** - * Gets the semantic search options. + * 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 semantic search options. + * @return the semanticQuery value. */ - public SemanticSearchOptions getSemanticSearchOptions() { - return this.semanticSearchOptions; + @Generated + public String getSemanticQuery() { + return this.semanticQuery; } /** - * Sets the semantic search options. + * 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 semanticSearchOptions the semantic search options. + * @param semanticQuery the semanticQuery value to set. * @return the SearchOptions object itself. */ - public SearchOptions setSemanticSearchOptions(SemanticSearchOptions semanticSearchOptions) { - this.semanticSearchOptions = semanticSearchOptions; + @Generated + public SearchOptions setSemanticQuery(String semanticQuery) { + this.semanticQuery = semanticQuery; return this; } /** - * Sets the vector search options for vector and hybrid search queries. + * Get the answers property: A value that specifies whether answers should be returned as part of the search + * response. * - * @param vectorSearchOptions the vector search options. + * @return the answers value. + */ + @Generated + public QueryAnswerType getAnswers() { + return this.answers; + } + + /** + * 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 SearchOptions object itself. */ - public SearchOptions setVectorSearchOptions(VectorSearchOptions vectorSearchOptions) { - this.vectorSearchOptions = vectorSearchOptions; + @Generated + public SearchOptions setAnswers(QueryAnswerType answers) { + this.answers = answers; return this; } /** - * Get the vector search options for vector and hybrid search queries. + * Get the captions property: A value that specifies whether captions should be returned as part of the search + * response. * - * @return the vector search options. + * @return the captions value. */ - public VectorSearchOptions getVectorSearchOptions() { - return this.vectorSearchOptions; + @Generated + public QueryCaptionType getCaptions() { + return this.captions; } /** - * Get the enableElevatedRead property: A value that specifies whether to enable elevated read for search - * requests. Elevated read allows search requests to read the latest committed index changes, reducing the latency - * between document upload and their availability for search. This may have a negative impact on search request - * performance. + * Set the captions property: A value that specifies whether captions should be returned as part of the search + * response. * - * @return the enableElevatedRead value. + * @param captions the captions value to set. + * @return the SearchOptions object itself. */ - public Boolean isElevatedReadEnabled() { - return this.enableElevatedRead; + @Generated + public SearchOptions setCaptions(QueryCaptionType captions) { + this.captions = captions; + return this; } /** - * Set the enableElevatedRead property: A value that specifies whether to enable elevated read for search - * requests. Elevated read allows search requests to read the latest committed index changes, reducing the latency - * between document upload and their availability for search. This may have a negative impact on search request - * performance. + * Get the queryRewrites property: A value that specifies whether query rewrites should be generated to augment the + * search query. * - * @param enableElevatedRead the enableElevatedRead value to set. + * @return the queryRewrites value. + */ + @Generated + public QueryRewritesType getQueryRewrites() { + return this.queryRewrites; + } + + /** + * 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 SearchOptions object itself. */ - public SearchOptions setElevatedReadEnabled(Boolean enableElevatedRead) { - this.enableElevatedRead = enableElevatedRead; + @Generated + public SearchOptions setQueryRewrites(QueryRewritesType queryRewrites) { + this.queryRewrites = queryRewrites; return this; } + /** + * Get the semanticFields property: The comma-separated list of field names used for semantic ranking. + * + * @return the semanticFields value. + */ + @Generated + public List getSemanticFields() { + return this.semanticFields; + } + + /** + * Set the semanticFields property: The comma-separated list of field names used for semantic ranking. + * + * @param semanticFields the semanticFields value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setSemanticFields(String... semanticFields) { + this.semanticFields = (semanticFields == null) ? null : Arrays.asList(semanticFields); + return this; + } + + /** + * Set the semanticFields property: The comma-separated list of field names used for semantic ranking. + * + * @param semanticFields the semanticFields value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setSemanticFields(List semanticFields) { + this.semanticFields = semanticFields; + return this; + } + + /** + * Get the vectorQueries property: The query parameters for vector and hybrid search queries. + * + * @return the vectorQueries value. + */ + @Generated + public List getVectorQueries() { + return this.vectorQueries; + } + + /** + * Set the vectorQueries property: The query parameters for vector and hybrid search queries. + * + * @param vectorQueries the vectorQueries value to set. + * @return the SearchOptions object itself. + */ + public SearchOptions setVectorQueries(VectorQuery... vectorQueries) { + this.vectorQueries = (vectorQueries == null) ? null : Arrays.asList(vectorQueries); + return this; + } + + /** + * Set the vectorQueries property: The query parameters for vector and hybrid search queries. + * + * @param vectorQueries the vectorQueries value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setVectorQueries(List vectorQueries) { + this.vectorQueries = vectorQueries; + return this; + } + + /** + * 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. + * + * @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. + * + * @param vectorFilterMode the vectorFilterMode value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setVectorFilterMode(VectorFilterMode vectorFilterMode) { + this.vectorFilterMode = vectorFilterMode; + return this; + } + + /** + * Get the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @return the hybridSearch value. + */ + @Generated + public HybridSearch getHybridSearch() { + return this.hybridSearch; + } + + /** + * Set the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @param hybridSearch the hybridSearch value to set. + * @return the SearchOptions object itself. + */ + @Generated + public SearchOptions setHybridSearch(HybridSearch hybridSearch) { + this.hybridSearch = hybridSearch; + return this; + } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedFlux.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedFlux.java new file mode 100644 index 000000000000..93476ece8f23 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedFlux.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.models; + +import com.azure.core.util.paging.ContinuablePagedFluxCore; +import com.azure.core.util.paging.PageRetriever; +import com.azure.search.documents.SearchAsyncClient; + +import java.util.function.Supplier; + +/** + * Response type for {@link SearchAsyncClient#search(SearchOptions)}. + */ +public final class SearchPagedFlux + extends ContinuablePagedFluxCore { + + /** + * Creates a new instance of {@link SearchPagedFlux}. + * + * @param pageRetrieverProvider The {@link Supplier} that returns the {@link PageRetriever} that iterates over + * the paged results of searching. + */ + public SearchPagedFlux( + Supplier> pageRetrieverProvider) { + super(pageRetrieverProvider); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedIterable.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedIterable.java new file mode 100644 index 000000000000..2aa363e00b57 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedIterable.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.models; + +import com.azure.core.util.paging.ContinuablePagedIterable; +import com.azure.core.util.paging.PageRetrieverSync; +import com.azure.search.documents.SearchClient; + +import java.util.function.Supplier; + +/** + * Response type for {@link SearchClient#search(SearchOptions)}. + */ +public final class SearchPagedIterable + extends ContinuablePagedIterable { + + /** + * Creates a new instance of {@link SearchPagedIterable}. + * + * @param pageRetrieverProvider The {@link Supplier} that returns the {@link PageRetrieverSync} that iterates over + * the paged results of searching. + */ + public SearchPagedIterable( + Supplier> pageRetrieverProvider) { + super(pageRetrieverProvider, null, null); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedResponse.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedResponse.java new file mode 100644 index 000000000000..68576c887385 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SearchPagedResponse.java @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.models; + +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.rest.Response; +import com.azure.core.util.BinaryData; +import com.azure.core.util.IterableStream; +import com.azure.core.util.paging.ContinuablePage; +import com.azure.search.documents.SearchServiceVersion; + +import java.util.List; +import java.util.Map; + +/** + * Class representing a page returned by the search API. + */ +public final class SearchPagedResponse + implements ContinuablePage, Response> { + private final Response response; + private final SearchDocumentsResult page; + private final SearchContinuationToken continuationToken; + + /** + * Creates a new {@link SearchPagedResponse} from the paged response. + * + * @param response The response containing search result. + * @param serviceVersion The service version used to send the search request, used by the + * {@link #getContinuationToken() continuation token} to ensure iterating through pages remains on the same service + * version. + */ + public SearchPagedResponse(Response response, SearchServiceVersion serviceVersion) { + this.response = response; + this.page = response.getValue().toObject(SearchDocumentsResult.class); + this.continuationToken = (this.page.getNextPageParameters() != null) + ? new SearchContinuationToken(this.page.getNextPageParameters(), serviceVersion) + : null; + } + + /** + * 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. + */ + public Long getCount() { + return page.getCount(); + } + + /** + * 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. + */ + public Double getCoverage() { + return page.getCoverage(); + } + + /** + * 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. + */ + public Map> getFacets() { + return page.getFacets(); + } + + /** + * 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. + */ + public List getAnswers() { + return page.getAnswers(); + } + + /** + * Get the debugInfo property: Debug information that applies to the search results as a whole. + * + * @return the debugInfo value. + */ + public DebugInfo getDebugInfo() { + return page.getDebugInfo(); + } + + /** + * Get the semanticPartialResponseReason property: Reason that a partial response was returned for a semantic + * ranking request. + * + * @return the semanticPartialResponseReason value. + */ + public SemanticErrorReason getSemanticPartialResponseReason() { + return page.getSemanticPartialResponseReason(); + } + + /** + * Get the semanticPartialResponseType property: Type of partial response that was returned for a semantic ranking + * request. + * + * @return the semanticPartialResponseType value. + */ + public SemanticSearchResultsType getSemanticPartialResponseType() { + return page.getSemanticPartialResponseType(); + } + + /** + * Get the semanticQueryRewritesResultType property: Type of query rewrite that was used to retrieve documents. + * + * @return the semanticQueryRewritesResultType value. + */ + public SemanticQueryRewritesResultType getSemanticQueryRewritesResultType() { + return page.getSemanticQueryRewritesResultType(); + } + + @Override + public IterableStream getElements() { + return IterableStream.of(page.getResults()); + } + + @Override + public SearchContinuationToken getContinuationToken() { + return continuationToken; + } + + @Override + public int getStatusCode() { + return response.getStatusCode(); + } + + @Override + public HttpHeaders getHeaders() { + return response.getHeaders(); + } + + @Override + public HttpRequest getRequest() { + return response.getRequest(); + } + + @Override + public List getValue() { + return page.getResults(); + } +} 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 77% 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 d56f730dee12..72315de053c5 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,10 +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. - -package com.azure.search.documents.implementation.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; @@ -12,30 +9,24 @@ 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.Arrays; +import java.util.LinkedList; import java.util.List; +import java.util.stream.Collectors; /** * 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. */ @Generated - private Boolean includeTotalResultCount; + private Boolean includeTotalCount; /* * The list of facet expressions to apply to the search query. Each facet expression contains a field name, @@ -55,7 +46,7 @@ public final class SearchRequest implements JsonSerializable { * highlighting. */ @Generated - private String highlightFields; + private List highlightFields; /* * A string tag that is appended to hit highlights. Must be set with highlightPreTag. Default is </em>. @@ -85,7 +76,7 @@ public final class SearchRequest implements JsonSerializable { * descending by document match score. There can be at most 32 $orderby clauses. */ @Generated - private String orderBy; + private List orderBy; /* * A value that specifies the syntax of the search query. The default is 'simple'. Use 'full' if your query uses the @@ -144,7 +135,7 @@ public final class SearchRequest implements JsonSerializable { * precedence over any field names listed in this parameter. */ @Generated - private String searchFields; + 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 @@ -160,17 +151,17 @@ public final class SearchRequest implements JsonSerializable { private QueryLanguage queryLanguage; /* - * A value that specified the type of the speller to use to spell-correct individual search query terms. + * A value that specifies the type of the speller to use to spell-correct individual search query terms. */ @Generated - private QuerySpellerType speller; + private QuerySpellerType querySpeller; /* * The comma-separated list of fields to retrieve. If unspecified, all fields marked as retrievable in the schema * are included. */ @Generated - private String select; + 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 @@ -192,7 +183,7 @@ public final class SearchRequest implements JsonSerializable { * The name of a semantic configuration that will be used when processing documents for queries of type semantic. */ @Generated - private String semanticConfiguration; + private String semanticConfigurationName; /* * Allows the user to choose whether a semantic call should fail completely (default / current behavior), or to @@ -217,43 +208,28 @@ public final class SearchRequest implements JsonSerializable { 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. */ @Generated - private String answers; + 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. */ @Generated - private String captions; + 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. */ @Generated - private String queryRewrites; + private QueryRewritesType queryRewrites; /* * The comma-separated list of field names used for semantic ranking. */ @Generated - private String semanticFields; + private List semanticFields; /* * The query parameters for vector and hybrid search queries. @@ -282,35 +258,21 @@ 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. - * - * @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 + * 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. - * - * @param includeTotalResultCount the includeTotalResultCount value to set. - * @return the SearchRequest object itself. + * + * @return the includeTotalCount value. */ @Generated - public SearchRequest setIncludeTotalResultCount(Boolean includeTotalResultCount) { - this.includeTotalResultCount = includeTotalResultCount; - return this; + public Boolean isIncludeTotalCount() { + return this.includeTotalCount; } /** * 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 @@ -318,22 +280,9 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest 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. */ @Generated @@ -341,46 +290,21 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest setFilter(String filter) { - this.filter = filter; - return this; - } - /** * Get the highlightFields property: The comma-separated list of field names to use for hit highlights. Only * searchable fields can be used for hit highlighting. - * + * * @return the highlightFields value. */ @Generated - public String getHighlightFields() { + public List getHighlightFields() { return this.highlightFields; } - /** - * Set the highlightFields property: The comma-separated 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 SearchRequest object itself. - */ - @Generated - public SearchRequest setHighlightFields(String 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. */ @Generated @@ -388,23 +312,10 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest 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. */ @Generated @@ -412,24 +323,11 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest 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. */ @Generated @@ -437,54 +335,24 @@ 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 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. - * + * * @return the orderBy value. */ @Generated - public String getOrderBy() { + public List 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. - * - * @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. - * + * * @return the queryType value. */ @Generated @@ -492,25 +360,12 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest setQueryType(QueryType queryType) { - this.queryType = queryType; - 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. 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 @@ -518,28 +373,13 @@ 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. - * - * @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. - * + * * @return the sessionId value. */ @Generated @@ -547,27 +387,11 @@ 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. - * - * @param sessionId the sessionId value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setSessionId(String sessionId) { - this.sessionId = sessionId; - 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. */ @Generated @@ -575,24 +399,10 @@ 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 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. - * + * * @return the scoringProfile value. */ @Generated @@ -600,22 +410,9 @@ 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 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. - * + * * @return the debug value. */ @Generated @@ -623,22 +420,10 @@ public QueryDebugMode getDebug() { return this.debug; } - /** - * 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. - * + * * @return the searchText value. */ @Generated @@ -646,49 +431,22 @@ 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. - * - * @param searchText the searchText value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setSearchText(String searchText) { - this.searchText = searchText; - return this; - } - /** * 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. - * + * * @return the searchFields value. */ @Generated - public String getSearchFields() { + public List 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. - * - * @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. - * + * * @return the searchMode value. */ @Generated @@ -696,22 +454,9 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest setSearchMode(SearchMode searchMode) { - this.searchMode = searchMode; - return this; - } - /** * Get the queryLanguage property: A value that specifies the language of the search query. - * + * * @return the queryLanguage value. */ @Generated @@ -720,70 +465,32 @@ public QueryLanguage getQueryLanguage() { } /** - * Set the queryLanguage property: A value that specifies the language of the search query. - * - * @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. - * - * @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 + * Get the querySpeller property: A value that specifies 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. + * + * @return the querySpeller value. */ @Generated - public SearchRequest setSpeller(QuerySpellerType speller) { - this.speller = speller; - return this; + public QuerySpellerType getQuerySpeller() { + return this.querySpeller; } /** * 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() { + public List 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. - * - * @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. - * + * * @return the skip value. */ @Generated @@ -791,25 +498,11 @@ 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 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. - * + * * @return the top value. */ @Generated @@ -818,47 +511,20 @@ public Integer getTop() { } /** - * 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. + * Get the semanticConfigurationName property: The name of a semantic configuration that will be used when + * processing documents for queries of type semantic. + * + * @return the semanticConfigurationName value. */ @Generated - public SearchRequest setTop(Integer top) { - this.top = top; - return this; - } - - /** - * Get the semanticConfiguration property: The name of a semantic configuration that will be used when processing - * documents for queries of type semantic. - * - * @return the semanticConfiguration value. - */ - @Generated - public String getSemanticConfiguration() { - return this.semanticConfiguration; - } - - /** - * Set the semanticConfiguration property: The name of a semantic configuration that will be used when processing - * documents for queries of type semantic. - * - * @param semanticConfiguration the semanticConfiguration value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setSemanticConfiguration(String semanticConfiguration) { - this.semanticConfiguration = semanticConfiguration; - return this; + public String getSemanticConfigurationName() { + return this.semanticConfigurationName; } /** * Get the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely * (default / current behavior), or to return partial results. - * + * * @return the semanticErrorHandling value. */ @Generated @@ -866,23 +532,10 @@ public SemanticErrorMode getSemanticErrorHandling() { return this.semanticErrorHandling; } - /** - * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely - * (default / current behavior), or to return partial results. - * - * @param semanticErrorHandling the semanticErrorHandling value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest 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. */ @Generated @@ -890,24 +543,11 @@ 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 SearchRequest object itself. - */ - @Generated - public SearchRequest setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { - this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; - 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. */ @Generated @@ -916,140 +556,51 @@ public String getSemanticQuery() { } /** - * 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 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. */ @Generated - public String getAnswers() { + 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'. - * - * @param answers the answers value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest 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'. - * + * Get the captions property: A value that specifies whether captions should be returned as part of the search + * response. + * * @return the captions value. */ @Generated - public String getCaptions() { + 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'. - * - * @param captions the captions value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setCaptions(String 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. */ @Generated - public String getQueryRewrites() { + 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`. - * - * @param queryRewrites the queryRewrites value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setQueryRewrites(String queryRewrites) { - this.queryRewrites = queryRewrites; - return this; - } - /** * Get the semanticFields property: The comma-separated list of field names used for semantic ranking. - * + * * @return the semanticFields value. */ @Generated - public String getSemanticFields() { + public List getSemanticFields() { return this.semanticFields; } - /** - * Set the semanticFields property: The comma-separated list of field names used for semantic ranking. - * - * @param semanticFields the semanticFields value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setSemanticFields(String semanticFields) { - this.semanticFields = semanticFields; - return this; - } - /** * Get the vectorQueries property: The query parameters for vector and hybrid search queries. - * + * * @return the vectorQueries value. */ @Generated @@ -1057,22 +608,10 @@ public List getVectorQueries() { return this.vectorQueries; } - /** - * Set the vectorQueries property: The query parameters for vector and hybrid search queries. - * - * @param vectorQueries the vectorQueries value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setVectorQueries(List vectorQueries) { - this.vectorQueries = vectorQueries; - return this; - } - /** * 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. - * + * * @return the vectorFilterMode value. */ @Generated @@ -1080,22 +619,9 @@ 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. - * - * @param vectorFilterMode the vectorFilterMode value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setVectorFilterMode(VectorFilterMode vectorFilterMode) { - this.vectorFilterMode = vectorFilterMode; - return this; - } - /** * Get the hybridSearch property: The query parameters to configure hybrid search behaviors. - * + * * @return the hybridSearch value. */ @Generated @@ -1103,18 +629,6 @@ public HybridSearch getHybridSearch() { return this.hybridSearch; } - /** - * Set the hybridSearch property: The query parameters to configure hybrid search behaviors. - * - * @param hybridSearch the hybridSearch value to set. - * @return the SearchRequest object itself. - */ - @Generated - public SearchRequest setHybridSearch(HybridSearch hybridSearch) { - this.hybridSearch = hybridSearch; - return this; - } - /** * {@inheritDoc} */ @@ -1122,14 +636,22 @@ public SearchRequest setHybridSearch(HybridSearch hybridSearch) { @Override public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStartObject(); - jsonWriter.writeBooleanField("count", this.includeTotalResultCount); + jsonWriter.writeBooleanField("count", this.includeTotalCount); jsonWriter.writeArrayField("facets", this.facets, (writer, element) -> writer.writeString(element)); jsonWriter.writeStringField("filter", this.filter); - jsonWriter.writeStringField("highlight", this.highlightFields); + if (this.highlightFields != null) { + jsonWriter.writeStringField("highlight", + this.highlightFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } jsonWriter.writeStringField("highlightPostTag", this.highlightPostTag); jsonWriter.writeStringField("highlightPreTag", this.highlightPreTag); jsonWriter.writeNumberField("minimumCoverage", this.minimumCoverage); - jsonWriter.writeStringField("orderby", this.orderBy); + if (this.orderBy != null) { + jsonWriter.writeStringField("orderby", + this.orderBy.stream().map(element -> element == null ? "" : element).collect(Collectors.joining(","))); + } jsonWriter.writeStringField("queryType", this.queryType == null ? null : this.queryType.toString()); jsonWriter.writeStringField("scoringStatistics", this.scoringStatistics == null ? null : this.scoringStatistics.toString()); @@ -1139,22 +661,35 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { jsonWriter.writeStringField("scoringProfile", this.scoringProfile); jsonWriter.writeStringField("debug", this.debug == null ? null : this.debug.toString()); jsonWriter.writeStringField("search", this.searchText); - jsonWriter.writeStringField("searchFields", this.searchFields); + if (this.searchFields != null) { + jsonWriter.writeStringField("searchFields", + this.searchFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } jsonWriter.writeStringField("searchMode", this.searchMode == null ? null : this.searchMode.toString()); jsonWriter.writeStringField("queryLanguage", this.queryLanguage == null ? null : this.queryLanguage.toString()); - jsonWriter.writeStringField("speller", this.speller == null ? null : this.speller.toString()); - jsonWriter.writeStringField("select", this.select); + jsonWriter.writeStringField("speller", this.querySpeller == null ? null : this.querySpeller.toString()); + if (this.select != null) { + jsonWriter.writeStringField("select", + this.select.stream().map(element -> element == null ? "" : element).collect(Collectors.joining(","))); + } jsonWriter.writeNumberField("skip", this.skip); jsonWriter.writeNumberField("top", this.top); - jsonWriter.writeStringField("semanticConfiguration", this.semanticConfiguration); + jsonWriter.writeStringField("semanticConfiguration", this.semanticConfigurationName); jsonWriter.writeStringField("semanticErrorHandling", 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("semanticFields", this.semanticFields); + 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()); + if (this.semanticFields != null) { + jsonWriter.writeStringField("semanticFields", + this.semanticFields.stream() + .map(element -> element == null ? "" : element) + .collect(Collectors.joining(","))); + } jsonWriter.writeArrayField("vectorQueries", this.vectorQueries, (writer, element) -> writer.writeJson(element)); jsonWriter.writeStringField("vectorFilterMode", this.vectorFilterMode == null ? null : this.vectorFilterMode.toString()); @@ -1164,7 +699,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SearchRequest from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SearchRequest if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -1177,16 +712,21 @@ public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("count".equals(fieldName)) { - deserializedSearchRequest.includeTotalResultCount = reader.getNullable(JsonReader::getBoolean); + deserializedSearchRequest.includeTotalCount = reader.getNullable(JsonReader::getBoolean); } else if ("facets".equals(fieldName)) { List facets = reader.readArray(reader1 -> reader1.getString()); deserializedSearchRequest.facets = facets; } else if ("filter".equals(fieldName)) { deserializedSearchRequest.filter = reader.getString(); } else if ("highlight".equals(fieldName)) { - deserializedSearchRequest.highlightFields = reader.getString(); + List highlightFields = reader.getNullable(nonNullReader -> { + String highlightFieldsEncodedAsString = nonNullReader.getString(); + return highlightFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(highlightFieldsEncodedAsString.split(",", -1))); + }); + deserializedSearchRequest.highlightFields = highlightFields; } else if ("highlightPostTag".equals(fieldName)) { deserializedSearchRequest.highlightPostTag = reader.getString(); } else if ("highlightPreTag".equals(fieldName)) { @@ -1194,7 +734,13 @@ public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { } else if ("minimumCoverage".equals(fieldName)) { deserializedSearchRequest.minimumCoverage = reader.getNullable(JsonReader::getDouble); } else if ("orderby".equals(fieldName)) { - deserializedSearchRequest.orderBy = reader.getString(); + List orderBy = reader.getNullable(nonNullReader -> { + String orderByEncodedAsString = nonNullReader.getString(); + return orderByEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(orderByEncodedAsString.split(",", -1))); + }); + deserializedSearchRequest.orderBy = orderBy; } else if ("queryType".equals(fieldName)) { deserializedSearchRequest.queryType = QueryType.fromString(reader.getString()); } else if ("scoringStatistics".equals(fieldName)) { @@ -1211,21 +757,33 @@ public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { } else if ("search".equals(fieldName)) { deserializedSearchRequest.searchText = reader.getString(); } else if ("searchFields".equals(fieldName)) { - deserializedSearchRequest.searchFields = reader.getString(); + List searchFields = reader.getNullable(nonNullReader -> { + String searchFieldsEncodedAsString = nonNullReader.getString(); + return searchFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(searchFieldsEncodedAsString.split(",", -1))); + }); + deserializedSearchRequest.searchFields = searchFields; } else if ("searchMode".equals(fieldName)) { deserializedSearchRequest.searchMode = SearchMode.fromString(reader.getString()); } else if ("queryLanguage".equals(fieldName)) { deserializedSearchRequest.queryLanguage = QueryLanguage.fromString(reader.getString()); } else if ("speller".equals(fieldName)) { - deserializedSearchRequest.speller = QuerySpellerType.fromString(reader.getString()); + deserializedSearchRequest.querySpeller = QuerySpellerType.fromString(reader.getString()); } else if ("select".equals(fieldName)) { - deserializedSearchRequest.select = reader.getString(); + List select = reader.getNullable(nonNullReader -> { + String selectEncodedAsString = nonNullReader.getString(); + return selectEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(selectEncodedAsString.split(",", -1))); + }); + deserializedSearchRequest.select = select; } else if ("skip".equals(fieldName)) { deserializedSearchRequest.skip = reader.getNullable(JsonReader::getInt); } else if ("top".equals(fieldName)) { deserializedSearchRequest.top = reader.getNullable(JsonReader::getInt); } else if ("semanticConfiguration".equals(fieldName)) { - deserializedSearchRequest.semanticConfiguration = reader.getString(); + deserializedSearchRequest.semanticConfigurationName = reader.getString(); } else if ("semanticErrorHandling".equals(fieldName)) { deserializedSearchRequest.semanticErrorHandling = SemanticErrorMode.fromString(reader.getString()); } else if ("semanticMaxWaitInMilliseconds".equals(fieldName)) { @@ -1233,13 +791,19 @@ 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(); + List semanticFields = reader.getNullable(nonNullReader -> { + String semanticFieldsEncodedAsString = nonNullReader.getString(); + return semanticFieldsEncodedAsString.isEmpty() + ? new LinkedList<>() + : new LinkedList<>(Arrays.asList(semanticFieldsEncodedAsString.split(",", -1))); + }); + deserializedSearchRequest.semanticFields = semanticFields; } else if ("vectorQueries".equals(fieldName)) { List vectorQueries = reader.readArray(reader1 -> VectorQuery.fromJson(reader1)); deserializedSearchRequest.vectorQueries = vectorQueries; @@ -1251,8 +815,445 @@ public static SearchRequest fromJson(JsonReader jsonReader) throws IOException { reader.skipChildren(); } } - return deserializedSearchRequest; }); } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setIncludeTotalCount(Boolean includeTotalCount) { + this.includeTotalCount = includeTotalCount; + 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setFacets(List facets) { + this.facets = facets; + return this; + } + + /** + * Set the filter property: The OData $filter expression to apply to the search query. + * + * @param filter the filter value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setFilter(String filter) { + this.filter = filter; + return this; + } + + /** + * Set the highlightFields property: The comma-separated 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setHighlightFields(List highlightFields) { + this.highlightFields = highlightFields; + return this; + } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setHighlightPostTag(String highlightPostTag) { + this.highlightPostTag = highlightPostTag; + return this; + } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setHighlightPreTag(String highlightPreTag) { + this.highlightPreTag = highlightPreTag; + return this; + } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setMinimumCoverage(Double minimumCoverage) { + this.minimumCoverage = minimumCoverage; + return this; + } + + /** + * 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(List orderBy) { + this.orderBy = orderBy; + return this; + } + + /** + * 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; + } + + /** + * 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. + * + * @param scoringStatistics the scoringStatistics value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setScoringStatistics(ScoringStatistics scoringStatistics) { + this.scoringStatistics = scoringStatistics; + return this; + } + + /** + * 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; + } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setScoringParameters(List scoringParameters) { + this.scoringParameters = scoringParameters; + return this; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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. + * + * @param searchFields the searchFields value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setSearchFields(List searchFields) { + this.searchFields = searchFields; + return this; + } + + /** + * 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; + } + + /** + * Set the queryLanguage property: A value that specifies the language of the search query. + * + * @param queryLanguage the queryLanguage value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setQueryLanguage(QueryLanguage queryLanguage) { + this.queryLanguage = queryLanguage; + return this; + } + + /** + * Set the querySpeller property: A value that specifies the type of the speller to use to spell-correct individual + * search query terms. + * + * @param querySpeller the querySpeller value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setQuerySpeller(QuerySpellerType querySpeller) { + this.querySpeller = querySpeller; + return this; + } + + /** + * 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(List select) { + this.select = select; + return this; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Set the semanticConfigurationName property: The name of a semantic configuration that will be used when + * processing documents for queries of type semantic. + * + * @param semanticConfigurationName the semanticConfigurationName value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setSemanticConfigurationName(String semanticConfigurationName) { + this.semanticConfigurationName = semanticConfigurationName; + return this; + } + + /** + * Set the semanticErrorHandling property: Allows the user to choose whether a semantic call should fail completely + * (default / current behavior), or to return partial results. + * + * @param semanticErrorHandling the semanticErrorHandling value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setSemanticErrorHandling(SemanticErrorMode semanticErrorHandling) { + this.semanticErrorHandling = semanticErrorHandling; + return this; + } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setSemanticMaxWaitInMilliseconds(Integer semanticMaxWaitInMilliseconds) { + this.semanticMaxWaitInMilliseconds = semanticMaxWaitInMilliseconds; + return this; + } + + /** + * 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 SearchRequest object itself. + */ + @Generated + public SearchRequest setSemanticQuery(String semanticQuery) { + this.semanticQuery = semanticQuery; + return this; + } + + /** + * 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. + */ + @Generated + public SearchRequest setAnswers(QueryAnswerType answers) { + this.answers = answers; + return this; + } + + /** + * 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. + */ + @Generated + public SearchRequest setCaptions(QueryCaptionType captions) { + this.captions = captions; + return this; + } + + /** + * 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. + */ + @Generated + public SearchRequest setQueryRewrites(QueryRewritesType queryRewrites) { + this.queryRewrites = queryRewrites; + return this; + } + + /** + * Set the semanticFields property: The comma-separated list of field names used for semantic ranking. + * + * @param semanticFields the semanticFields value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setSemanticFields(List semanticFields) { + this.semanticFields = semanticFields; + return this; + } + + /** + * Set the vectorQueries property: The query parameters for vector and hybrid search queries. + * + * @param vectorQueries the vectorQueries value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setVectorQueries(List vectorQueries) { + this.vectorQueries = vectorQueries; + return this; + } + + /** + * 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. + * + * @param vectorFilterMode the vectorFilterMode value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setVectorFilterMode(VectorFilterMode vectorFilterMode) { + this.vectorFilterMode = vectorFilterMode; + return this; + } + + /** + * Set the hybridSearch property: The query parameters to configure hybrid search behaviors. + * + * @param hybridSearch the hybridSearch value to set. + * @return the SearchRequest object itself. + */ + @Generated + public SearchRequest setHybridSearch(HybridSearch hybridSearch) { + this.hybridSearch = hybridSearch; + return this; + } } 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 f3659c82caed..592f086a53f7 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,103 +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.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.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 { +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. */ - private final double score; + @Generated + private 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. + * The relevance score computed by boosting the Reranker Score. Search results are sorted by the + * RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic Config. + * RerankerBoostedScore is only returned for queries of type 'semantic'. */ + @Generated + private Double rerankerBoostedScore; + + /* + * 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; + /* + * 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'. + */ + @Generated + private List captions; + /* * Contains debugging information that can be used to further explore your search results. */ + @Generated private DocumentDebugInfo documentDebugInfo; /* * Contains a document found by a search query, plus associated metadata. */ + @Generated private Map additionalProperties; - /* - * The json serializer. + /** + * Creates an instance of SearchResult class. */ - 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, Double rerankerBoostedScore) { - searchResult.setSemanticSearchResult(rerankerScore, captions, rerankerBoostedScore); - } + @Generated + public SearchResult() { + } - @Override - public void setDocumentDebugInfo(SearchResult searchResult, DocumentDebugInfo documentDebugInfo) { - searchResult.setDocumentDebugInfo(documentDebugInfo); - } - }); + /** + * 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; } /** - * Constructor of {@link SearchResult}. + * 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'. * - * @param score The relevance score of the document compared to other documents returned by the query. + * @return the rerankerScore value. */ - public SearchResult(double score) { - this.score = score; + @Generated + public Double getRerankerScore() { + return this.rerankerScore; } /** - * Get the score property: The relevance score of the document compared to other documents returned by the query. + * Get the rerankerBoostedScore property: The relevance score computed by boosting the Reranker Score. Search + * results are sorted by the RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the + * Semantic Config. RerankerBoostedScore is only returned for queries of type 'semantic'. * - * @return the score value. + * @return the rerankerBoostedScore value. */ - public double getScore() { - return this.score; + @Generated + public Double getRerankerBoostedScore() { + return this.rerankerBoostedScore; } /** @@ -106,88 +114,112 @@ public double getScore() { * * @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. + * 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 semanticSearchResult value. + * @return the captions value. */ - public SemanticSearchResult getSemanticSearch() { - return this.semanticSearch; + @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. */ + @Generated public DocumentDebugInfo getDocumentDebugInfo() { return this.documentDebugInfo; } /** - * Get the additionalProperties property: Unmatched properties from the message are deserialized this collection. + * Get the additionalProperties property: Contains a document found by a search query, plus associated metadata. * - * @param modelClass The model class converts to. - * @param Convert document to the generic type. * @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)); + @Generated + public Map getAdditionalProperties() { + return this.additionalProperties; } /** - * The private setter to set the additionalProperties property via {@code SearchResultHelper.SearchResultAccessor}. + * Set the additionalProperties property: Contains a document found by a search query, plus associated metadata. * - * @param additionalProperties The Unmatched properties from the message are deserialized this collection. + * @param additionalProperties the additionalProperties value to set. + * @return the SearchResult object itself. */ - private void setAdditionalProperties(SearchDocument additionalProperties) { + @Generated + public SearchResult setAdditionalProperties(Map additionalProperties) { this.additionalProperties = additionalProperties; + return this; } /** - * 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; - } - - /** - * 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(); + if (additionalProperties != null) { + for (Map.Entry additionalProperty : additionalProperties.entrySet()) { + jsonWriter.writeUntypedField(additionalProperty.getKey(), additionalProperty.getValue()); + } + } + return jsonWriter.writeEndObject(); } /** - * The private setter to set the semanticSearchResult property via - * {@code SearchResultHelper.setSemanticSearchResult}. + * Reads an instance of SearchResult from the JsonReader. * - * @param rerankerScore The reranker score. - * @param captions The captions. - * @param rerankerBoostedScore The boosted reranker score. - */ - private void setSemanticSearchResult(Double rerankerScore, List captions, - Double rerankerBoostedScore) { - this.semanticSearch = new SemanticSearchResult(rerankerScore, captions, rerankerBoostedScore); + * @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 -> { + SearchResult deserializedSearchResult = new SearchResult(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("@search.score".equals(fieldName)) { + deserializedSearchResult.score = reader.getDouble(); + } else if ("@search.rerankerScore".equals(fieldName)) { + deserializedSearchResult.rerankerScore = reader.getNullable(JsonReader::getDouble); + } else if ("@search.rerankerBoostedScore".equals(fieldName)) { + deserializedSearchResult.rerankerBoostedScore = reader.getNullable(JsonReader::getDouble); + } else if ("@search.highlights".equals(fieldName)) { + Map> highlights + = reader.readMap(reader1 -> reader1.readArray(reader2 -> reader2.getString())); + deserializedSearchResult.highlights = highlights; + } else if ("@search.captions".equals(fieldName)) { + List captions + = reader.readArray(reader1 -> QueryCaptionResult.fromJson(reader1)); + deserializedSearchResult.captions = captions; + } else if ("@search.documentDebugInfo".equals(fieldName)) { + deserializedSearchResult.documentDebugInfo = DocumentDebugInfo.fromJson(reader); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + 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 963f967952c8..569a17945318 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -13,22 +11,19 @@ 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 '. */ @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 ' */ @Generated private final double value; @@ -44,7 +39,7 @@ public SearchScoreThreshold(double 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. */ @@ -55,11 +50,9 @@ public VectorThresholdKind getKind() { } /** - * 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`. + * Get the value property: The threshold will filter based on the '. * - * @return the value. + * @return the value value. */ @Generated public double getValue() { @@ -90,7 +83,6 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { @@ -98,19 +90,15 @@ public static SearchScoreThreshold fromJson(JsonReader jsonReader) throws IOExce 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/models/SemanticDebugInfo.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticDebugInfo.java index 00dfab77b25f..5514e28b6aa0 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -16,10 +13,11 @@ 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 */ @@ -48,13 +46,13 @@ public final class SemanticDebugInfo implements JsonSerializable getContentFields() { /** * 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 @@ -86,7 +84,7 @@ public List getKeywordFields() { /** * Get the rerankerInput property: The raw concatenated strings that were sent to the semantic enrichment process. - * + * * @return the rerankerInput value. */ @Generated @@ -106,7 +104,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SemanticDebugInfo from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SemanticDebugInfo if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -119,7 +117,6 @@ public static SemanticDebugInfo fromJson(JsonReader jsonReader) throws IOExcepti while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("titleField".equals(fieldName)) { deserializedSemanticDebugInfo.titleField = QueryResultDocumentSemanticField.fromJson(reader); } else if ("contentFields".equals(fieldName)) { @@ -136,7 +133,6 @@ public static SemanticDebugInfo fromJson(JsonReader jsonReader) throws IOExcepti reader.skipChildren(); } } - return deserializedSemanticDebugInfo; }); } 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 0884753da13f..067edf256d88 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -14,6 +11,7 @@ * 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. @@ -30,7 +28,7 @@ public final class SemanticErrorMode extends ExpandableStringEnum { + /** * If `semanticMaxWaitInMilliseconds` was set and the semantic processing duration exceeded that value. Only the * base results were returned. @@ -35,7 +33,7 @@ public final class SemanticErrorReason extends ExpandableStringEnum { + /** * The field was fully used for semantic enrichment. */ @@ -34,7 +32,7 @@ public final class SemanticFieldState extends ExpandableStringEnum { + /** * Query rewrites were not successfully generated for this request. Only the original query was used to retrieve the * results. @@ -23,7 +21,7 @@ public final class SemanticQueryRewritesResultType extends ExpandableStringEnum< /** * Creates a new instance of SemanticQueryRewritesResultType value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -33,7 +31,7 @@ public SemanticQueryRewritesResultType() { /** * Creates or finds a SemanticQueryRewritesResultType from its string representation. - * + * * @param name a name to look for. * @return the corresponding SemanticQueryRewritesResultType. */ @@ -44,7 +42,7 @@ public static SemanticQueryRewritesResultType fromString(String name) { /** * Gets known SemanticQueryRewritesResultType values. - * + * * @return known SemanticQueryRewritesResultType values. */ @Generated 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 f1890fbfda6c..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResult.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 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; - - /* - * The relevance score computed by boosting the Reranker Score. Search results are sorted by the - * RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the Semantic Config. - * RerankerBoostedScore is only returned for queries of type 'semantic' - */ - private final Double rerankerBoostedScore; - - SemanticSearchResult(Double rerankerScore, List queryCaptions, Double rerankerBoostedScore) { - this.rerankerBoostedScore = rerankerBoostedScore; - 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; - } - - /** - * Get the rerankerBoostedScore property: The relevance score computed by boosting the Reranker Score. Search - * results are sorted by the RerankerScore/RerankerBoostedScore based on useScoringProfileBoostedRanking in the - * Semantic Config. RerankerBoostedScore is only returned for queries of type 'semantic'. - * - * @return the rerankerBoostedScore value. - */ - public Double getRerankerBoostedScore() { - return this.rerankerBoostedScore; - } - -} 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 8ac26496fc2f..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SemanticSearchResults.java +++ /dev/null @@ -1,68 +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.SemanticSearchResultsAccessHelper; - -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(List queryAnswers, SemanticErrorReason semanticErrorReason, - SemanticSearchResultsType semanticSearchResultsType, - SemanticQueryRewritesResultType semanticQueryRewritesResultType) { - this.queryAnswers = queryAnswers; - this.errorReason = semanticErrorReason; - this.resultsType = semanticSearchResultsType; - this.semanticQueryRewritesResultType = semanticQueryRewritesResultType; - } - - /** - * 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 6b6aba8677ca..30e55b81b2f5 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -14,6 +11,7 @@ * Type of partial response that was returned for a semantic ranking request. */ public final class SemanticSearchResultsType extends ExpandableStringEnum { + /** * Results without any semantic enrichment or reranking. */ @@ -29,7 +27,7 @@ public final class SemanticSearchResultsType extends ExpandableStringEnum { + /* - * 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 */ @Generated private Double searchScore; @@ -38,13 +34,12 @@ public final class SingleVectorFieldResult implements JsonSerializable { + /* * The sequence of results returned by the query. */ @Generated - private final List results; + private List results; /* * A value indicating the percentage of the index that was included in the query, or null if minimumCoverage was not @@ -35,17 +33,14 @@ public final class SuggestDocumentsResult implements JsonSerializable results) { - this.results = results; + private SuggestDocumentsResult() { } /** * Get the results property: The sequence of results returned by the query. - * + * * @return the results value. */ @Generated @@ -56,7 +51,7 @@ public List getResults() { /** * 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 @@ -76,7 +71,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of SuggestDocumentsResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of SuggestDocumentsResult if the JsonReader was pointing to an instance of it, or null if it * was pointing to JSON null. @@ -86,29 +81,20 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @Generated public static SuggestDocumentsResult fromJson(JsonReader jsonReader) throws IOException { return jsonReader.readObject(reader -> { - boolean resultsFound = false; - List results = null; - Double coverage = null; + SuggestDocumentsResult deserializedSuggestDocumentsResult = new SuggestDocumentsResult(); while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("value".equals(fieldName)) { - results = reader.readArray(reader1 -> SuggestResult.fromJson(reader1)); - resultsFound = true; + List results = reader.readArray(reader1 -> SuggestResult.fromJson(reader1)); + deserializedSuggestDocumentsResult.results = results; } else if ("@search.coverage".equals(fieldName)) { - coverage = reader.getNullable(JsonReader::getDouble); + deserializedSuggestDocumentsResult.coverage = reader.getNullable(JsonReader::getDouble); } else { reader.skipChildren(); } } - if (resultsFound) { - 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 index b4a9f389eb3a..376e3aac4aa1 100644 --- 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 @@ -1,25 +1,18 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; -import com.azure.json.JsonWriter; -import java.io.IOException; import java.util.Arrays; import java.util.List; /** - * Parameter group. + * Options for suggest API. */ @Fluent -public final class SuggestOptions implements JsonSerializable { +public final class SuggestOptions { /* * An OData expression that filters the documents considered for suggestions. @@ -28,9 +21,9 @@ public final class SuggestOptions implements JsonSerializable { 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 + * 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 @@ -51,7 +44,7 @@ public final class SuggestOptions implements JsonSerializable { private String highlightPreTag; /* - * A number between 0 and 100 indicating the percentage of the index that must be covered by a suggestions query in + * 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. */ @@ -59,39 +52,57 @@ public final class SuggestOptions implements JsonSerializable { 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. + * 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 List orderBy; /* - * The list of field names to search for the specified search text. Target fields must be included in the specified - * suggester. + * 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. */ @Generated private List searchFields; /* - * The 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 List select; /* - * The number of suggestions to retrieve. The value must be a number between 1 and 100. The default is 5. + * 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. */ @Generated private Integer top; /** * Creates an instance of SuggestOptions class. + * + * @param searchText the searchText value to set. + * @param suggesterName the suggesterName value to set. */ @Generated - public SuggestOptions() { + public SuggestOptions(String searchText, String suggesterName) { + this.searchText = searchText; + this.suggesterName = suggesterName; } /** @@ -117,23 +128,23 @@ public SuggestOptions setFilter(String filter) { } /** - * 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. + * 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. * * @return the useFuzzyMatching value. */ @Generated - public Boolean useFuzzyMatching() { + public Boolean isUseFuzzyMatching() { 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. + * 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. * * @param useFuzzyMatching the useFuzzyMatching value to set. * @return the SuggestOptions object itself. @@ -194,7 +205,7 @@ public SuggestOptions 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 suggestions query in order for the query to be reported as a success. This parameter can be useful + * 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. @@ -206,7 +217,7 @@ public Double getMinimumCoverage() { /** * 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 + * 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. @@ -219,11 +230,11 @@ public SuggestOptions setMinimumCoverage(Double minimumCoverage) { } /** - * 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. + * 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. */ @@ -233,11 +244,26 @@ public List getOrderBy() { } /** - * 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. + * 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 SuggestOptions object itself. + */ + public SuggestOptions setOrderBy(String... orderBy) { + this.orderBy = (orderBy == null) ? null : Arrays.asList(orderBy); + return this; + } + + /** + * 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 SuggestOptions object itself. @@ -249,8 +275,19 @@ public SuggestOptions setOrderBy(List orderBy) { } /** - * 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. + * 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. * * @return the searchFields value. */ @@ -260,8 +297,20 @@ public List getSearchFields() { } /** - * 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. + * 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 SuggestOptions object itself. + */ + public SuggestOptions setSearchFields(String... searchFields) { + this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); + return this; + } + + /** + * 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 SuggestOptions object itself. @@ -273,8 +322,8 @@ public SuggestOptions setSearchFields(List searchFields) { } /** - * Get the select property: The 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. */ @@ -284,139 +333,62 @@ public List getSelect() { } /** - * Set the select property: The 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 SuggestOptions object itself. */ - @Generated - public SuggestOptions setSelect(List select) { - this.select = select; + public SuggestOptions setSelect(String... select) { + this.select = (select == null) ? null : Arrays.asList(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. - */ - @Generated - 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. + * 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 top the top value to set. + * @param select the select value to set. * @return the SuggestOptions object itself. */ @Generated - public SuggestOptions setTop(Integer top) { - this.top = top; + public SuggestOptions setSelect(List select) { + this.select = select; 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. + * Get the suggesterName property: The name of the suggester as specified in the suggesters collection that's part + * of the index definition. * - * @param orderBy the orderBy value to set. - * @return the SuggestOptions object itself. + * @return the suggesterName value. */ - public SuggestOptions setOrderBy(String... orderBy) { - this.orderBy = (orderBy == null) ? null : Arrays.asList(orderBy); - return this; + @Generated + public String getSuggesterName() { + return this.suggesterName; } /** - * 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. + * Get the top property: The number of suggestions to retrieve. This must be a value between 1 and 100. The default + * is 5. * - * @param searchFields the searchFields value to set. - * @return the SuggestOptions object itself. + * @return the top value. */ - public SuggestOptions setSearchFields(String... searchFields) { - this.searchFields = (searchFields == null) ? null : Arrays.asList(searchFields); - return this; + @Generated + public Integer getTop() { + return this.top; } /** - * Set the select property: The list of fields to retrieve. If unspecified, only the key field will be included in - * the results. + * Set the top property: The number of suggestions to retrieve. This must be a value between 1 and 100. The default + * is 5. * - * @param select the select value to set. + * @param top the top value to set. * @return the SuggestOptions object itself. */ - public SuggestOptions setSelect(String... select) { - this.select = (select == null) ? null : Arrays.asList(select); + @Generated + public SuggestOptions setTop(Integer top) { + this.top = top; 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/models/SuggestResult.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/SuggestResult.java index f1ae0f6b42c1..06a3cfbed7ab 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,120 @@ // 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.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. + * 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; +public final class SuggestResult implements JsonSerializable { /* * The text of the suggestion result. */ - private final String text; + @Generated + private 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. + */ + @Generated + public SuggestResult() { } /** - * Constructor of {@link SuggestResult}. + * Get the text property: The text of the suggestion result. * - * @param text 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. + * Get the additionalProperties property: A result containing a document found by a suggestion query, plus + * associated metadata. * - * @param modelClass The model class converts to. - * @param Convert document to the generic type. * @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. + * Set the additionalProperties property: A result containing a document found by a suggestion query, plus + * associated metadata. * - * @return the text value. + * @param additionalProperties the additionalProperties value to set. + * @return the SuggestResult object itself. */ - public String getText() { - return this.text; + @Generated + public SuggestResult setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * {@inheritDoc} + */ + @Generated + @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(); } /** - * The private setter to set the select property - * via {@link SuggestResultHelper.SuggestResultAccessor}. + * Reads an instance of SuggestResult from the JsonReader. * - * @param additionalProperties The unmatched properties from the message. + * @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 -> { + SuggestResult deserializedSuggestResult = new SuggestResult(); + Map additionalProperties = null; + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + if ("@search.text".equals(fieldName)) { + deserializedSuggestResult.text = reader.getString(); + } else { + if (additionalProperties == null) { + additionalProperties = new LinkedHashMap<>(); + } + additionalProperties.put(fieldName, reader.readUntyped()); + } + } + deserializedSuggestResult.additionalProperties = additionalProperties; + return deserializedSuggestResult; + }); } } 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 2959a2e6d87e..c3c83d2ae246 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -19,6 +16,7 @@ */ @Immutable public final class TextResult implements JsonSerializable { + /* * The BM25 or Classic score for the text portion of the query. */ @@ -29,12 +27,12 @@ public final class TextResult implements JsonSerializable { * Creates an instance of TextResult class. */ @Generated - public TextResult() { + private TextResult() { } /** * Get the searchScore property: The BM25 or Classic score for the text portion of the query. - * + * * @return the searchScore value. */ @Generated @@ -54,7 +52,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of TextResult from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of TextResult if the JsonReader was pointing to an instance of it, or null if it was pointing * to JSON null. @@ -67,14 +65,12 @@ public static TextResult fromJson(JsonReader jsonReader) throws IOException { while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("searchScore".equals(fieldName)) { deserializedTextResult.searchScore = reader.getNullable(JsonReader::getDouble); } else { reader.skipChildren(); } } - return deserializedTextResult; }); } 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/models/VectorFilterMode.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorFilterMode.java index 9013c2870389..e4b1802e3658 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -14,6 +11,7 @@ * 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'. @@ -36,7 +34,7 @@ public final class VectorFilterMode extends ExpandableStringEnum { /* - * The kind of vector query being performed. + * Type of query. */ @Generated private VectorQueryKind kind = VectorQueryKind.fromString("VectorQuery"); @@ -29,7 +27,7 @@ public class VectorQuery implements JsonSerializable { * Number of nearest neighbors to return as top hits. */ @Generated - private Integer kNearestNeighborsCount; + private Integer kNearestNeighbors; /* * Vector Fields of type Collection(Edm.Single) to be included in the vector searched. @@ -91,7 +89,7 @@ public VectorQuery() { } /** - * Get the kind property: The kind of vector query being performed. + * Get the kind property: Type of query. * * @return the kind value. */ @@ -101,24 +99,24 @@ public VectorQueryKind getKind() { } /** - * Get the kNearestNeighborsCount property: Number of nearest neighbors to return as top hits. + * Get the kNearestNeighbors property: Number of nearest neighbors to return as top hits. * - * @return the kNearestNeighborsCount value. + * @return the kNearestNeighbors value. */ @Generated - public Integer getKNearestNeighborsCount() { - return this.kNearestNeighborsCount; + public Integer getKNearestNeighbors() { + return this.kNearestNeighbors; } /** - * Set the kNearestNeighborsCount property: Number of nearest neighbors to return as top hits. + * Set the kNearestNeighbors property: Number of nearest neighbors to return as top hits. * - * @param kNearestNeighborsCount the kNearestNeighborsCount value to set. + * @param kNearestNeighbors the kNearestNeighbors value to set. * @return the VectorQuery object itself. */ @Generated - public VectorQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - this.kNearestNeighborsCount = kNearestNeighborsCount; + public VectorQuery setKNearestNeighbors(Integer kNearestNeighbors) { + this.kNearestNeighbors = kNearestNeighbors; return this; } @@ -139,8 +137,8 @@ public String getFields() { * @return the VectorQuery object itself. */ @Generated - public VectorQuery setFields(String... fields) { - this.fields = (fields == null) ? null : String.join(",", fields); + public VectorQuery setFields(String fields) { + this.fields = fields; return this; } @@ -210,22 +208,6 @@ public Float 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. - * - * @param weight the weight value to set. - * @return the VectorQuery object itself. - */ - @Generated - public VectorQuery setWeight(Float weight) { - this.weight = weight; - return this; - } - /** * Get the threshold property: The threshold used for vector queries. Note this can only be set if all 'fields' use * the same similarity metric. @@ -312,7 +294,7 @@ public VectorQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) { 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); @@ -349,14 +331,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()); } @@ -374,7 +356,7 @@ static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx 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)) { @@ -396,4 +378,20 @@ static VectorQuery fromJsonKnownDiscriminator(JsonReader jsonReader) throws IOEx return deserializedVectorQuery; }); } + + /** + * 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. + */ + @Generated + public VectorQuery setWeight(Float weight) { + this.weight = weight; + return this; + } } 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 dc03226a5954..2680b1eed274 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -14,6 +11,7 @@ * The kind of vector query being performed. */ public final class VectorQueryKind extends ExpandableStringEnum { + /** * Vector query where a raw vector value is provided. */ @@ -40,7 +38,7 @@ public final class VectorQueryKind extends ExpandableStringEnum /** * Creates a new instance of VectorQueryKind value. - * + * * @deprecated Use the {@link #fromString(String)} factory method. */ @Generated @@ -50,7 +48,7 @@ public VectorQueryKind() { /** * Creates or finds a VectorQueryKind from its string representation. - * + * * @param name a name to look for. * @return the corresponding VectorQueryKind. */ @@ -61,7 +59,7 @@ public static VectorQueryKind fromString(String name) { /** * Gets known VectorQueryKind values. - * + * * @return known VectorQueryKind values. */ @Generated 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/models/VectorSimilarityThreshold.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java index 889ce166dcff..ba5196ab7882 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -20,8 +17,9 @@ */ @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; @@ -36,7 +34,7 @@ public final class VectorSimilarityThreshold extends VectorThreshold { /** * Creates an instance of VectorSimilarityThreshold class. - * + * * @param value the value value to set. */ @Generated @@ -45,8 +43,8 @@ public VectorSimilarityThreshold(double 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 @@ -59,7 +57,7 @@ public VectorThresholdKind getKind() { * 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 @@ -81,7 +79,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorSimilarityThreshold from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorSimilarityThreshold if the JsonReader was pointing to an instance of it, or null if * it was pointing to JSON null. @@ -91,29 +89,22 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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) { 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) { - VectorSimilarityThreshold deserializedVectorSimilarityThreshold = new VectorSimilarityThreshold(value); - deserializedVectorSimilarityThreshold.kind = kind; - - return deserializedVectorSimilarityThreshold; - } - throw new IllegalStateException("Missing required property: value"); + VectorSimilarityThreshold deserializedVectorSimilarityThreshold = new VectorSimilarityThreshold(value); + deserializedVectorSimilarityThreshold.kind = kind; + 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 8f441fbc82bf..76775c8babd9 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -19,8 +16,9 @@ */ @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"); @@ -33,8 +31,8 @@ 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 @@ -55,7 +53,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { /** * Reads an instance of VectorThreshold from the JsonReader. - * + * * @param jsonReader The JsonReader being read. * @return An instance of VectorThreshold if the JsonReader was pointing to an instance of it, or null if it was * pointing to JSON null. @@ -66,7 +64,8 @@ public static VectorThreshold fromJson(JsonReader jsonReader) throws IOException return jsonReader.readObject(reader -> { String discriminatorValue = null; try (JsonReader readerToUse = reader.bufferObject()) { - readerToUse.nextToken(); // Prepare for reading + // Prepare for reading + readerToUse.nextToken(); while (readerToUse.nextToken() != JsonToken.END_OBJECT) { String fieldName = readerToUse.getFieldName(); readerToUse.nextToken(); @@ -96,14 +95,12 @@ static VectorThreshold fromJsonKnownDiscriminator(JsonReader jsonReader) throws while (reader.nextToken() != JsonToken.END_OBJECT) { String fieldName = reader.getFieldName(); reader.nextToken(); - if ("kind".equals(fieldName)) { deserializedVectorThreshold.kind = VectorThresholdKind.fromString(reader.getString()); } else { reader.skipChildren(); } } - return deserializedVectorThreshold; }); } 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 17e98291e8e9..62f3ac2f0d83 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -11,9 +8,10 @@ import java.util.Collection; /** - * The kind of vector query being performed. + * The kind of threshold used to filter vector queries. */ 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 @@ -32,7 +30,7 @@ public final class VectorThresholdKind extends ExpandableStringEnum { - Integer kNearestNeighborsCount = null; + Integer kNearestNeighbors = null; String fields = null; Boolean exhaustive = null; Double oversampling = null; @@ -212,15 +200,14 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc VectorThreshold threshold = null; String filterOverride = null; Integer perDocumentVectorLimit = 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)) { @@ -237,30 +224,36 @@ public static VectorizableTextQuery fromJson(JsonReader jsonReader) throws IOExc perDocumentVectorLimit = reader.getNullable(JsonReader::getInt); } 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.setPerDocumentVectorLimit(perDocumentVectorLimit); - 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.setPerDocumentVectorLimit(perDocumentVectorLimit); + deserializedVectorizableTextQuery.kind = kind; + deserializedVectorizableTextQuery.queryRewrites = queryRewrites; + return deserializedVectorizableTextQuery; }); } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public VectorizableTextQuery setWeight(Float weight) { + super.setWeight(weight); + return this; + } } 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 56fd3d62b327..4851a9dcb1af 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,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -20,7 +18,7 @@ public final class VectorizedQuery extends VectorQuery { /* - * The kind of vector query being performed. + * Type of query. */ @Generated private VectorQueryKind kind = VectorQueryKind.VECTOR; @@ -42,7 +40,7 @@ public VectorizedQuery(List vector) { } /** - * Get the kind property: The kind of vector query being performed. + * Get the kind property: Type of query. * * @return the kind value. */ @@ -67,8 +65,8 @@ public List getVector() { */ @Generated @Override - public VectorizedQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) { - super.setKNearestNeighborsCount(kNearestNeighborsCount); + public VectorizedQuery setKNearestNeighbors(Integer kNearestNeighbors) { + super.setKNearestNeighbors(kNearestNeighbors); return this; } @@ -77,7 +75,7 @@ public VectorizedQuery setKNearestNeighborsCount(Integer kNearestNeighborsCount) */ @Generated @Override - public VectorizedQuery setFields(String... fields) { + public VectorizedQuery setFields(String fields) { super.setFields(fields); return this; } @@ -102,16 +100,6 @@ public VectorizedQuery setOversampling(Double oversampling) { return this; } - /** - * {@inheritDoc} - */ - @Generated - @Override - public VectorizedQuery setWeight(Float weight) { - super.setWeight(weight); - return this; - } - /** * {@inheritDoc} */ @@ -149,7 +137,7 @@ public VectorizedQuery setPerDocumentVectorLimit(Integer perDocumentVectorLimit) @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()); @@ -174,7 +162,7 @@ public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { @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; @@ -182,14 +170,13 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException VectorThreshold threshold = null; String filterOverride = null; Integer perDocumentVectorLimit = null; - boolean vectorFound = false; 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)) { @@ -206,27 +193,33 @@ public static VectorizedQuery fromJson(JsonReader jsonReader) throws IOException perDocumentVectorLimit = reader.getNullable(JsonReader::getInt); } else if ("vector".equals(fieldName)) { vector = reader.readArray(reader1 -> reader1.getFloat()); - vectorFound = true; } 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.setPerDocumentVectorLimit(perDocumentVectorLimit); - 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.setPerDocumentVectorLimit(perDocumentVectorLimit); + deserializedVectorizedQuery.kind = kind; + return deserializedVectorizedQuery; }); } + + /** + * {@inheritDoc} + */ + @Generated + @Override + public VectorizedQuery setWeight(Float weight) { + super.setWeight(weight); + return this; + } } 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 d892eea2f33b..e3a1fe470c39 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,9 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the 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; @@ -15,10 +12,11 @@ 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. */ @@ -29,13 +27,13 @@ public final class VectorsDebugInfo implements JsonSerializable Type of the document in the action. */ -public final class OnActionAddedOptions { - private final IndexAction action; +public final class OnActionAddedOptions { + private final IndexAction action; /** * Creates a new OnActionAddedOptions object. * * @param action Action being added. */ - public OnActionAddedOptions(IndexAction action) { + public OnActionAddedOptions(IndexAction action) { this.action = action; } @@ -31,7 +29,7 @@ public OnActionAddedOptions(IndexAction action) { * * @return The action. */ - public IndexAction getAction() { + 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 index 07432de04725..5f424005d7b7 100644 --- 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 @@ -12,11 +12,9 @@ /** * 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; +public final class OnActionErrorOptions { + private final IndexAction action; private Throwable throwable; private IndexingResult indexingResult; @@ -26,7 +24,7 @@ public final class OnActionErrorOptions { * * @param action Action that failed with an error. */ - public OnActionErrorOptions(IndexAction action) { + public OnActionErrorOptions(IndexAction action) { this.action = action; } @@ -35,7 +33,7 @@ public OnActionErrorOptions(IndexAction action) { * * @return The action. */ - public IndexAction getAction() { + public IndexAction getAction() { return action; } @@ -45,7 +43,7 @@ public IndexAction getAction() { * @param throwable Throwable that caused the action to fail. * @return The updated OnActionErrorOptions object. */ - public OnActionErrorOptions setThrowable(Throwable throwable) { + public OnActionErrorOptions setThrowable(Throwable throwable) { this.throwable = throwable; return this; } @@ -65,7 +63,7 @@ public Throwable getThrowable() { * @param indexingResult The indexing result for the action. * @return The updated OnActionErrorOptions object. */ - public OnActionErrorOptions setIndexingResult(IndexingResult indexingResult) { + public OnActionErrorOptions setIndexingResult(IndexingResult indexingResult) { this.indexingResult = indexingResult; return this; } 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 index 2049dc3353f9..2fc12490b87b 100644 --- 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 @@ -10,18 +10,16 @@ /** * 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; +public final class OnActionSentOptions { + private final IndexAction indexAction; /** * Creates a new OnActionSentOptions object. * * @param indexAction Action that was sent. */ - public OnActionSentOptions(IndexAction indexAction) { + public OnActionSentOptions(IndexAction indexAction) { this.indexAction = indexAction; } @@ -30,7 +28,7 @@ public OnActionSentOptions(IndexAction indexAction) { * * @return The action. */ - public IndexAction getIndexAction() { + 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 index 84099d43751a..ac5828133c6c 100644 --- 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 @@ -11,18 +11,16 @@ /** * 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; +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) { + public OnActionSucceededOptions(IndexAction indexAction) { this.indexAction = indexAction; } @@ -31,7 +29,7 @@ public OnActionSucceededOptions(IndexAction indexAction) { * * @return The action. */ - public IndexAction getIndexAction() { + public IndexAction getIndexAction() { return indexAction; } } 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 d501e9eb50c5..a94a0986e1a5 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,9 @@ // 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:

- * - *
    - *
  • 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 ad7f31acc185..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedFlux.java +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Supplier; - -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.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; - -/** - * 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}. - * @deprecated Use {@link SearchPagedResponse#getCount()} when consuming {@link #byPage()}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getCoverage()} when consuming {@link #byPage()}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getFacets()} when consuming {@link #byPage()}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getSemanticResults()} when consuming {@link #byPage()}. - */ - @Deprecated - public Mono getSemanticResults() { - return metadataSupplier.get().map(metadata -> metadata.getFirstPageResponse().getSemanticResults()); - } - - /** - * 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. - * @deprecated Use {@link SearchPagedResponse#getDebugInfo()} when consuming {@link #byPage()}. - */ - @Deprecated - 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 6e72e39b8e1a..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedIterable.java +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.search.documents.util; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Supplier; - -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.models.DebugInfo; -import com.azure.search.documents.models.FacetResult; -import com.azure.search.documents.models.SearchResult; -import com.azure.search.documents.models.SemanticSearchResults; - -/** - * 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. - * @deprecated Use {@link SearchPagedIterable#SearchPagedIterable(Supplier)} or - * {@link SearchPagedIterable#SearchPagedIterable(Supplier, Function)}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getCoverage()} when consuming {@link #streamByPage()} or - * {@link #iterableByPage()}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getFacets()} when consuming {@link #streamByPage()} or - * {@link #iterableByPage()}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getCount()} when consuming {@link #streamByPage()} or - * {@link #iterableByPage()}. - */ - @Deprecated - 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}. - * @deprecated Use {@link SearchPagedResponse#getSemanticResults()} when consuming {@link #streamByPage()} or - * {@link #iterableByPage()}. - */ - @Deprecated - public SemanticSearchResults getSemanticResults() { - return metadataSupplier != null - ? metadataSupplier.get().getFirstPageResponse().getSemanticResults() - : 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. - * @deprecated Use {@link SearchPagedResponse#getDebugInfo()} when consuming {@link #streamByPage()} or - * {@link #iterableByPage()}. - */ - @Deprecated - 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 59a67eaeb5d5..000000000000 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/util/SearchPagedResponse.java +++ /dev/null @@ -1,163 +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.SemanticSearchResultsAccessHelper; -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.SemanticSearchResults; -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 SemanticSearchResults semanticSearchResults; - private final DebugInfo debugInfo; - - /** - * 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. - * @deprecated Use {@link SearchPagedResponse#SearchPagedResponse(Response, String, Map, Long, Double, List, SemanticErrorReason, SemanticSearchResultsType, DebugInfo, SemanticQueryRewritesResultType)} - */ - @Deprecated - 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. - * @deprecated Use {@link SearchPagedResponse#SearchPagedResponse(Response, String, Map, Long, Double, List, SemanticErrorReason, SemanticSearchResultsType, DebugInfo, SemanticQueryRewritesResultType)} - */ - @Deprecated - 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.semanticSearchResults = SemanticSearchResultsAccessHelper.create(queryAnswers, semanticErrorReason, - semanticSearchResultsType, semanticQueryRewritesResultType); - this.debugInfo = debugInfo; - } - - /** - * 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. - */ - 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. - * - * @return the coverage value. - */ - 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. - * - * @return the facets value. - */ - public Map> getFacets() { - return this.facets; - } - - /** - * 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 semanticSearchResults; - } - - /** - * Get the debugInfo property: Debug information that applies to the search results as a whole. - * - * @return the debugInfo value. - */ - public DebugInfo getDebugInfo() { - return debugInfo; - } - - @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..7a4eb44e021e 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,20 @@ // 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.knowledgebases; exports com.azure.search.documents.indexes.models; + exports com.azure.search.documents.knowledgebases.models; exports com.azure.search.documents.models; exports com.azure.search.documents.options; - exports com.azure.search.documents.util; + + 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.knowledgebases.models to com.azure.core; + 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..362a624e037c --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_apiview_properties.json @@ -0,0 +1,646 @@ +{ + "flavor": "azure", + "CrossLanguageDefinitionId": { + "com.azure.search.documents.SearchAsyncClient": "Customizations.SearchClient", + "com.azure.search.documents.SearchAsyncClient.autocomplete": "Customizations.SearchClient.Documents.autocompletePost", + "com.azure.search.documents.SearchAsyncClient.autocompleteGet": "Customizations.SearchClient.Documents.autocompleteGet", + "com.azure.search.documents.SearchAsyncClient.autocompleteGetWithResponse": "Customizations.SearchClient.Documents.autocompleteGet", + "com.azure.search.documents.SearchAsyncClient.autocompleteWithResponse": "Customizations.SearchClient.Documents.autocompletePost", + "com.azure.search.documents.SearchAsyncClient.getDocument": "Customizations.SearchClient.Documents.get", + "com.azure.search.documents.SearchAsyncClient.getDocumentCount": "Customizations.SearchClient.Documents.count", + "com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse": "Customizations.SearchClient.Documents.count", + "com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse": "Customizations.SearchClient.Documents.get", + "com.azure.search.documents.SearchAsyncClient.index": "Customizations.SearchClient.Documents.index", + "com.azure.search.documents.SearchAsyncClient.indexWithResponse": "Customizations.SearchClient.Documents.index", + "com.azure.search.documents.SearchAsyncClient.search": "Customizations.SearchClient.Documents.searchPost", + "com.azure.search.documents.SearchAsyncClient.searchGet": "Customizations.SearchClient.Documents.searchGet", + "com.azure.search.documents.SearchAsyncClient.searchGetWithResponse": "Customizations.SearchClient.Documents.searchGet", + "com.azure.search.documents.SearchAsyncClient.searchWithResponse": "Customizations.SearchClient.Documents.searchPost", + "com.azure.search.documents.SearchAsyncClient.suggest": "Customizations.SearchClient.Documents.suggestPost", + "com.azure.search.documents.SearchAsyncClient.suggestGet": "Customizations.SearchClient.Documents.suggestGet", + "com.azure.search.documents.SearchAsyncClient.suggestGetWithResponse": "Customizations.SearchClient.Documents.suggestGet", + "com.azure.search.documents.SearchAsyncClient.suggestWithResponse": "Customizations.SearchClient.Documents.suggestPost", + "com.azure.search.documents.SearchClient": "Customizations.SearchClient", + "com.azure.search.documents.SearchClient.autocomplete": "Customizations.SearchClient.Documents.autocompletePost", + "com.azure.search.documents.SearchClient.autocompleteGet": "Customizations.SearchClient.Documents.autocompleteGet", + "com.azure.search.documents.SearchClient.autocompleteGetWithResponse": "Customizations.SearchClient.Documents.autocompleteGet", + "com.azure.search.documents.SearchClient.autocompleteWithResponse": "Customizations.SearchClient.Documents.autocompletePost", + "com.azure.search.documents.SearchClient.getDocument": "Customizations.SearchClient.Documents.get", + "com.azure.search.documents.SearchClient.getDocumentCount": "Customizations.SearchClient.Documents.count", + "com.azure.search.documents.SearchClient.getDocumentCountWithResponse": "Customizations.SearchClient.Documents.count", + "com.azure.search.documents.SearchClient.getDocumentWithResponse": "Customizations.SearchClient.Documents.get", + "com.azure.search.documents.SearchClient.index": "Customizations.SearchClient.Documents.index", + "com.azure.search.documents.SearchClient.indexWithResponse": "Customizations.SearchClient.Documents.index", + "com.azure.search.documents.SearchClient.search": "Customizations.SearchClient.Documents.searchPost", + "com.azure.search.documents.SearchClient.searchGet": "Customizations.SearchClient.Documents.searchGet", + "com.azure.search.documents.SearchClient.searchGetWithResponse": "Customizations.SearchClient.Documents.searchGet", + "com.azure.search.documents.SearchClient.searchWithResponse": "Customizations.SearchClient.Documents.searchPost", + "com.azure.search.documents.SearchClient.suggest": "Customizations.SearchClient.Documents.suggestPost", + "com.azure.search.documents.SearchClient.suggestGet": "Customizations.SearchClient.Documents.suggestGet", + "com.azure.search.documents.SearchClient.suggestGetWithResponse": "Customizations.SearchClient.Documents.suggestGet", + "com.azure.search.documents.SearchClient.suggestWithResponse": "Customizations.SearchClient.Documents.suggestPost", + "com.azure.search.documents.SearchClientBuilder": "Customizations.SearchClient", + "com.azure.search.documents.implementation.models.AutocompletePostRequest": "Customizations.SearchClient.autocompletePost.Request.anonymous", + "com.azure.search.documents.implementation.models.SearchPostRequest": "Customizations.SearchClient.searchPost.Request.anonymous", + "com.azure.search.documents.implementation.models.SuggestPostRequest": "Customizations.SearchClient.suggestPost.Request.anonymous", + "com.azure.search.documents.indexes.SearchIndexAsyncClient": "Customizations.SearchIndexClient", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.analyzeText": "Customizations.SearchIndexClient.Indexes.analyze", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.analyzeTextWithResponse": "Customizations.SearchIndexClient.Indexes.analyze", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createAlias": "Customizations.SearchIndexClient.Aliases.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createAliasWithResponse": "Customizations.SearchIndexClient.Aliases.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndex": "Customizations.SearchIndexClient.Indexes.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse": "Customizations.SearchIndexClient.Indexes.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeSource": "Customizations.SearchIndexClient.Sources.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAlias": "Customizations.SearchIndexClient.Aliases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAliasWithResponse": "Customizations.SearchIndexClient.Aliases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndex": "Customizations.SearchIndexClient.Indexes.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse": "Customizations.SearchIndexClient.Indexes.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeSource": "Customizations.SearchIndexClient.Sources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.create", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAlias": "Customizations.SearchIndexClient.Aliases.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAliasWithResponse": "Customizations.SearchIndexClient.Aliases.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndex": "Customizations.SearchIndexClient.Indexes.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse": "Customizations.SearchIndexClient.Indexes.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeSource": "Customizations.SearchIndexClient.Sources.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.delete", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getAlias": "Customizations.SearchIndexClient.Aliases.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getAliasWithResponse": "Customizations.SearchIndexClient.Aliases.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndex": "Customizations.SearchIndexClient.Indexes.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatistics": "Customizations.SearchIndexClient.Indexes.getStatistics", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatisticsWithResponse": "Customizations.SearchIndexClient.Indexes.getStatistics", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse": "Customizations.SearchIndexClient.Indexes.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSource": "Customizations.SearchIndexClient.Sources.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSourceStatus": "Customizations.SearchIndexClient.Sources.getStatus", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSourceStatusWithResponse": "Customizations.SearchIndexClient.Sources.getStatus", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatistics": "Customizations.SearchIndexClient.Root.getServiceStatistics", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatisticsWithResponse": "Customizations.SearchIndexClient.Root.getServiceStatistics", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.get", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMaps": "Customizations.SearchIndexClient.SynonymMaps.list", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapsWithResponse": "Customizations.SearchIndexClient.SynonymMaps.list", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.listAliases": "Customizations.SearchIndexClient.Aliases.list", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexStatsSummary": "Customizations.SearchIndexClient.Root.getIndexStatsSummary", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexes": "Customizations.SearchIndexClient.Indexes.list", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.listKnowledgeBases": "Customizations.SearchIndexClient.KnowledgeBases.list", + "com.azure.search.documents.indexes.SearchIndexAsyncClient.listKnowledgeSources": "Customizations.SearchIndexClient.Sources.list", + "com.azure.search.documents.indexes.SearchIndexClient": "Customizations.SearchIndexClient", + "com.azure.search.documents.indexes.SearchIndexClient.analyzeText": "Customizations.SearchIndexClient.Indexes.analyze", + "com.azure.search.documents.indexes.SearchIndexClient.analyzeTextWithResponse": "Customizations.SearchIndexClient.Indexes.analyze", + "com.azure.search.documents.indexes.SearchIndexClient.createAlias": "Customizations.SearchIndexClient.Aliases.create", + "com.azure.search.documents.indexes.SearchIndexClient.createAliasWithResponse": "Customizations.SearchIndexClient.Aliases.create", + "com.azure.search.documents.indexes.SearchIndexClient.createIndex": "Customizations.SearchIndexClient.Indexes.create", + "com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse": "Customizations.SearchIndexClient.Indexes.create", + "com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.create", + "com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.create", + "com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeSource": "Customizations.SearchIndexClient.Sources.create", + "com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.create", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAlias": "Customizations.SearchIndexClient.Aliases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAliasWithResponse": "Customizations.SearchIndexClient.Aliases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndex": "Customizations.SearchIndexClient.Indexes.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse": "Customizations.SearchIndexClient.Indexes.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeSource": "Customizations.SearchIndexClient.Sources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexClient.createSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.create", + "com.azure.search.documents.indexes.SearchIndexClient.createSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.create", + "com.azure.search.documents.indexes.SearchIndexClient.deleteAlias": "Customizations.SearchIndexClient.Aliases.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteAliasWithResponse": "Customizations.SearchIndexClient.Aliases.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteIndex": "Customizations.SearchIndexClient.Indexes.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse": "Customizations.SearchIndexClient.Indexes.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeSource": "Customizations.SearchIndexClient.Sources.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.delete", + "com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.delete", + "com.azure.search.documents.indexes.SearchIndexClient.getAlias": "Customizations.SearchIndexClient.Aliases.get", + "com.azure.search.documents.indexes.SearchIndexClient.getAliasWithResponse": "Customizations.SearchIndexClient.Aliases.get", + "com.azure.search.documents.indexes.SearchIndexClient.getIndex": "Customizations.SearchIndexClient.Indexes.get", + "com.azure.search.documents.indexes.SearchIndexClient.getIndexStatistics": "Customizations.SearchIndexClient.Indexes.getStatistics", + "com.azure.search.documents.indexes.SearchIndexClient.getIndexStatisticsWithResponse": "Customizations.SearchIndexClient.Indexes.getStatistics", + "com.azure.search.documents.indexes.SearchIndexClient.getIndexWithResponse": "Customizations.SearchIndexClient.Indexes.get", + "com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeBase": "Customizations.SearchIndexClient.KnowledgeBases.get", + "com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeBaseWithResponse": "Customizations.SearchIndexClient.KnowledgeBases.get", + "com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSource": "Customizations.SearchIndexClient.Sources.get", + "com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSourceStatus": "Customizations.SearchIndexClient.Sources.getStatus", + "com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSourceStatusWithResponse": "Customizations.SearchIndexClient.Sources.getStatus", + "com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSourceWithResponse": "Customizations.SearchIndexClient.Sources.get", + "com.azure.search.documents.indexes.SearchIndexClient.getServiceStatistics": "Customizations.SearchIndexClient.Root.getServiceStatistics", + "com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse": "Customizations.SearchIndexClient.Root.getServiceStatistics", + "com.azure.search.documents.indexes.SearchIndexClient.getSynonymMap": "Customizations.SearchIndexClient.SynonymMaps.get", + "com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapWithResponse": "Customizations.SearchIndexClient.SynonymMaps.get", + "com.azure.search.documents.indexes.SearchIndexClient.getSynonymMaps": "Customizations.SearchIndexClient.SynonymMaps.list", + "com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapsWithResponse": "Customizations.SearchIndexClient.SynonymMaps.list", + "com.azure.search.documents.indexes.SearchIndexClient.listAliases": "Customizations.SearchIndexClient.Aliases.list", + "com.azure.search.documents.indexes.SearchIndexClient.listIndexStatsSummary": "Customizations.SearchIndexClient.Root.getIndexStatsSummary", + "com.azure.search.documents.indexes.SearchIndexClient.listIndexes": "Customizations.SearchIndexClient.Indexes.list", + "com.azure.search.documents.indexes.SearchIndexClient.listKnowledgeBases": "Customizations.SearchIndexClient.KnowledgeBases.list", + "com.azure.search.documents.indexes.SearchIndexClient.listKnowledgeSources": "Customizations.SearchIndexClient.Sources.list", + "com.azure.search.documents.indexes.SearchIndexClientBuilder": "Customizations.SearchIndexClient", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient": "Customizations.SearchIndexerClient", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.create", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.create", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexer": "Customizations.SearchIndexerClient.Indexers.create", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.create", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexer": "Customizations.SearchIndexerClient.Indexers.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillset": "Customizations.SearchIndexerClient.Skillsets.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillset": "Customizations.SearchIndexerClient.Skillsets.create", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.create", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.delete", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.delete", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexer": "Customizations.SearchIndexerClient.Indexers.delete", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.delete", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillset": "Customizations.SearchIndexerClient.Skillsets.delete", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.delete", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.get", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.get", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnections": "Customizations.SearchIndexerClient.DataSources.list", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionsWithResponse": "Customizations.SearchIndexerClient.DataSources.list", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexer": "Customizations.SearchIndexerClient.Indexers.get", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatus": "Customizations.SearchIndexerClient.Indexers.getStatus", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse": "Customizations.SearchIndexerClient.Indexers.getStatus", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.get", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexers": "Customizations.SearchIndexerClient.Indexers.list", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexersWithResponse": "Customizations.SearchIndexerClient.Indexers.list", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillset": "Customizations.SearchIndexerClient.Skillsets.get", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.get", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsets": "Customizations.SearchIndexerClient.Skillsets.list", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetsWithResponse": "Customizations.SearchIndexerClient.Skillsets.list", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocuments": "Customizations.SearchIndexerClient.Indexers.resetDocs", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocumentsWithResponse": "Customizations.SearchIndexerClient.Indexers.resetDocs", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexer": "Customizations.SearchIndexerClient.Indexers.reset", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.reset", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkills": "Customizations.SearchIndexerClient.Skillsets.resetSkills", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkillsWithResponse": "Customizations.SearchIndexerClient.Skillsets.resetSkills", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resync": "Customizations.SearchIndexerClient.Indexers.resync", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.resyncWithResponse": "Customizations.SearchIndexerClient.Indexers.resync", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexer": "Customizations.SearchIndexerClient.Indexers.run", + "com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.run", + "com.azure.search.documents.indexes.SearchIndexerClient": "Customizations.SearchIndexerClient", + "com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.create", + "com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.create", + "com.azure.search.documents.indexes.SearchIndexerClient.createIndexer": "Customizations.SearchIndexerClient.Indexers.create", + "com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.create", + "com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexer": "Customizations.SearchIndexerClient.Indexers.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillset": "Customizations.SearchIndexerClient.Skillsets.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.createOrUpdate", + "com.azure.search.documents.indexes.SearchIndexerClient.createSkillset": "Customizations.SearchIndexerClient.Skillsets.create", + "com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.create", + "com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.delete", + "com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.delete", + "com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexer": "Customizations.SearchIndexerClient.Indexers.delete", + "com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.delete", + "com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillset": "Customizations.SearchIndexerClient.Skillsets.delete", + "com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.delete", + "com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnection": "Customizations.SearchIndexerClient.DataSources.get", + "com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionWithResponse": "Customizations.SearchIndexerClient.DataSources.get", + "com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnections": "Customizations.SearchIndexerClient.DataSources.list", + "com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionsWithResponse": "Customizations.SearchIndexerClient.DataSources.list", + "com.azure.search.documents.indexes.SearchIndexerClient.getIndexer": "Customizations.SearchIndexerClient.Indexers.get", + "com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatus": "Customizations.SearchIndexerClient.Indexers.getStatus", + "com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatusWithResponse": "Customizations.SearchIndexerClient.Indexers.getStatus", + "com.azure.search.documents.indexes.SearchIndexerClient.getIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.get", + "com.azure.search.documents.indexes.SearchIndexerClient.getIndexers": "Customizations.SearchIndexerClient.Indexers.list", + "com.azure.search.documents.indexes.SearchIndexerClient.getIndexersWithResponse": "Customizations.SearchIndexerClient.Indexers.list", + "com.azure.search.documents.indexes.SearchIndexerClient.getSkillset": "Customizations.SearchIndexerClient.Skillsets.get", + "com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetWithResponse": "Customizations.SearchIndexerClient.Skillsets.get", + "com.azure.search.documents.indexes.SearchIndexerClient.getSkillsets": "Customizations.SearchIndexerClient.Skillsets.list", + "com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetsWithResponse": "Customizations.SearchIndexerClient.Skillsets.list", + "com.azure.search.documents.indexes.SearchIndexerClient.resetDocuments": "Customizations.SearchIndexerClient.Indexers.resetDocs", + "com.azure.search.documents.indexes.SearchIndexerClient.resetDocumentsWithResponse": "Customizations.SearchIndexerClient.Indexers.resetDocs", + "com.azure.search.documents.indexes.SearchIndexerClient.resetIndexer": "Customizations.SearchIndexerClient.Indexers.reset", + "com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.reset", + "com.azure.search.documents.indexes.SearchIndexerClient.resetSkills": "Customizations.SearchIndexerClient.Skillsets.resetSkills", + "com.azure.search.documents.indexes.SearchIndexerClient.resetSkillsWithResponse": "Customizations.SearchIndexerClient.Skillsets.resetSkills", + "com.azure.search.documents.indexes.SearchIndexerClient.resync": "Customizations.SearchIndexerClient.Indexers.resync", + "com.azure.search.documents.indexes.SearchIndexerClient.resyncWithResponse": "Customizations.SearchIndexerClient.Indexers.resync", + "com.azure.search.documents.indexes.SearchIndexerClient.runIndexer": "Customizations.SearchIndexerClient.Indexers.run", + "com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse": "Customizations.SearchIndexerClient.Indexers.run", + "com.azure.search.documents.indexes.SearchIndexerClientBuilder": "Customizations.SearchIndexerClient", + "com.azure.search.documents.indexes.models.AIFoundryModelCatalogName": "Search.AIFoundryModelCatalogName", + "com.azure.search.documents.indexes.models.AIServicesAccountIdentity": "Search.AIServicesAccountIdentity", + "com.azure.search.documents.indexes.models.AIServicesAccountKey": "Search.AIServicesAccountKey", + "com.azure.search.documents.indexes.models.AIServicesVisionParameters": "Search.AIServicesVisionParameters", + "com.azure.search.documents.indexes.models.AIServicesVisionVectorizer": "Search.AIServicesVisionVectorizer", + "com.azure.search.documents.indexes.models.AnalyzeResult": "Search.AnalyzeResult", + "com.azure.search.documents.indexes.models.AnalyzeTextOptions": "Search.AnalyzeRequest", + "com.azure.search.documents.indexes.models.AnalyzedTokenInfo": "Search.AnalyzedTokenInfo", + "com.azure.search.documents.indexes.models.AsciiFoldingTokenFilter": "Search.AsciiFoldingTokenFilter", + "com.azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials": "Search.AzureActiveDirectoryApplicationCredentials", + "com.azure.search.documents.indexes.models.AzureBlobKnowledgeSource": "Search.AzureBlobKnowledgeSource", + "com.azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters": "Search.AzureBlobKnowledgeSourceParameters", + "com.azure.search.documents.indexes.models.AzureMachineLearningParameters": "Search.AMLParameters", + "com.azure.search.documents.indexes.models.AzureMachineLearningSkill": "Search.AzureMachineLearningSkill", + "com.azure.search.documents.indexes.models.AzureMachineLearningVectorizer": "Search.AMLVectorizer", + "com.azure.search.documents.indexes.models.AzureOpenAIEmbeddingSkill": "Search.AzureOpenAIEmbeddingSkill", + "com.azure.search.documents.indexes.models.AzureOpenAIModelName": "Search.AzureOpenAIModelName", + "com.azure.search.documents.indexes.models.AzureOpenAITokenizerParameters": "Search.AzureOpenAITokenizerParameters", + "com.azure.search.documents.indexes.models.AzureOpenAIVectorizer": "Search.AzureOpenAIVectorizer", + "com.azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters": "Search.AzureOpenAIVectorizerParameters", + "com.azure.search.documents.indexes.models.BM25SimilarityAlgorithm": "Search.BM25SimilarityAlgorithm", + "com.azure.search.documents.indexes.models.BinaryQuantizationCompression": "Search.BinaryQuantizationCompression", + "com.azure.search.documents.indexes.models.BlobIndexerDataToExtract": "Search.BlobIndexerDataToExtract", + "com.azure.search.documents.indexes.models.BlobIndexerImageAction": "Search.BlobIndexerImageAction", + "com.azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm": "Search.BlobIndexerPDFTextRotationAlgorithm", + "com.azure.search.documents.indexes.models.BlobIndexerParsingMode": "Search.BlobIndexerParsingMode", + "com.azure.search.documents.indexes.models.CharFilter": "Search.CharFilter", + "com.azure.search.documents.indexes.models.CharFilterName": "Search.CharFilterName", + "com.azure.search.documents.indexes.models.ChatCompletionCommonModelParameters": "Search.ChatCompletionCommonModelParameters", + "com.azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior": "Search.ChatCompletionExtraParametersBehavior", + "com.azure.search.documents.indexes.models.ChatCompletionResponseFormat": "Search.ChatCompletionResponseFormat", + "com.azure.search.documents.indexes.models.ChatCompletionResponseFormatType": "Search.ChatCompletionResponseFormatType", + "com.azure.search.documents.indexes.models.ChatCompletionSchema": "Search.ChatCompletionSchema", + "com.azure.search.documents.indexes.models.ChatCompletionSchemaProperties": "Search.ChatCompletionSchemaProperties", + "com.azure.search.documents.indexes.models.ChatCompletionSkill": "Search.ChatCompletionSkill", + "com.azure.search.documents.indexes.models.CjkBigramTokenFilter": "Search.CjkBigramTokenFilter", + "com.azure.search.documents.indexes.models.CjkBigramTokenFilterScripts": "Search.CjkBigramTokenFilterScripts", + "com.azure.search.documents.indexes.models.ClassicSimilarityAlgorithm": "Search.ClassicSimilarityAlgorithm", + "com.azure.search.documents.indexes.models.ClassicTokenizer": "Search.ClassicTokenizer", + "com.azure.search.documents.indexes.models.CognitiveServicesAccount": "Search.CognitiveServicesAccount", + "com.azure.search.documents.indexes.models.CognitiveServicesAccountKey": "Search.CognitiveServicesAccountKey", + "com.azure.search.documents.indexes.models.CommonGramTokenFilter": "Search.CommonGramTokenFilter", + "com.azure.search.documents.indexes.models.ConditionalSkill": "Search.ConditionalSkill", + "com.azure.search.documents.indexes.models.ContentUnderstandingSkill": "Search.ContentUnderstandingSkill", + "com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties": "Search.ContentUnderstandingSkillChunkingProperties", + "com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit": "Search.ContentUnderstandingSkillChunkingUnit", + "com.azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions": "Search.ContentUnderstandingSkillExtractionOptions", + "com.azure.search.documents.indexes.models.CorsOptions": "Search.CorsOptions", + "com.azure.search.documents.indexes.models.CreatedResources": "Search.CreatedResources", + "com.azure.search.documents.indexes.models.CustomAnalyzer": "Search.CustomAnalyzer", + "com.azure.search.documents.indexes.models.CustomEntity": "Search.CustomEntity", + "com.azure.search.documents.indexes.models.CustomEntityAlias": "Search.CustomEntityAlias", + "com.azure.search.documents.indexes.models.CustomEntityLookupSkill": "Search.CustomEntityLookupSkill", + "com.azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage": "Search.CustomEntityLookupSkillLanguage", + "com.azure.search.documents.indexes.models.CustomNormalizer": "Search.CustomNormalizer", + "com.azure.search.documents.indexes.models.DataChangeDetectionPolicy": "Search.DataChangeDetectionPolicy", + "com.azure.search.documents.indexes.models.DataDeletionDetectionPolicy": "Search.DataDeletionDetectionPolicy", + "com.azure.search.documents.indexes.models.DataSourceCredentials": "Search.DataSourceCredentials", + "com.azure.search.documents.indexes.models.DefaultCognitiveServicesAccount": "Search.DefaultCognitiveServicesAccount", + "com.azure.search.documents.indexes.models.DictionaryDecompounderTokenFilter": "Search.DictionaryDecompounderTokenFilter", + "com.azure.search.documents.indexes.models.DistanceScoringFunction": "Search.DistanceScoringFunction", + "com.azure.search.documents.indexes.models.DistanceScoringParameters": "Search.DistanceScoringParameters", + "com.azure.search.documents.indexes.models.DocumentExtractionSkill": "Search.DocumentExtractionSkill", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkill": "Search.DocumentIntelligenceLayoutSkill", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties": "Search.DocumentIntelligenceLayoutSkillChunkingProperties", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit": "Search.DocumentIntelligenceLayoutSkillChunkingUnit", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions": "Search.DocumentIntelligenceLayoutSkillExtractionOptions", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth": "Search.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat": "Search.DocumentIntelligenceLayoutSkillOutputFormat", + "com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode": "Search.DocumentIntelligenceLayoutSkillOutputMode", + "com.azure.search.documents.indexes.models.DocumentKeysOrIds": "Search.DocumentKeysOrIds", + "com.azure.search.documents.indexes.models.EdgeNGramTokenFilter": "Search.EdgeNGramTokenFilter", + "com.azure.search.documents.indexes.models.EdgeNGramTokenFilterSide": "Search.EdgeNGramTokenFilterSide", + "com.azure.search.documents.indexes.models.EdgeNGramTokenFilterV2": "Search.EdgeNGramTokenFilterV2", + "com.azure.search.documents.indexes.models.EdgeNGramTokenizer": "Search.EdgeNGramTokenizer", + "com.azure.search.documents.indexes.models.ElisionTokenFilter": "Search.ElisionTokenFilter", + "com.azure.search.documents.indexes.models.EntityLinkingSkill": "Search.EntityLinkingSkill", + "com.azure.search.documents.indexes.models.EntityRecognitionSkillV3": "Search.EntityRecognitionSkillV3", + "com.azure.search.documents.indexes.models.ExhaustiveKnnAlgorithmConfiguration": "Search.ExhaustiveKnnAlgorithmConfiguration", + "com.azure.search.documents.indexes.models.ExhaustiveKnnParameters": "Search.ExhaustiveKnnParameters", + "com.azure.search.documents.indexes.models.FieldMapping": "Search.FieldMapping", + "com.azure.search.documents.indexes.models.FieldMappingFunction": "Search.FieldMappingFunction", + "com.azure.search.documents.indexes.models.FreshnessScoringFunction": "Search.FreshnessScoringFunction", + "com.azure.search.documents.indexes.models.FreshnessScoringParameters": "Search.FreshnessScoringParameters", + "com.azure.search.documents.indexes.models.GetIndexStatisticsResult": "Search.GetIndexStatisticsResult", + "com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy": "Search.HighWaterMarkChangeDetectionPolicy", + "com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration": "Search.HnswAlgorithmConfiguration", + "com.azure.search.documents.indexes.models.HnswParameters": "Search.HnswParameters", + "com.azure.search.documents.indexes.models.ImageAnalysisSkill": "Search.ImageAnalysisSkill", + "com.azure.search.documents.indexes.models.ImageAnalysisSkillLanguage": "Search.ImageAnalysisSkillLanguage", + "com.azure.search.documents.indexes.models.ImageDetail": "Search.ImageDetail", + "com.azure.search.documents.indexes.models.IndexProjectionMode": "Search.IndexProjectionMode", + "com.azure.search.documents.indexes.models.IndexStatisticsSummary": "Search.IndexStatisticsSummary", + "com.azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSource": "Search.IndexedOneLakeKnowledgeSource", + "com.azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSourceParameters": "Search.IndexedOneLakeKnowledgeSourceParameters", + "com.azure.search.documents.indexes.models.IndexedSharePointContainerName": "Search.IndexedSharePointContainerName", + "com.azure.search.documents.indexes.models.IndexedSharePointKnowledgeSource": "Search.IndexedSharePointKnowledgeSource", + "com.azure.search.documents.indexes.models.IndexedSharePointKnowledgeSourceParameters": "Search.IndexedSharePointKnowledgeSourceParameters", + "com.azure.search.documents.indexes.models.IndexerCurrentState": "Search.IndexerCurrentState", + "com.azure.search.documents.indexes.models.IndexerExecutionEnvironment": "Search.IndexerExecutionEnvironment", + "com.azure.search.documents.indexes.models.IndexerExecutionResult": "Search.IndexerExecutionResult", + "com.azure.search.documents.indexes.models.IndexerExecutionStatus": "Search.IndexerExecutionStatus", + "com.azure.search.documents.indexes.models.IndexerExecutionStatusDetail": "Search.IndexerExecutionStatusDetail", + "com.azure.search.documents.indexes.models.IndexerPermissionOption": "Search.IndexerPermissionOption", + "com.azure.search.documents.indexes.models.IndexerResyncBody": "Search.IndexerResyncBody", + "com.azure.search.documents.indexes.models.IndexerResyncOption": "Search.IndexerResyncOption", + "com.azure.search.documents.indexes.models.IndexerRuntime": "Search.IndexerRuntime", + "com.azure.search.documents.indexes.models.IndexerStatus": "Search.IndexerStatus", + "com.azure.search.documents.indexes.models.IndexingMode": "Search.IndexingMode", + "com.azure.search.documents.indexes.models.IndexingParameters": "Search.IndexingParameters", + "com.azure.search.documents.indexes.models.IndexingParametersConfiguration": "Search.IndexingParametersConfiguration", + "com.azure.search.documents.indexes.models.IndexingSchedule": "Search.IndexingSchedule", + "com.azure.search.documents.indexes.models.InputFieldMappingEntry": "Search.InputFieldMappingEntry", + "com.azure.search.documents.indexes.models.KeepTokenFilter": "Search.KeepTokenFilter", + "com.azure.search.documents.indexes.models.KeyPhraseExtractionSkill": "Search.KeyPhraseExtractionSkill", + "com.azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage": "Search.KeyPhraseExtractionSkillLanguage", + "com.azure.search.documents.indexes.models.KeywordMarkerTokenFilter": "Search.KeywordMarkerTokenFilter", + "com.azure.search.documents.indexes.models.KeywordTokenizer": "Search.KeywordTokenizer", + "com.azure.search.documents.indexes.models.KeywordTokenizerV2": "Search.KeywordTokenizerV2", + "com.azure.search.documents.indexes.models.KnowledgeBase": "Search.KnowledgeBase", + "com.azure.search.documents.indexes.models.KnowledgeBaseAzureOpenAIModel": "Search.KnowledgeBaseAzureOpenAIModel", + "com.azure.search.documents.indexes.models.KnowledgeBaseModel": "Search.KnowledgeBaseModel", + "com.azure.search.documents.indexes.models.KnowledgeBaseModelKind": "Search.KnowledgeBaseModelKind", + "com.azure.search.documents.indexes.models.KnowledgeSource": "Search.KnowledgeSource", + "com.azure.search.documents.indexes.models.KnowledgeSourceContentExtractionMode": "Search.KnowledgeSourceContentExtractionMode", + "com.azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption": "Search.KnowledgeSourceIngestionPermissionOption", + "com.azure.search.documents.indexes.models.KnowledgeSourceKind": "Search.KnowledgeSourceKind", + "com.azure.search.documents.indexes.models.KnowledgeSourceReference": "Search.KnowledgeSourceReference", + "com.azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus": "Search.KnowledgeSourceSynchronizationStatus", + "com.azure.search.documents.indexes.models.LanguageDetectionSkill": "Search.LanguageDetectionSkill", + "com.azure.search.documents.indexes.models.LengthTokenFilter": "Search.LengthTokenFilter", + "com.azure.search.documents.indexes.models.LexicalAnalyzer": "Search.LexicalAnalyzer", + "com.azure.search.documents.indexes.models.LexicalAnalyzerName": "Search.LexicalAnalyzerName", + "com.azure.search.documents.indexes.models.LexicalNormalizer": "Search.LexicalNormalizer", + "com.azure.search.documents.indexes.models.LexicalNormalizerName": "Search.LexicalNormalizerName", + "com.azure.search.documents.indexes.models.LexicalTokenizer": "Search.LexicalTokenizer", + "com.azure.search.documents.indexes.models.LexicalTokenizerName": "Search.LexicalTokenizerName", + "com.azure.search.documents.indexes.models.LimitTokenFilter": "Search.LimitTokenFilter", + "com.azure.search.documents.indexes.models.ListDataSourcesResult": "Search.ListDataSourcesResult", + "com.azure.search.documents.indexes.models.ListIndexersResult": "Search.ListIndexersResult", + "com.azure.search.documents.indexes.models.ListSkillsetsResult": "Search.ListSkillsetsResult", + "com.azure.search.documents.indexes.models.ListSynonymMapsResult": "Search.ListSynonymMapsResult", + "com.azure.search.documents.indexes.models.LuceneStandardAnalyzer": "Search.LuceneStandardAnalyzer", + "com.azure.search.documents.indexes.models.LuceneStandardTokenizer": "Search.LuceneStandardTokenizer", + "com.azure.search.documents.indexes.models.LuceneStandardTokenizerV2": "Search.LuceneStandardTokenizerV2", + "com.azure.search.documents.indexes.models.MagnitudeScoringFunction": "Search.MagnitudeScoringFunction", + "com.azure.search.documents.indexes.models.MagnitudeScoringParameters": "Search.MagnitudeScoringParameters", + "com.azure.search.documents.indexes.models.MappingCharFilter": "Search.MappingCharFilter", + "com.azure.search.documents.indexes.models.MarkdownHeaderDepth": "Search.MarkdownHeaderDepth", + "com.azure.search.documents.indexes.models.MarkdownParsingSubmode": "Search.MarkdownParsingSubmode", + "com.azure.search.documents.indexes.models.MergeSkill": "Search.MergeSkill", + "com.azure.search.documents.indexes.models.MicrosoftLanguageStemmingTokenizer": "Search.MicrosoftLanguageStemmingTokenizer", + "com.azure.search.documents.indexes.models.MicrosoftLanguageTokenizer": "Search.MicrosoftLanguageTokenizer", + "com.azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage": "Search.MicrosoftStemmingTokenizerLanguage", + "com.azure.search.documents.indexes.models.MicrosoftTokenizerLanguage": "Search.MicrosoftTokenizerLanguage", + "com.azure.search.documents.indexes.models.NGramTokenFilter": "Search.NGramTokenFilter", + "com.azure.search.documents.indexes.models.NGramTokenFilterV2": "Search.NGramTokenFilterV2", + "com.azure.search.documents.indexes.models.NGramTokenizer": "Search.NGramTokenizer", + "com.azure.search.documents.indexes.models.NativeBlobSoftDeleteDeletionDetectionPolicy": "Search.NativeBlobSoftDeleteDeletionDetectionPolicy", + "com.azure.search.documents.indexes.models.OcrLineEnding": "Search.OcrLineEnding", + "com.azure.search.documents.indexes.models.OcrSkill": "Search.OcrSkill", + "com.azure.search.documents.indexes.models.OcrSkillLanguage": "Search.OcrSkillLanguage", + "com.azure.search.documents.indexes.models.OutputFieldMappingEntry": "Search.OutputFieldMappingEntry", + "com.azure.search.documents.indexes.models.PIIDetectionSkill": "Search.PIIDetectionSkill", + "com.azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode": "Search.PIIDetectionSkillMaskingMode", + "com.azure.search.documents.indexes.models.PathHierarchyTokenizerV2": "Search.PathHierarchyTokenizerV2", + "com.azure.search.documents.indexes.models.PatternAnalyzer": "Search.PatternAnalyzer", + "com.azure.search.documents.indexes.models.PatternCaptureTokenFilter": "Search.PatternCaptureTokenFilter", + "com.azure.search.documents.indexes.models.PatternReplaceCharFilter": "Search.PatternReplaceCharFilter", + "com.azure.search.documents.indexes.models.PatternReplaceTokenFilter": "Search.PatternReplaceTokenFilter", + "com.azure.search.documents.indexes.models.PatternTokenizer": "Search.PatternTokenizer", + "com.azure.search.documents.indexes.models.PermissionFilter": "Search.PermissionFilter", + "com.azure.search.documents.indexes.models.PhoneticEncoder": "Search.PhoneticEncoder", + "com.azure.search.documents.indexes.models.PhoneticTokenFilter": "Search.PhoneticTokenFilter", + "com.azure.search.documents.indexes.models.RankingOrder": "Search.RankingOrder", + "com.azure.search.documents.indexes.models.RegexFlags": "Search.RegexFlags", + "com.azure.search.documents.indexes.models.RemoteSharePointKnowledgeSource": "Search.RemoteSharePointKnowledgeSource", + "com.azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters": "Search.RemoteSharePointKnowledgeSourceParameters", + "com.azure.search.documents.indexes.models.RescoringOptions": "Search.RescoringOptions", + "com.azure.search.documents.indexes.models.ResourceCounter": "Search.ResourceCounter", + "com.azure.search.documents.indexes.models.ScalarQuantizationCompression": "Search.ScalarQuantizationCompression", + "com.azure.search.documents.indexes.models.ScalarQuantizationParameters": "Search.ScalarQuantizationParameters", + "com.azure.search.documents.indexes.models.ScoringFunction": "Search.ScoringFunction", + "com.azure.search.documents.indexes.models.ScoringFunctionAggregation": "Search.ScoringFunctionAggregation", + "com.azure.search.documents.indexes.models.ScoringFunctionInterpolation": "Search.ScoringFunctionInterpolation", + "com.azure.search.documents.indexes.models.ScoringProfile": "Search.ScoringProfile", + "com.azure.search.documents.indexes.models.SearchAlias": "Search.SearchAlias", + "com.azure.search.documents.indexes.models.SearchField": "Search.SearchField", + "com.azure.search.documents.indexes.models.SearchFieldDataType": "Search.SearchFieldDataType", + "com.azure.search.documents.indexes.models.SearchIndex": "Search.SearchIndex", + "com.azure.search.documents.indexes.models.SearchIndexFieldReference": "Search.SearchIndexFieldReference", + "com.azure.search.documents.indexes.models.SearchIndexKnowledgeSource": "Search.SearchIndexKnowledgeSource", + "com.azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters": "Search.SearchIndexKnowledgeSourceParameters", + "com.azure.search.documents.indexes.models.SearchIndexPermissionFilterOption": "Search.SearchIndexPermissionFilterOption", + "com.azure.search.documents.indexes.models.SearchIndexer": "Search.SearchIndexer", + "com.azure.search.documents.indexes.models.SearchIndexerCache": "Search.SearchIndexerCache", + "com.azure.search.documents.indexes.models.SearchIndexerDataContainer": "Search.SearchIndexerDataContainer", + "com.azure.search.documents.indexes.models.SearchIndexerDataIdentity": "Search.SearchIndexerDataIdentity", + "com.azure.search.documents.indexes.models.SearchIndexerDataNoneIdentity": "Search.SearchIndexerDataNoneIdentity", + "com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection": "Search.SearchIndexerDataSource", + "com.azure.search.documents.indexes.models.SearchIndexerDataSourceType": "Search.SearchIndexerDataSourceType", + "com.azure.search.documents.indexes.models.SearchIndexerDataUserAssignedIdentity": "Search.SearchIndexerDataUserAssignedIdentity", + "com.azure.search.documents.indexes.models.SearchIndexerError": "Search.SearchIndexerError", + "com.azure.search.documents.indexes.models.SearchIndexerIndexProjection": "Search.SearchIndexerIndexProjection", + "com.azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector": "Search.SearchIndexerIndexProjectionSelector", + "com.azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters": "Search.SearchIndexerIndexProjectionsParameters", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStore": "Search.SearchIndexerKnowledgeStore", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreBlobProjectionSelector": "Search.SearchIndexerKnowledgeStoreBlobProjectionSelector", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector": "Search.SearchIndexerKnowledgeStoreFileProjectionSelector", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector": "Search.SearchIndexerKnowledgeStoreObjectProjectionSelector", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters": "Search.SearchIndexerKnowledgeStoreParameters", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection": "Search.SearchIndexerKnowledgeStoreProjection", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjectionSelector": "Search.SearchIndexerKnowledgeStoreProjectionSelector", + "com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector": "Search.SearchIndexerKnowledgeStoreTableProjectionSelector", + "com.azure.search.documents.indexes.models.SearchIndexerLimits": "Search.SearchIndexerLimits", + "com.azure.search.documents.indexes.models.SearchIndexerSkill": "Search.SearchIndexerSkill", + "com.azure.search.documents.indexes.models.SearchIndexerSkillset": "Search.SearchIndexerSkillset", + "com.azure.search.documents.indexes.models.SearchIndexerStatus": "Search.SearchIndexerStatus", + "com.azure.search.documents.indexes.models.SearchIndexerWarning": "Search.SearchIndexerWarning", + "com.azure.search.documents.indexes.models.SearchResourceEncryptionKey": "Search.SearchResourceEncryptionKey", + "com.azure.search.documents.indexes.models.SearchServiceCounters": "Search.SearchServiceCounters", + "com.azure.search.documents.indexes.models.SearchServiceLimits": "Search.SearchServiceLimits", + "com.azure.search.documents.indexes.models.SearchServiceStatistics": "Search.SearchServiceStatistics", + "com.azure.search.documents.indexes.models.SearchSuggester": "Search.SearchSuggester", + "com.azure.search.documents.indexes.models.SemanticConfiguration": "Search.SemanticConfiguration", + "com.azure.search.documents.indexes.models.SemanticField": "Search.SemanticField", + "com.azure.search.documents.indexes.models.SemanticPrioritizedFields": "Search.SemanticPrioritizedFields", + "com.azure.search.documents.indexes.models.SemanticSearch": "Search.SemanticSearch", + "com.azure.search.documents.indexes.models.SentimentSkillV3": "Search.SentimentSkillV3", + "com.azure.search.documents.indexes.models.ServiceIndexersRuntime": "Search.ServiceIndexersRuntime", + "com.azure.search.documents.indexes.models.ShaperSkill": "Search.ShaperSkill", + "com.azure.search.documents.indexes.models.ShingleTokenFilter": "Search.ShingleTokenFilter", + "com.azure.search.documents.indexes.models.SimilarityAlgorithm": "Search.SimilarityAlgorithm", + "com.azure.search.documents.indexes.models.SkillNames": "Search.SkillNames", + "com.azure.search.documents.indexes.models.SnowballTokenFilter": "Search.SnowballTokenFilter", + "com.azure.search.documents.indexes.models.SnowballTokenFilterLanguage": "Search.SnowballTokenFilterLanguage", + "com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy": "Search.SoftDeleteColumnDeletionDetectionPolicy", + "com.azure.search.documents.indexes.models.SplitSkill": "Search.SplitSkill", + "com.azure.search.documents.indexes.models.SplitSkillEncoderModelName": "Search.SplitSkillEncoderModelName", + "com.azure.search.documents.indexes.models.SplitSkillLanguage": "Search.SplitSkillLanguage", + "com.azure.search.documents.indexes.models.SplitSkillUnit": "Search.SplitSkillUnit", + "com.azure.search.documents.indexes.models.SqlIntegratedChangeTrackingPolicy": "Search.SqlIntegratedChangeTrackingPolicy", + "com.azure.search.documents.indexes.models.StemmerOverrideTokenFilter": "Search.StemmerOverrideTokenFilter", + "com.azure.search.documents.indexes.models.StemmerTokenFilter": "Search.StemmerTokenFilter", + "com.azure.search.documents.indexes.models.StemmerTokenFilterLanguage": "Search.StemmerTokenFilterLanguage", + "com.azure.search.documents.indexes.models.StopAnalyzer": "Search.StopAnalyzer", + "com.azure.search.documents.indexes.models.StopwordsList": "Search.StopwordsList", + "com.azure.search.documents.indexes.models.StopwordsTokenFilter": "Search.StopwordsTokenFilter", + "com.azure.search.documents.indexes.models.SynonymMap": "Search.SynonymMap", + "com.azure.search.documents.indexes.models.SynonymTokenFilter": "Search.SynonymTokenFilter", + "com.azure.search.documents.indexes.models.TagScoringFunction": "Search.TagScoringFunction", + "com.azure.search.documents.indexes.models.TagScoringParameters": "Search.TagScoringParameters", + "com.azure.search.documents.indexes.models.TextSplitMode": "Search.TextSplitMode", + "com.azure.search.documents.indexes.models.TextTranslationSkill": "Search.TextTranslationSkill", + "com.azure.search.documents.indexes.models.TextTranslationSkillLanguage": "Search.TextTranslationSkillLanguage", + "com.azure.search.documents.indexes.models.TextWeights": "Search.TextWeights", + "com.azure.search.documents.indexes.models.TokenCharacterKind": "Search.TokenCharacterKind", + "com.azure.search.documents.indexes.models.TokenFilter": "Search.TokenFilter", + "com.azure.search.documents.indexes.models.TokenFilterName": "Search.TokenFilterName", + "com.azure.search.documents.indexes.models.TruncateTokenFilter": "Search.TruncateTokenFilter", + "com.azure.search.documents.indexes.models.UaxUrlEmailTokenizer": "Search.UaxUrlEmailTokenizer", + "com.azure.search.documents.indexes.models.UniqueTokenFilter": "Search.UniqueTokenFilter", + "com.azure.search.documents.indexes.models.VectorEncodingFormat": "Search.VectorEncodingFormat", + "com.azure.search.documents.indexes.models.VectorSearch": "Search.VectorSearch", + "com.azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration": "Search.VectorSearchAlgorithmConfiguration", + "com.azure.search.documents.indexes.models.VectorSearchAlgorithmKind": "Search.VectorSearchAlgorithmKind", + "com.azure.search.documents.indexes.models.VectorSearchAlgorithmMetric": "Search.VectorSearchAlgorithmMetric", + "com.azure.search.documents.indexes.models.VectorSearchCompression": "Search.VectorSearchCompression", + "com.azure.search.documents.indexes.models.VectorSearchCompressionKind": "Search.VectorSearchCompressionKind", + "com.azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod": "Search.VectorSearchCompressionRescoreStorageMethod", + "com.azure.search.documents.indexes.models.VectorSearchCompressionTarget": "Search.VectorSearchCompressionTarget", + "com.azure.search.documents.indexes.models.VectorSearchProfile": "Search.VectorSearchProfile", + "com.azure.search.documents.indexes.models.VectorSearchVectorizer": "Search.VectorSearchVectorizer", + "com.azure.search.documents.indexes.models.VectorSearchVectorizerKind": "Search.VectorSearchVectorizerKind", + "com.azure.search.documents.indexes.models.VisionVectorizeSkill": "Search.VisionVectorizeSkill", + "com.azure.search.documents.indexes.models.VisualFeature": "Search.VisualFeature", + "com.azure.search.documents.indexes.models.WebApiHttpHeaders": "Search.WebApiHttpHeaders", + "com.azure.search.documents.indexes.models.WebApiSkill": "Search.WebApiSkill", + "com.azure.search.documents.indexes.models.WebApiVectorizer": "Search.WebApiVectorizer", + "com.azure.search.documents.indexes.models.WebApiVectorizerParameters": "Search.WebApiVectorizerParameters", + "com.azure.search.documents.indexes.models.WebKnowledgeSource": "Search.WebKnowledgeSource", + "com.azure.search.documents.indexes.models.WebKnowledgeSourceDomain": "Search.WebKnowledgeSourceDomain", + "com.azure.search.documents.indexes.models.WebKnowledgeSourceDomains": "Search.WebKnowledgeSourceDomains", + "com.azure.search.documents.indexes.models.WebKnowledgeSourceParameters": "Search.WebKnowledgeSourceParameters", + "com.azure.search.documents.indexes.models.WordDelimiterTokenFilter": "Search.WordDelimiterTokenFilter", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalAsyncClient": "Customizations.KnowledgeBaseRetrievalClient", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalAsyncClient.retrieve": "Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalAsyncClient.retrieveWithResponse": "Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient": "Customizations.KnowledgeBaseRetrievalClient", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient.retrieve": "Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient.retrieveWithResponse": "Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve", + "com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClientBuilder": "Customizations.KnowledgeBaseRetrievalClient", + "com.azure.search.documents.knowledgebases.models.AIServices": "Search.AIServices", + "com.azure.search.documents.knowledgebases.models.AzureBlobKnowledgeSourceParams": "Search.AzureBlobKnowledgeSourceParams", + "com.azure.search.documents.knowledgebases.models.CompletedSynchronizationState": "Search.CompletedSynchronizationState", + "com.azure.search.documents.knowledgebases.models.IndexedOneLakeKnowledgeSourceParams": "Search.IndexedOneLakeKnowledgeSourceParams", + "com.azure.search.documents.knowledgebases.models.IndexedSharePointKnowledgeSourceParams": "Search.IndexedSharePointKnowledgeSourceParams", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecord": "Search.KnowledgeBaseActivityRecord", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecordType": "Search.KnowledgeBaseActivityRecordType", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseAgenticReasoningActivityRecord": "Search.KnowledgeBaseAgenticReasoningActivityRecord", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseAzureBlobReference": "Search.KnowledgeBaseAzureBlobReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseErrorAdditionalInfo": "Search.KnowledgeBaseErrorAdditionalInfo", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail": "Search.KnowledgeBaseErrorDetail", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseImageContent": "Search.KnowledgeBaseImageContent", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedOneLakeReference": "Search.KnowledgeBaseIndexedOneLakeReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedSharePointReference": "Search.KnowledgeBaseIndexedSharePointReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessage": "Search.KnowledgeBaseMessage", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContent": "Search.KnowledgeBaseMessageContent", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContentType": "Search.KnowledgeBaseMessageContentType", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageImageContent": "Search.KnowledgeBaseMessageImageContent", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageTextContent": "Search.KnowledgeBaseMessageTextContent", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseModelAnswerSynthesisActivityRecord": "Search.KnowledgeBaseModelAnswerSynthesisActivityRecord", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseModelQueryPlanningActivityRecord": "Search.KnowledgeBaseModelQueryPlanningActivityRecord", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseReference": "Search.KnowledgeBaseReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseReferenceType": "Search.KnowledgeBaseReferenceType", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseRemoteSharePointReference": "Search.KnowledgeBaseRemoteSharePointReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest": "Search.KnowledgeBaseRetrievalRequest", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse": "Search.KnowledgeBaseRetrievalResponse", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseSearchIndexReference": "Search.KnowledgeBaseSearchIndexReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeBaseWebReference": "Search.KnowledgeBaseWebReference", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntent": "Search.KnowledgeRetrievalIntent", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntentType": "Search.KnowledgeRetrievalIntentType", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalLowReasoningEffort": "Search.KnowledgeRetrievalLowReasoningEffort", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalMediumReasoningEffort": "Search.KnowledgeRetrievalMediumReasoningEffort", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalMinimalReasoningEffort": "Search.KnowledgeRetrievalMinimalReasoningEffort", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode": "Search.KnowledgeRetrievalOutputMode", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort": "Search.KnowledgeRetrievalReasoningEffort", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind": "Search.KnowledgeRetrievalReasoningEffortKind", + "com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalSemanticIntent": "Search.KnowledgeRetrievalSemanticIntent", + "com.azure.search.documents.knowledgebases.models.KnowledgeSourceAzureOpenAIVectorizer": "Search.KnowledgeSourceAzureOpenAIVectorizer", + "com.azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters": "Search.KnowledgeSourceIngestionParameters", + "com.azure.search.documents.knowledgebases.models.KnowledgeSourceParams": "Search.KnowledgeSourceParams", + "com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatistics": "Search.KnowledgeSourceStatistics", + "com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatus": "Search.KnowledgeSourceStatus", + "com.azure.search.documents.knowledgebases.models.KnowledgeSourceVectorizer": "Search.KnowledgeSourceVectorizer", + "com.azure.search.documents.knowledgebases.models.RemoteSharePointKnowledgeSourceParams": "Search.RemoteSharePointKnowledgeSourceParams", + "com.azure.search.documents.knowledgebases.models.SearchIndexKnowledgeSourceParams": "Search.SearchIndexKnowledgeSourceParams", + "com.azure.search.documents.knowledgebases.models.SharePointSensitivityLabelInfo": "Search.SharePointSensitivityLabelInfo", + "com.azure.search.documents.knowledgebases.models.SynchronizationState": "Search.SynchronizationState", + "com.azure.search.documents.knowledgebases.models.WebKnowledgeSourceParams": "Search.WebKnowledgeSourceParams", + "com.azure.search.documents.models.AutocompleteItem": "Search.AutocompleteItem", + "com.azure.search.documents.models.AutocompleteMode": "Search.AutocompleteMode", + "com.azure.search.documents.models.AutocompleteOptions": null, + "com.azure.search.documents.models.AutocompleteResult": "Search.AutocompleteResult", + "com.azure.search.documents.models.DebugInfo": "Search.DebugInfo", + "com.azure.search.documents.models.DocumentDebugInfo": "Search.DocumentDebugInfo", + "com.azure.search.documents.models.FacetResult": "Search.FacetResult", + "com.azure.search.documents.models.HybridCountAndFacetMode": "Search.HybridCountAndFacetMode", + "com.azure.search.documents.models.HybridSearch": "Search.HybridSearch", + "com.azure.search.documents.models.IndexAction": "Search.IndexAction", + "com.azure.search.documents.models.IndexActionType": "Search.IndexActionType", + "com.azure.search.documents.models.IndexDocumentsBatch": "Search.IndexBatch", + "com.azure.search.documents.models.IndexDocumentsResult": "Search.IndexDocumentsResult", + "com.azure.search.documents.models.IndexingResult": "Search.IndexingResult", + "com.azure.search.documents.models.LookupDocument": "Search.LookupDocument", + "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.QueryResultDocumentInnerHit": "Search.QueryResultDocumentInnerHit", + "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.ScoringStatistics": "Search.ScoringStatistics", + "com.azure.search.documents.models.SearchDocumentsResult": "Search.SearchDocumentsResult", + "com.azure.search.documents.models.SearchMode": "Search.SearchMode", + "com.azure.search.documents.models.SearchOptions": null, + "com.azure.search.documents.models.SearchRequest": "Search.SearchRequest", + "com.azure.search.documents.models.SearchResult": "Search.SearchResult", + "com.azure.search.documents.models.SearchScoreThreshold": "Search.SearchScoreThreshold", + "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.SemanticFieldState": "Search.SemanticFieldState", + "com.azure.search.documents.models.SemanticQueryRewritesResultType": "Search.SemanticQueryRewritesResultType", + "com.azure.search.documents.models.SemanticSearchResultsType": "Search.SemanticSearchResultsType", + "com.azure.search.documents.models.SingleVectorFieldResult": "Search.SingleVectorFieldResult", + "com.azure.search.documents.models.SuggestDocumentsResult": "Search.SuggestDocumentsResult", + "com.azure.search.documents.models.SuggestOptions": null, + "com.azure.search.documents.models.SuggestResult": "Search.SuggestResult", + "com.azure.search.documents.models.TextResult": "Search.TextResult", + "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.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" + } +} diff --git a/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_metadata.json b/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_metadata.json new file mode 100644 index 000000000000..7e50412056c5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/resources/META-INF/azure-search-documents_metadata.json @@ -0,0 +1 @@ +{"flavor":"azure","apiVersion":"2025-11-01-preview","crossLanguageDefinitions":{"com.azure.search.documents.SearchAsyncClient":"Customizations.SearchClient","com.azure.search.documents.SearchAsyncClient.autocomplete":"Customizations.SearchClient.Documents.autocompletePost","com.azure.search.documents.SearchAsyncClient.autocompleteGet":"Customizations.SearchClient.Documents.autocompleteGet","com.azure.search.documents.SearchAsyncClient.autocompleteGetWithResponse":"Customizations.SearchClient.Documents.autocompleteGet","com.azure.search.documents.SearchAsyncClient.autocompleteWithResponse":"Customizations.SearchClient.Documents.autocompletePost","com.azure.search.documents.SearchAsyncClient.getDocument":"Customizations.SearchClient.Documents.get","com.azure.search.documents.SearchAsyncClient.getDocumentCount":"Customizations.SearchClient.Documents.count","com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse":"Customizations.SearchClient.Documents.count","com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse":"Customizations.SearchClient.Documents.get","com.azure.search.documents.SearchAsyncClient.index":"Customizations.SearchClient.Documents.index","com.azure.search.documents.SearchAsyncClient.indexWithResponse":"Customizations.SearchClient.Documents.index","com.azure.search.documents.SearchAsyncClient.search":"Customizations.SearchClient.Documents.searchPost","com.azure.search.documents.SearchAsyncClient.searchGet":"Customizations.SearchClient.Documents.searchGet","com.azure.search.documents.SearchAsyncClient.searchGetWithResponse":"Customizations.SearchClient.Documents.searchGet","com.azure.search.documents.SearchAsyncClient.searchWithResponse":"Customizations.SearchClient.Documents.searchPost","com.azure.search.documents.SearchAsyncClient.suggest":"Customizations.SearchClient.Documents.suggestPost","com.azure.search.documents.SearchAsyncClient.suggestGet":"Customizations.SearchClient.Documents.suggestGet","com.azure.search.documents.SearchAsyncClient.suggestGetWithResponse":"Customizations.SearchClient.Documents.suggestGet","com.azure.search.documents.SearchAsyncClient.suggestWithResponse":"Customizations.SearchClient.Documents.suggestPost","com.azure.search.documents.SearchClient":"Customizations.SearchClient","com.azure.search.documents.SearchClient.autocomplete":"Customizations.SearchClient.Documents.autocompletePost","com.azure.search.documents.SearchClient.autocompleteGet":"Customizations.SearchClient.Documents.autocompleteGet","com.azure.search.documents.SearchClient.autocompleteGetWithResponse":"Customizations.SearchClient.Documents.autocompleteGet","com.azure.search.documents.SearchClient.autocompleteWithResponse":"Customizations.SearchClient.Documents.autocompletePost","com.azure.search.documents.SearchClient.getDocument":"Customizations.SearchClient.Documents.get","com.azure.search.documents.SearchClient.getDocumentCount":"Customizations.SearchClient.Documents.count","com.azure.search.documents.SearchClient.getDocumentCountWithResponse":"Customizations.SearchClient.Documents.count","com.azure.search.documents.SearchClient.getDocumentWithResponse":"Customizations.SearchClient.Documents.get","com.azure.search.documents.SearchClient.index":"Customizations.SearchClient.Documents.index","com.azure.search.documents.SearchClient.indexWithResponse":"Customizations.SearchClient.Documents.index","com.azure.search.documents.SearchClient.search":"Customizations.SearchClient.Documents.searchPost","com.azure.search.documents.SearchClient.searchGet":"Customizations.SearchClient.Documents.searchGet","com.azure.search.documents.SearchClient.searchGetWithResponse":"Customizations.SearchClient.Documents.searchGet","com.azure.search.documents.SearchClient.searchWithResponse":"Customizations.SearchClient.Documents.searchPost","com.azure.search.documents.SearchClient.suggest":"Customizations.SearchClient.Documents.suggestPost","com.azure.search.documents.SearchClient.suggestGet":"Customizations.SearchClient.Documents.suggestGet","com.azure.search.documents.SearchClient.suggestGetWithResponse":"Customizations.SearchClient.Documents.suggestGet","com.azure.search.documents.SearchClient.suggestWithResponse":"Customizations.SearchClient.Documents.suggestPost","com.azure.search.documents.SearchClientBuilder":"Customizations.SearchClient","com.azure.search.documents.implementation.models.AutocompletePostRequest":"Customizations.SearchClient.autocompletePost.Request.anonymous","com.azure.search.documents.implementation.models.SearchPostRequest":"Customizations.SearchClient.searchPost.Request.anonymous","com.azure.search.documents.implementation.models.SuggestPostRequest":"Customizations.SearchClient.suggestPost.Request.anonymous","com.azure.search.documents.indexes.SearchIndexAsyncClient":"Customizations.SearchIndexClient","com.azure.search.documents.indexes.SearchIndexAsyncClient.analyzeText":"Customizations.SearchIndexClient.Indexes.analyze","com.azure.search.documents.indexes.SearchIndexAsyncClient.analyzeTextWithResponse":"Customizations.SearchIndexClient.Indexes.analyze","com.azure.search.documents.indexes.SearchIndexAsyncClient.createAlias":"Customizations.SearchIndexClient.Aliases.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createAliasWithResponse":"Customizations.SearchIndexClient.Aliases.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndex":"Customizations.SearchIndexClient.Indexes.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse":"Customizations.SearchIndexClient.Indexes.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeSource":"Customizations.SearchIndexClient.Sources.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAlias":"Customizations.SearchIndexClient.Aliases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAliasWithResponse":"Customizations.SearchIndexClient.Aliases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndex":"Customizations.SearchIndexClient.Indexes.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse":"Customizations.SearchIndexClient.Indexes.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeSource":"Customizations.SearchIndexClient.Sources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.createOrUpdate","com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.create","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAlias":"Customizations.SearchIndexClient.Aliases.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAliasWithResponse":"Customizations.SearchIndexClient.Aliases.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndex":"Customizations.SearchIndexClient.Indexes.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse":"Customizations.SearchIndexClient.Indexes.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeSource":"Customizations.SearchIndexClient.Sources.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.delete","com.azure.search.documents.indexes.SearchIndexAsyncClient.getAlias":"Customizations.SearchIndexClient.Aliases.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getAliasWithResponse":"Customizations.SearchIndexClient.Aliases.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndex":"Customizations.SearchIndexClient.Indexes.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatistics":"Customizations.SearchIndexClient.Indexes.getStatistics","com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatisticsWithResponse":"Customizations.SearchIndexClient.Indexes.getStatistics","com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse":"Customizations.SearchIndexClient.Indexes.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSource":"Customizations.SearchIndexClient.Sources.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSourceStatus":"Customizations.SearchIndexClient.Sources.getStatus","com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSourceStatusWithResponse":"Customizations.SearchIndexClient.Sources.getStatus","com.azure.search.documents.indexes.SearchIndexAsyncClient.getKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatistics":"Customizations.SearchIndexClient.Root.getServiceStatistics","com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatisticsWithResponse":"Customizations.SearchIndexClient.Root.getServiceStatistics","com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.get","com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMaps":"Customizations.SearchIndexClient.SynonymMaps.list","com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapsWithResponse":"Customizations.SearchIndexClient.SynonymMaps.list","com.azure.search.documents.indexes.SearchIndexAsyncClient.listAliases":"Customizations.SearchIndexClient.Aliases.list","com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexStatsSummary":"Customizations.SearchIndexClient.Root.getIndexStatsSummary","com.azure.search.documents.indexes.SearchIndexAsyncClient.listIndexes":"Customizations.SearchIndexClient.Indexes.list","com.azure.search.documents.indexes.SearchIndexAsyncClient.listKnowledgeBases":"Customizations.SearchIndexClient.KnowledgeBases.list","com.azure.search.documents.indexes.SearchIndexAsyncClient.listKnowledgeSources":"Customizations.SearchIndexClient.Sources.list","com.azure.search.documents.indexes.SearchIndexClient":"Customizations.SearchIndexClient","com.azure.search.documents.indexes.SearchIndexClient.analyzeText":"Customizations.SearchIndexClient.Indexes.analyze","com.azure.search.documents.indexes.SearchIndexClient.analyzeTextWithResponse":"Customizations.SearchIndexClient.Indexes.analyze","com.azure.search.documents.indexes.SearchIndexClient.createAlias":"Customizations.SearchIndexClient.Aliases.create","com.azure.search.documents.indexes.SearchIndexClient.createAliasWithResponse":"Customizations.SearchIndexClient.Aliases.create","com.azure.search.documents.indexes.SearchIndexClient.createIndex":"Customizations.SearchIndexClient.Indexes.create","com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse":"Customizations.SearchIndexClient.Indexes.create","com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.create","com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.create","com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeSource":"Customizations.SearchIndexClient.Sources.create","com.azure.search.documents.indexes.SearchIndexClient.createKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.create","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAlias":"Customizations.SearchIndexClient.Aliases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAliasWithResponse":"Customizations.SearchIndexClient.Aliases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndex":"Customizations.SearchIndexClient.Indexes.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse":"Customizations.SearchIndexClient.Indexes.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeSource":"Customizations.SearchIndexClient.Sources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.createOrUpdate","com.azure.search.documents.indexes.SearchIndexClient.createSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.create","com.azure.search.documents.indexes.SearchIndexClient.createSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.create","com.azure.search.documents.indexes.SearchIndexClient.deleteAlias":"Customizations.SearchIndexClient.Aliases.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteAliasWithResponse":"Customizations.SearchIndexClient.Aliases.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteIndex":"Customizations.SearchIndexClient.Indexes.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse":"Customizations.SearchIndexClient.Indexes.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeSource":"Customizations.SearchIndexClient.Sources.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.delete","com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.delete","com.azure.search.documents.indexes.SearchIndexClient.getAlias":"Customizations.SearchIndexClient.Aliases.get","com.azure.search.documents.indexes.SearchIndexClient.getAliasWithResponse":"Customizations.SearchIndexClient.Aliases.get","com.azure.search.documents.indexes.SearchIndexClient.getIndex":"Customizations.SearchIndexClient.Indexes.get","com.azure.search.documents.indexes.SearchIndexClient.getIndexStatistics":"Customizations.SearchIndexClient.Indexes.getStatistics","com.azure.search.documents.indexes.SearchIndexClient.getIndexStatisticsWithResponse":"Customizations.SearchIndexClient.Indexes.getStatistics","com.azure.search.documents.indexes.SearchIndexClient.getIndexWithResponse":"Customizations.SearchIndexClient.Indexes.get","com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeBase":"Customizations.SearchIndexClient.KnowledgeBases.get","com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeBaseWithResponse":"Customizations.SearchIndexClient.KnowledgeBases.get","com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSource":"Customizations.SearchIndexClient.Sources.get","com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSourceStatus":"Customizations.SearchIndexClient.Sources.getStatus","com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSourceStatusWithResponse":"Customizations.SearchIndexClient.Sources.getStatus","com.azure.search.documents.indexes.SearchIndexClient.getKnowledgeSourceWithResponse":"Customizations.SearchIndexClient.Sources.get","com.azure.search.documents.indexes.SearchIndexClient.getServiceStatistics":"Customizations.SearchIndexClient.Root.getServiceStatistics","com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse":"Customizations.SearchIndexClient.Root.getServiceStatistics","com.azure.search.documents.indexes.SearchIndexClient.getSynonymMap":"Customizations.SearchIndexClient.SynonymMaps.get","com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapWithResponse":"Customizations.SearchIndexClient.SynonymMaps.get","com.azure.search.documents.indexes.SearchIndexClient.getSynonymMaps":"Customizations.SearchIndexClient.SynonymMaps.list","com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapsWithResponse":"Customizations.SearchIndexClient.SynonymMaps.list","com.azure.search.documents.indexes.SearchIndexClient.listAliases":"Customizations.SearchIndexClient.Aliases.list","com.azure.search.documents.indexes.SearchIndexClient.listIndexStatsSummary":"Customizations.SearchIndexClient.Root.getIndexStatsSummary","com.azure.search.documents.indexes.SearchIndexClient.listIndexes":"Customizations.SearchIndexClient.Indexes.list","com.azure.search.documents.indexes.SearchIndexClient.listKnowledgeBases":"Customizations.SearchIndexClient.KnowledgeBases.list","com.azure.search.documents.indexes.SearchIndexClient.listKnowledgeSources":"Customizations.SearchIndexClient.Sources.list","com.azure.search.documents.indexes.SearchIndexClientBuilder":"Customizations.SearchIndexClient","com.azure.search.documents.indexes.SearchIndexerAsyncClient":"Customizations.SearchIndexerClient","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.create","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.create","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexer":"Customizations.SearchIndexerClient.Indexers.create","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.create","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexer":"Customizations.SearchIndexerClient.Indexers.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillset":"Customizations.SearchIndexerClient.Skillsets.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillset":"Customizations.SearchIndexerClient.Skillsets.create","com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.create","com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.delete","com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.delete","com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexer":"Customizations.SearchIndexerClient.Indexers.delete","com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.delete","com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillset":"Customizations.SearchIndexerClient.Skillsets.delete","com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.delete","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.get","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.get","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnections":"Customizations.SearchIndexerClient.DataSources.list","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionsWithResponse":"Customizations.SearchIndexerClient.DataSources.list","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexer":"Customizations.SearchIndexerClient.Indexers.get","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatus":"Customizations.SearchIndexerClient.Indexers.getStatus","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse":"Customizations.SearchIndexerClient.Indexers.getStatus","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.get","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexers":"Customizations.SearchIndexerClient.Indexers.list","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexersWithResponse":"Customizations.SearchIndexerClient.Indexers.list","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillset":"Customizations.SearchIndexerClient.Skillsets.get","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.get","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsets":"Customizations.SearchIndexerClient.Skillsets.list","com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetsWithResponse":"Customizations.SearchIndexerClient.Skillsets.list","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocuments":"Customizations.SearchIndexerClient.Indexers.resetDocs","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocumentsWithResponse":"Customizations.SearchIndexerClient.Indexers.resetDocs","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexer":"Customizations.SearchIndexerClient.Indexers.reset","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.reset","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkills":"Customizations.SearchIndexerClient.Skillsets.resetSkills","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkillsWithResponse":"Customizations.SearchIndexerClient.Skillsets.resetSkills","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resync":"Customizations.SearchIndexerClient.Indexers.resync","com.azure.search.documents.indexes.SearchIndexerAsyncClient.resyncWithResponse":"Customizations.SearchIndexerClient.Indexers.resync","com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexer":"Customizations.SearchIndexerClient.Indexers.run","com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.run","com.azure.search.documents.indexes.SearchIndexerClient":"Customizations.SearchIndexerClient","com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.create","com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.create","com.azure.search.documents.indexes.SearchIndexerClient.createIndexer":"Customizations.SearchIndexerClient.Indexers.create","com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.create","com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexer":"Customizations.SearchIndexerClient.Indexers.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillset":"Customizations.SearchIndexerClient.Skillsets.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.createOrUpdate","com.azure.search.documents.indexes.SearchIndexerClient.createSkillset":"Customizations.SearchIndexerClient.Skillsets.create","com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.create","com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.delete","com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.delete","com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexer":"Customizations.SearchIndexerClient.Indexers.delete","com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.delete","com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillset":"Customizations.SearchIndexerClient.Skillsets.delete","com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.delete","com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnection":"Customizations.SearchIndexerClient.DataSources.get","com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionWithResponse":"Customizations.SearchIndexerClient.DataSources.get","com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnections":"Customizations.SearchIndexerClient.DataSources.list","com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionsWithResponse":"Customizations.SearchIndexerClient.DataSources.list","com.azure.search.documents.indexes.SearchIndexerClient.getIndexer":"Customizations.SearchIndexerClient.Indexers.get","com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatus":"Customizations.SearchIndexerClient.Indexers.getStatus","com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatusWithResponse":"Customizations.SearchIndexerClient.Indexers.getStatus","com.azure.search.documents.indexes.SearchIndexerClient.getIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.get","com.azure.search.documents.indexes.SearchIndexerClient.getIndexers":"Customizations.SearchIndexerClient.Indexers.list","com.azure.search.documents.indexes.SearchIndexerClient.getIndexersWithResponse":"Customizations.SearchIndexerClient.Indexers.list","com.azure.search.documents.indexes.SearchIndexerClient.getSkillset":"Customizations.SearchIndexerClient.Skillsets.get","com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetWithResponse":"Customizations.SearchIndexerClient.Skillsets.get","com.azure.search.documents.indexes.SearchIndexerClient.getSkillsets":"Customizations.SearchIndexerClient.Skillsets.list","com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetsWithResponse":"Customizations.SearchIndexerClient.Skillsets.list","com.azure.search.documents.indexes.SearchIndexerClient.resetDocuments":"Customizations.SearchIndexerClient.Indexers.resetDocs","com.azure.search.documents.indexes.SearchIndexerClient.resetDocumentsWithResponse":"Customizations.SearchIndexerClient.Indexers.resetDocs","com.azure.search.documents.indexes.SearchIndexerClient.resetIndexer":"Customizations.SearchIndexerClient.Indexers.reset","com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.reset","com.azure.search.documents.indexes.SearchIndexerClient.resetSkills":"Customizations.SearchIndexerClient.Skillsets.resetSkills","com.azure.search.documents.indexes.SearchIndexerClient.resetSkillsWithResponse":"Customizations.SearchIndexerClient.Skillsets.resetSkills","com.azure.search.documents.indexes.SearchIndexerClient.resync":"Customizations.SearchIndexerClient.Indexers.resync","com.azure.search.documents.indexes.SearchIndexerClient.resyncWithResponse":"Customizations.SearchIndexerClient.Indexers.resync","com.azure.search.documents.indexes.SearchIndexerClient.runIndexer":"Customizations.SearchIndexerClient.Indexers.run","com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse":"Customizations.SearchIndexerClient.Indexers.run","com.azure.search.documents.indexes.SearchIndexerClientBuilder":"Customizations.SearchIndexerClient","com.azure.search.documents.indexes.models.AIFoundryModelCatalogName":"Search.AIFoundryModelCatalogName","com.azure.search.documents.indexes.models.AIServicesAccountIdentity":"Search.AIServicesAccountIdentity","com.azure.search.documents.indexes.models.AIServicesAccountKey":"Search.AIServicesAccountKey","com.azure.search.documents.indexes.models.AIServicesVisionParameters":"Search.AIServicesVisionParameters","com.azure.search.documents.indexes.models.AIServicesVisionVectorizer":"Search.AIServicesVisionVectorizer","com.azure.search.documents.indexes.models.AnalyzeResult":"Search.AnalyzeResult","com.azure.search.documents.indexes.models.AnalyzeTextOptions":"Search.AnalyzeRequest","com.azure.search.documents.indexes.models.AnalyzedTokenInfo":"Search.AnalyzedTokenInfo","com.azure.search.documents.indexes.models.AsciiFoldingTokenFilter":"Search.AsciiFoldingTokenFilter","com.azure.search.documents.indexes.models.AzureActiveDirectoryApplicationCredentials":"Search.AzureActiveDirectoryApplicationCredentials","com.azure.search.documents.indexes.models.AzureBlobKnowledgeSource":"Search.AzureBlobKnowledgeSource","com.azure.search.documents.indexes.models.AzureBlobKnowledgeSourceParameters":"Search.AzureBlobKnowledgeSourceParameters","com.azure.search.documents.indexes.models.AzureMachineLearningParameters":"Search.AMLParameters","com.azure.search.documents.indexes.models.AzureMachineLearningSkill":"Search.AzureMachineLearningSkill","com.azure.search.documents.indexes.models.AzureMachineLearningVectorizer":"Search.AMLVectorizer","com.azure.search.documents.indexes.models.AzureOpenAIEmbeddingSkill":"Search.AzureOpenAIEmbeddingSkill","com.azure.search.documents.indexes.models.AzureOpenAIModelName":"Search.AzureOpenAIModelName","com.azure.search.documents.indexes.models.AzureOpenAITokenizerParameters":"Search.AzureOpenAITokenizerParameters","com.azure.search.documents.indexes.models.AzureOpenAIVectorizer":"Search.AzureOpenAIVectorizer","com.azure.search.documents.indexes.models.AzureOpenAIVectorizerParameters":"Search.AzureOpenAIVectorizerParameters","com.azure.search.documents.indexes.models.BM25SimilarityAlgorithm":"Search.BM25SimilarityAlgorithm","com.azure.search.documents.indexes.models.BinaryQuantizationCompression":"Search.BinaryQuantizationCompression","com.azure.search.documents.indexes.models.BlobIndexerDataToExtract":"Search.BlobIndexerDataToExtract","com.azure.search.documents.indexes.models.BlobIndexerImageAction":"Search.BlobIndexerImageAction","com.azure.search.documents.indexes.models.BlobIndexerPDFTextRotationAlgorithm":"Search.BlobIndexerPDFTextRotationAlgorithm","com.azure.search.documents.indexes.models.BlobIndexerParsingMode":"Search.BlobIndexerParsingMode","com.azure.search.documents.indexes.models.CharFilter":"Search.CharFilter","com.azure.search.documents.indexes.models.CharFilterName":"Search.CharFilterName","com.azure.search.documents.indexes.models.ChatCompletionCommonModelParameters":"Search.ChatCompletionCommonModelParameters","com.azure.search.documents.indexes.models.ChatCompletionExtraParametersBehavior":"Search.ChatCompletionExtraParametersBehavior","com.azure.search.documents.indexes.models.ChatCompletionResponseFormat":"Search.ChatCompletionResponseFormat","com.azure.search.documents.indexes.models.ChatCompletionResponseFormatType":"Search.ChatCompletionResponseFormatType","com.azure.search.documents.indexes.models.ChatCompletionSchema":"Search.ChatCompletionSchema","com.azure.search.documents.indexes.models.ChatCompletionSchemaProperties":"Search.ChatCompletionSchemaProperties","com.azure.search.documents.indexes.models.ChatCompletionSkill":"Search.ChatCompletionSkill","com.azure.search.documents.indexes.models.CjkBigramTokenFilter":"Search.CjkBigramTokenFilter","com.azure.search.documents.indexes.models.CjkBigramTokenFilterScripts":"Search.CjkBigramTokenFilterScripts","com.azure.search.documents.indexes.models.ClassicSimilarityAlgorithm":"Search.ClassicSimilarityAlgorithm","com.azure.search.documents.indexes.models.ClassicTokenizer":"Search.ClassicTokenizer","com.azure.search.documents.indexes.models.CognitiveServicesAccount":"Search.CognitiveServicesAccount","com.azure.search.documents.indexes.models.CognitiveServicesAccountKey":"Search.CognitiveServicesAccountKey","com.azure.search.documents.indexes.models.CommonGramTokenFilter":"Search.CommonGramTokenFilter","com.azure.search.documents.indexes.models.ConditionalSkill":"Search.ConditionalSkill","com.azure.search.documents.indexes.models.ContentUnderstandingSkill":"Search.ContentUnderstandingSkill","com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties":"Search.ContentUnderstandingSkillChunkingProperties","com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit":"Search.ContentUnderstandingSkillChunkingUnit","com.azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions":"Search.ContentUnderstandingSkillExtractionOptions","com.azure.search.documents.indexes.models.CorsOptions":"Search.CorsOptions","com.azure.search.documents.indexes.models.CreatedResources":"Search.CreatedResources","com.azure.search.documents.indexes.models.CustomAnalyzer":"Search.CustomAnalyzer","com.azure.search.documents.indexes.models.CustomEntity":"Search.CustomEntity","com.azure.search.documents.indexes.models.CustomEntityAlias":"Search.CustomEntityAlias","com.azure.search.documents.indexes.models.CustomEntityLookupSkill":"Search.CustomEntityLookupSkill","com.azure.search.documents.indexes.models.CustomEntityLookupSkillLanguage":"Search.CustomEntityLookupSkillLanguage","com.azure.search.documents.indexes.models.CustomNormalizer":"Search.CustomNormalizer","com.azure.search.documents.indexes.models.DataChangeDetectionPolicy":"Search.DataChangeDetectionPolicy","com.azure.search.documents.indexes.models.DataDeletionDetectionPolicy":"Search.DataDeletionDetectionPolicy","com.azure.search.documents.indexes.models.DataSourceCredentials":"Search.DataSourceCredentials","com.azure.search.documents.indexes.models.DefaultCognitiveServicesAccount":"Search.DefaultCognitiveServicesAccount","com.azure.search.documents.indexes.models.DictionaryDecompounderTokenFilter":"Search.DictionaryDecompounderTokenFilter","com.azure.search.documents.indexes.models.DistanceScoringFunction":"Search.DistanceScoringFunction","com.azure.search.documents.indexes.models.DistanceScoringParameters":"Search.DistanceScoringParameters","com.azure.search.documents.indexes.models.DocumentExtractionSkill":"Search.DocumentExtractionSkill","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkill":"Search.DocumentIntelligenceLayoutSkill","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingProperties":"Search.DocumentIntelligenceLayoutSkillChunkingProperties","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillChunkingUnit":"Search.DocumentIntelligenceLayoutSkillChunkingUnit","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillExtractionOptions":"Search.DocumentIntelligenceLayoutSkillExtractionOptions","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth":"Search.DocumentIntelligenceLayoutSkillMarkdownHeaderDepth","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputFormat":"Search.DocumentIntelligenceLayoutSkillOutputFormat","com.azure.search.documents.indexes.models.DocumentIntelligenceLayoutSkillOutputMode":"Search.DocumentIntelligenceLayoutSkillOutputMode","com.azure.search.documents.indexes.models.DocumentKeysOrIds":"Search.DocumentKeysOrIds","com.azure.search.documents.indexes.models.EdgeNGramTokenFilter":"Search.EdgeNGramTokenFilter","com.azure.search.documents.indexes.models.EdgeNGramTokenFilterSide":"Search.EdgeNGramTokenFilterSide","com.azure.search.documents.indexes.models.EdgeNGramTokenFilterV2":"Search.EdgeNGramTokenFilterV2","com.azure.search.documents.indexes.models.EdgeNGramTokenizer":"Search.EdgeNGramTokenizer","com.azure.search.documents.indexes.models.ElisionTokenFilter":"Search.ElisionTokenFilter","com.azure.search.documents.indexes.models.EntityLinkingSkill":"Search.EntityLinkingSkill","com.azure.search.documents.indexes.models.EntityRecognitionSkillV3":"Search.EntityRecognitionSkillV3","com.azure.search.documents.indexes.models.ExhaustiveKnnAlgorithmConfiguration":"Search.ExhaustiveKnnAlgorithmConfiguration","com.azure.search.documents.indexes.models.ExhaustiveKnnParameters":"Search.ExhaustiveKnnParameters","com.azure.search.documents.indexes.models.FieldMapping":"Search.FieldMapping","com.azure.search.documents.indexes.models.FieldMappingFunction":"Search.FieldMappingFunction","com.azure.search.documents.indexes.models.FreshnessScoringFunction":"Search.FreshnessScoringFunction","com.azure.search.documents.indexes.models.FreshnessScoringParameters":"Search.FreshnessScoringParameters","com.azure.search.documents.indexes.models.GetIndexStatisticsResult":"Search.GetIndexStatisticsResult","com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy":"Search.HighWaterMarkChangeDetectionPolicy","com.azure.search.documents.indexes.models.HnswAlgorithmConfiguration":"Search.HnswAlgorithmConfiguration","com.azure.search.documents.indexes.models.HnswParameters":"Search.HnswParameters","com.azure.search.documents.indexes.models.ImageAnalysisSkill":"Search.ImageAnalysisSkill","com.azure.search.documents.indexes.models.ImageAnalysisSkillLanguage":"Search.ImageAnalysisSkillLanguage","com.azure.search.documents.indexes.models.ImageDetail":"Search.ImageDetail","com.azure.search.documents.indexes.models.IndexProjectionMode":"Search.IndexProjectionMode","com.azure.search.documents.indexes.models.IndexStatisticsSummary":"Search.IndexStatisticsSummary","com.azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSource":"Search.IndexedOneLakeKnowledgeSource","com.azure.search.documents.indexes.models.IndexedOneLakeKnowledgeSourceParameters":"Search.IndexedOneLakeKnowledgeSourceParameters","com.azure.search.documents.indexes.models.IndexedSharePointContainerName":"Search.IndexedSharePointContainerName","com.azure.search.documents.indexes.models.IndexedSharePointKnowledgeSource":"Search.IndexedSharePointKnowledgeSource","com.azure.search.documents.indexes.models.IndexedSharePointKnowledgeSourceParameters":"Search.IndexedSharePointKnowledgeSourceParameters","com.azure.search.documents.indexes.models.IndexerCurrentState":"Search.IndexerCurrentState","com.azure.search.documents.indexes.models.IndexerExecutionEnvironment":"Search.IndexerExecutionEnvironment","com.azure.search.documents.indexes.models.IndexerExecutionResult":"Search.IndexerExecutionResult","com.azure.search.documents.indexes.models.IndexerExecutionStatus":"Search.IndexerExecutionStatus","com.azure.search.documents.indexes.models.IndexerExecutionStatusDetail":"Search.IndexerExecutionStatusDetail","com.azure.search.documents.indexes.models.IndexerPermissionOption":"Search.IndexerPermissionOption","com.azure.search.documents.indexes.models.IndexerResyncBody":"Search.IndexerResyncBody","com.azure.search.documents.indexes.models.IndexerResyncOption":"Search.IndexerResyncOption","com.azure.search.documents.indexes.models.IndexerRuntime":"Search.IndexerRuntime","com.azure.search.documents.indexes.models.IndexerStatus":"Search.IndexerStatus","com.azure.search.documents.indexes.models.IndexingMode":"Search.IndexingMode","com.azure.search.documents.indexes.models.IndexingParameters":"Search.IndexingParameters","com.azure.search.documents.indexes.models.IndexingParametersConfiguration":"Search.IndexingParametersConfiguration","com.azure.search.documents.indexes.models.IndexingSchedule":"Search.IndexingSchedule","com.azure.search.documents.indexes.models.InputFieldMappingEntry":"Search.InputFieldMappingEntry","com.azure.search.documents.indexes.models.KeepTokenFilter":"Search.KeepTokenFilter","com.azure.search.documents.indexes.models.KeyPhraseExtractionSkill":"Search.KeyPhraseExtractionSkill","com.azure.search.documents.indexes.models.KeyPhraseExtractionSkillLanguage":"Search.KeyPhraseExtractionSkillLanguage","com.azure.search.documents.indexes.models.KeywordMarkerTokenFilter":"Search.KeywordMarkerTokenFilter","com.azure.search.documents.indexes.models.KeywordTokenizer":"Search.KeywordTokenizer","com.azure.search.documents.indexes.models.KeywordTokenizerV2":"Search.KeywordTokenizerV2","com.azure.search.documents.indexes.models.KnowledgeBase":"Search.KnowledgeBase","com.azure.search.documents.indexes.models.KnowledgeBaseAzureOpenAIModel":"Search.KnowledgeBaseAzureOpenAIModel","com.azure.search.documents.indexes.models.KnowledgeBaseModel":"Search.KnowledgeBaseModel","com.azure.search.documents.indexes.models.KnowledgeBaseModelKind":"Search.KnowledgeBaseModelKind","com.azure.search.documents.indexes.models.KnowledgeSource":"Search.KnowledgeSource","com.azure.search.documents.indexes.models.KnowledgeSourceContentExtractionMode":"Search.KnowledgeSourceContentExtractionMode","com.azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption":"Search.KnowledgeSourceIngestionPermissionOption","com.azure.search.documents.indexes.models.KnowledgeSourceKind":"Search.KnowledgeSourceKind","com.azure.search.documents.indexes.models.KnowledgeSourceReference":"Search.KnowledgeSourceReference","com.azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus":"Search.KnowledgeSourceSynchronizationStatus","com.azure.search.documents.indexes.models.LanguageDetectionSkill":"Search.LanguageDetectionSkill","com.azure.search.documents.indexes.models.LengthTokenFilter":"Search.LengthTokenFilter","com.azure.search.documents.indexes.models.LexicalAnalyzer":"Search.LexicalAnalyzer","com.azure.search.documents.indexes.models.LexicalAnalyzerName":"Search.LexicalAnalyzerName","com.azure.search.documents.indexes.models.LexicalNormalizer":"Search.LexicalNormalizer","com.azure.search.documents.indexes.models.LexicalNormalizerName":"Search.LexicalNormalizerName","com.azure.search.documents.indexes.models.LexicalTokenizer":"Search.LexicalTokenizer","com.azure.search.documents.indexes.models.LexicalTokenizerName":"Search.LexicalTokenizerName","com.azure.search.documents.indexes.models.LimitTokenFilter":"Search.LimitTokenFilter","com.azure.search.documents.indexes.models.ListDataSourcesResult":"Search.ListDataSourcesResult","com.azure.search.documents.indexes.models.ListIndexersResult":"Search.ListIndexersResult","com.azure.search.documents.indexes.models.ListSkillsetsResult":"Search.ListSkillsetsResult","com.azure.search.documents.indexes.models.ListSynonymMapsResult":"Search.ListSynonymMapsResult","com.azure.search.documents.indexes.models.LuceneStandardAnalyzer":"Search.LuceneStandardAnalyzer","com.azure.search.documents.indexes.models.LuceneStandardTokenizer":"Search.LuceneStandardTokenizer","com.azure.search.documents.indexes.models.LuceneStandardTokenizerV2":"Search.LuceneStandardTokenizerV2","com.azure.search.documents.indexes.models.MagnitudeScoringFunction":"Search.MagnitudeScoringFunction","com.azure.search.documents.indexes.models.MagnitudeScoringParameters":"Search.MagnitudeScoringParameters","com.azure.search.documents.indexes.models.MappingCharFilter":"Search.MappingCharFilter","com.azure.search.documents.indexes.models.MarkdownHeaderDepth":"Search.MarkdownHeaderDepth","com.azure.search.documents.indexes.models.MarkdownParsingSubmode":"Search.MarkdownParsingSubmode","com.azure.search.documents.indexes.models.MergeSkill":"Search.MergeSkill","com.azure.search.documents.indexes.models.MicrosoftLanguageStemmingTokenizer":"Search.MicrosoftLanguageStemmingTokenizer","com.azure.search.documents.indexes.models.MicrosoftLanguageTokenizer":"Search.MicrosoftLanguageTokenizer","com.azure.search.documents.indexes.models.MicrosoftStemmingTokenizerLanguage":"Search.MicrosoftStemmingTokenizerLanguage","com.azure.search.documents.indexes.models.MicrosoftTokenizerLanguage":"Search.MicrosoftTokenizerLanguage","com.azure.search.documents.indexes.models.NGramTokenFilter":"Search.NGramTokenFilter","com.azure.search.documents.indexes.models.NGramTokenFilterV2":"Search.NGramTokenFilterV2","com.azure.search.documents.indexes.models.NGramTokenizer":"Search.NGramTokenizer","com.azure.search.documents.indexes.models.NativeBlobSoftDeleteDeletionDetectionPolicy":"Search.NativeBlobSoftDeleteDeletionDetectionPolicy","com.azure.search.documents.indexes.models.OcrLineEnding":"Search.OcrLineEnding","com.azure.search.documents.indexes.models.OcrSkill":"Search.OcrSkill","com.azure.search.documents.indexes.models.OcrSkillLanguage":"Search.OcrSkillLanguage","com.azure.search.documents.indexes.models.OutputFieldMappingEntry":"Search.OutputFieldMappingEntry","com.azure.search.documents.indexes.models.PIIDetectionSkill":"Search.PIIDetectionSkill","com.azure.search.documents.indexes.models.PIIDetectionSkillMaskingMode":"Search.PIIDetectionSkillMaskingMode","com.azure.search.documents.indexes.models.PathHierarchyTokenizerV2":"Search.PathHierarchyTokenizerV2","com.azure.search.documents.indexes.models.PatternAnalyzer":"Search.PatternAnalyzer","com.azure.search.documents.indexes.models.PatternCaptureTokenFilter":"Search.PatternCaptureTokenFilter","com.azure.search.documents.indexes.models.PatternReplaceCharFilter":"Search.PatternReplaceCharFilter","com.azure.search.documents.indexes.models.PatternReplaceTokenFilter":"Search.PatternReplaceTokenFilter","com.azure.search.documents.indexes.models.PatternTokenizer":"Search.PatternTokenizer","com.azure.search.documents.indexes.models.PermissionFilter":"Search.PermissionFilter","com.azure.search.documents.indexes.models.PhoneticEncoder":"Search.PhoneticEncoder","com.azure.search.documents.indexes.models.PhoneticTokenFilter":"Search.PhoneticTokenFilter","com.azure.search.documents.indexes.models.RankingOrder":"Search.RankingOrder","com.azure.search.documents.indexes.models.RegexFlags":"Search.RegexFlags","com.azure.search.documents.indexes.models.RemoteSharePointKnowledgeSource":"Search.RemoteSharePointKnowledgeSource","com.azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters":"Search.RemoteSharePointKnowledgeSourceParameters","com.azure.search.documents.indexes.models.RescoringOptions":"Search.RescoringOptions","com.azure.search.documents.indexes.models.ResourceCounter":"Search.ResourceCounter","com.azure.search.documents.indexes.models.ScalarQuantizationCompression":"Search.ScalarQuantizationCompression","com.azure.search.documents.indexes.models.ScalarQuantizationParameters":"Search.ScalarQuantizationParameters","com.azure.search.documents.indexes.models.ScoringFunction":"Search.ScoringFunction","com.azure.search.documents.indexes.models.ScoringFunctionAggregation":"Search.ScoringFunctionAggregation","com.azure.search.documents.indexes.models.ScoringFunctionInterpolation":"Search.ScoringFunctionInterpolation","com.azure.search.documents.indexes.models.ScoringProfile":"Search.ScoringProfile","com.azure.search.documents.indexes.models.SearchAlias":"Search.SearchAlias","com.azure.search.documents.indexes.models.SearchField":"Search.SearchField","com.azure.search.documents.indexes.models.SearchFieldDataType":"Search.SearchFieldDataType","com.azure.search.documents.indexes.models.SearchIndex":"Search.SearchIndex","com.azure.search.documents.indexes.models.SearchIndexFieldReference":"Search.SearchIndexFieldReference","com.azure.search.documents.indexes.models.SearchIndexKnowledgeSource":"Search.SearchIndexKnowledgeSource","com.azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters":"Search.SearchIndexKnowledgeSourceParameters","com.azure.search.documents.indexes.models.SearchIndexPermissionFilterOption":"Search.SearchIndexPermissionFilterOption","com.azure.search.documents.indexes.models.SearchIndexer":"Search.SearchIndexer","com.azure.search.documents.indexes.models.SearchIndexerCache":"Search.SearchIndexerCache","com.azure.search.documents.indexes.models.SearchIndexerDataContainer":"Search.SearchIndexerDataContainer","com.azure.search.documents.indexes.models.SearchIndexerDataIdentity":"Search.SearchIndexerDataIdentity","com.azure.search.documents.indexes.models.SearchIndexerDataNoneIdentity":"Search.SearchIndexerDataNoneIdentity","com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection":"Search.SearchIndexerDataSource","com.azure.search.documents.indexes.models.SearchIndexerDataSourceType":"Search.SearchIndexerDataSourceType","com.azure.search.documents.indexes.models.SearchIndexerDataUserAssignedIdentity":"Search.SearchIndexerDataUserAssignedIdentity","com.azure.search.documents.indexes.models.SearchIndexerError":"Search.SearchIndexerError","com.azure.search.documents.indexes.models.SearchIndexerIndexProjection":"Search.SearchIndexerIndexProjection","com.azure.search.documents.indexes.models.SearchIndexerIndexProjectionSelector":"Search.SearchIndexerIndexProjectionSelector","com.azure.search.documents.indexes.models.SearchIndexerIndexProjectionsParameters":"Search.SearchIndexerIndexProjectionsParameters","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStore":"Search.SearchIndexerKnowledgeStore","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreBlobProjectionSelector":"Search.SearchIndexerKnowledgeStoreBlobProjectionSelector","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreFileProjectionSelector":"Search.SearchIndexerKnowledgeStoreFileProjectionSelector","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreObjectProjectionSelector":"Search.SearchIndexerKnowledgeStoreObjectProjectionSelector","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreParameters":"Search.SearchIndexerKnowledgeStoreParameters","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjection":"Search.SearchIndexerKnowledgeStoreProjection","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreProjectionSelector":"Search.SearchIndexerKnowledgeStoreProjectionSelector","com.azure.search.documents.indexes.models.SearchIndexerKnowledgeStoreTableProjectionSelector":"Search.SearchIndexerKnowledgeStoreTableProjectionSelector","com.azure.search.documents.indexes.models.SearchIndexerLimits":"Search.SearchIndexerLimits","com.azure.search.documents.indexes.models.SearchIndexerSkill":"Search.SearchIndexerSkill","com.azure.search.documents.indexes.models.SearchIndexerSkillset":"Search.SearchIndexerSkillset","com.azure.search.documents.indexes.models.SearchIndexerStatus":"Search.SearchIndexerStatus","com.azure.search.documents.indexes.models.SearchIndexerWarning":"Search.SearchIndexerWarning","com.azure.search.documents.indexes.models.SearchResourceEncryptionKey":"Search.SearchResourceEncryptionKey","com.azure.search.documents.indexes.models.SearchServiceCounters":"Search.SearchServiceCounters","com.azure.search.documents.indexes.models.SearchServiceLimits":"Search.SearchServiceLimits","com.azure.search.documents.indexes.models.SearchServiceStatistics":"Search.SearchServiceStatistics","com.azure.search.documents.indexes.models.SearchSuggester":"Search.SearchSuggester","com.azure.search.documents.indexes.models.SemanticConfiguration":"Search.SemanticConfiguration","com.azure.search.documents.indexes.models.SemanticField":"Search.SemanticField","com.azure.search.documents.indexes.models.SemanticPrioritizedFields":"Search.SemanticPrioritizedFields","com.azure.search.documents.indexes.models.SemanticSearch":"Search.SemanticSearch","com.azure.search.documents.indexes.models.SentimentSkillV3":"Search.SentimentSkillV3","com.azure.search.documents.indexes.models.ServiceIndexersRuntime":"Search.ServiceIndexersRuntime","com.azure.search.documents.indexes.models.ShaperSkill":"Search.ShaperSkill","com.azure.search.documents.indexes.models.ShingleTokenFilter":"Search.ShingleTokenFilter","com.azure.search.documents.indexes.models.SimilarityAlgorithm":"Search.SimilarityAlgorithm","com.azure.search.documents.indexes.models.SkillNames":"Search.SkillNames","com.azure.search.documents.indexes.models.SnowballTokenFilter":"Search.SnowballTokenFilter","com.azure.search.documents.indexes.models.SnowballTokenFilterLanguage":"Search.SnowballTokenFilterLanguage","com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy":"Search.SoftDeleteColumnDeletionDetectionPolicy","com.azure.search.documents.indexes.models.SplitSkill":"Search.SplitSkill","com.azure.search.documents.indexes.models.SplitSkillEncoderModelName":"Search.SplitSkillEncoderModelName","com.azure.search.documents.indexes.models.SplitSkillLanguage":"Search.SplitSkillLanguage","com.azure.search.documents.indexes.models.SplitSkillUnit":"Search.SplitSkillUnit","com.azure.search.documents.indexes.models.SqlIntegratedChangeTrackingPolicy":"Search.SqlIntegratedChangeTrackingPolicy","com.azure.search.documents.indexes.models.StemmerOverrideTokenFilter":"Search.StemmerOverrideTokenFilter","com.azure.search.documents.indexes.models.StemmerTokenFilter":"Search.StemmerTokenFilter","com.azure.search.documents.indexes.models.StemmerTokenFilterLanguage":"Search.StemmerTokenFilterLanguage","com.azure.search.documents.indexes.models.StopAnalyzer":"Search.StopAnalyzer","com.azure.search.documents.indexes.models.StopwordsList":"Search.StopwordsList","com.azure.search.documents.indexes.models.StopwordsTokenFilter":"Search.StopwordsTokenFilter","com.azure.search.documents.indexes.models.SynonymMap":"Search.SynonymMap","com.azure.search.documents.indexes.models.SynonymTokenFilter":"Search.SynonymTokenFilter","com.azure.search.documents.indexes.models.TagScoringFunction":"Search.TagScoringFunction","com.azure.search.documents.indexes.models.TagScoringParameters":"Search.TagScoringParameters","com.azure.search.documents.indexes.models.TextSplitMode":"Search.TextSplitMode","com.azure.search.documents.indexes.models.TextTranslationSkill":"Search.TextTranslationSkill","com.azure.search.documents.indexes.models.TextTranslationSkillLanguage":"Search.TextTranslationSkillLanguage","com.azure.search.documents.indexes.models.TextWeights":"Search.TextWeights","com.azure.search.documents.indexes.models.TokenCharacterKind":"Search.TokenCharacterKind","com.azure.search.documents.indexes.models.TokenFilter":"Search.TokenFilter","com.azure.search.documents.indexes.models.TokenFilterName":"Search.TokenFilterName","com.azure.search.documents.indexes.models.TruncateTokenFilter":"Search.TruncateTokenFilter","com.azure.search.documents.indexes.models.UaxUrlEmailTokenizer":"Search.UaxUrlEmailTokenizer","com.azure.search.documents.indexes.models.UniqueTokenFilter":"Search.UniqueTokenFilter","com.azure.search.documents.indexes.models.VectorEncodingFormat":"Search.VectorEncodingFormat","com.azure.search.documents.indexes.models.VectorSearch":"Search.VectorSearch","com.azure.search.documents.indexes.models.VectorSearchAlgorithmConfiguration":"Search.VectorSearchAlgorithmConfiguration","com.azure.search.documents.indexes.models.VectorSearchAlgorithmKind":"Search.VectorSearchAlgorithmKind","com.azure.search.documents.indexes.models.VectorSearchAlgorithmMetric":"Search.VectorSearchAlgorithmMetric","com.azure.search.documents.indexes.models.VectorSearchCompression":"Search.VectorSearchCompression","com.azure.search.documents.indexes.models.VectorSearchCompressionKind":"Search.VectorSearchCompressionKind","com.azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod":"Search.VectorSearchCompressionRescoreStorageMethod","com.azure.search.documents.indexes.models.VectorSearchCompressionTarget":"Search.VectorSearchCompressionTarget","com.azure.search.documents.indexes.models.VectorSearchProfile":"Search.VectorSearchProfile","com.azure.search.documents.indexes.models.VectorSearchVectorizer":"Search.VectorSearchVectorizer","com.azure.search.documents.indexes.models.VectorSearchVectorizerKind":"Search.VectorSearchVectorizerKind","com.azure.search.documents.indexes.models.VisionVectorizeSkill":"Search.VisionVectorizeSkill","com.azure.search.documents.indexes.models.VisualFeature":"Search.VisualFeature","com.azure.search.documents.indexes.models.WebApiHttpHeaders":"Search.WebApiHttpHeaders","com.azure.search.documents.indexes.models.WebApiSkill":"Search.WebApiSkill","com.azure.search.documents.indexes.models.WebApiVectorizer":"Search.WebApiVectorizer","com.azure.search.documents.indexes.models.WebApiVectorizerParameters":"Search.WebApiVectorizerParameters","com.azure.search.documents.indexes.models.WebKnowledgeSource":"Search.WebKnowledgeSource","com.azure.search.documents.indexes.models.WebKnowledgeSourceDomain":"Search.WebKnowledgeSourceDomain","com.azure.search.documents.indexes.models.WebKnowledgeSourceDomains":"Search.WebKnowledgeSourceDomains","com.azure.search.documents.indexes.models.WebKnowledgeSourceParameters":"Search.WebKnowledgeSourceParameters","com.azure.search.documents.indexes.models.WordDelimiterTokenFilter":"Search.WordDelimiterTokenFilter","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalAsyncClient":"Customizations.KnowledgeBaseRetrievalClient","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalAsyncClient.retrieve":"Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalAsyncClient.retrieveWithResponse":"Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient":"Customizations.KnowledgeBaseRetrievalClient","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient.retrieve":"Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient.retrieveWithResponse":"Customizations.KnowledgeBaseRetrievalClient.KnowledgeRetrieval.retrieve","com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClientBuilder":"Customizations.KnowledgeBaseRetrievalClient","com.azure.search.documents.knowledgebases.models.AIServices":"Search.AIServices","com.azure.search.documents.knowledgebases.models.AzureBlobKnowledgeSourceParams":"Search.AzureBlobKnowledgeSourceParams","com.azure.search.documents.knowledgebases.models.CompletedSynchronizationState":"Search.CompletedSynchronizationState","com.azure.search.documents.knowledgebases.models.IndexedOneLakeKnowledgeSourceParams":"Search.IndexedOneLakeKnowledgeSourceParams","com.azure.search.documents.knowledgebases.models.IndexedSharePointKnowledgeSourceParams":"Search.IndexedSharePointKnowledgeSourceParams","com.azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecord":"Search.KnowledgeBaseActivityRecord","com.azure.search.documents.knowledgebases.models.KnowledgeBaseActivityRecordType":"Search.KnowledgeBaseActivityRecordType","com.azure.search.documents.knowledgebases.models.KnowledgeBaseAgenticReasoningActivityRecord":"Search.KnowledgeBaseAgenticReasoningActivityRecord","com.azure.search.documents.knowledgebases.models.KnowledgeBaseAzureBlobReference":"Search.KnowledgeBaseAzureBlobReference","com.azure.search.documents.knowledgebases.models.KnowledgeBaseErrorAdditionalInfo":"Search.KnowledgeBaseErrorAdditionalInfo","com.azure.search.documents.knowledgebases.models.KnowledgeBaseErrorDetail":"Search.KnowledgeBaseErrorDetail","com.azure.search.documents.knowledgebases.models.KnowledgeBaseImageContent":"Search.KnowledgeBaseImageContent","com.azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedOneLakeReference":"Search.KnowledgeBaseIndexedOneLakeReference","com.azure.search.documents.knowledgebases.models.KnowledgeBaseIndexedSharePointReference":"Search.KnowledgeBaseIndexedSharePointReference","com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessage":"Search.KnowledgeBaseMessage","com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContent":"Search.KnowledgeBaseMessageContent","com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageContentType":"Search.KnowledgeBaseMessageContentType","com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageImageContent":"Search.KnowledgeBaseMessageImageContent","com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageTextContent":"Search.KnowledgeBaseMessageTextContent","com.azure.search.documents.knowledgebases.models.KnowledgeBaseModelAnswerSynthesisActivityRecord":"Search.KnowledgeBaseModelAnswerSynthesisActivityRecord","com.azure.search.documents.knowledgebases.models.KnowledgeBaseModelQueryPlanningActivityRecord":"Search.KnowledgeBaseModelQueryPlanningActivityRecord","com.azure.search.documents.knowledgebases.models.KnowledgeBaseReference":"Search.KnowledgeBaseReference","com.azure.search.documents.knowledgebases.models.KnowledgeBaseReferenceType":"Search.KnowledgeBaseReferenceType","com.azure.search.documents.knowledgebases.models.KnowledgeBaseRemoteSharePointReference":"Search.KnowledgeBaseRemoteSharePointReference","com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest":"Search.KnowledgeBaseRetrievalRequest","com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse":"Search.KnowledgeBaseRetrievalResponse","com.azure.search.documents.knowledgebases.models.KnowledgeBaseSearchIndexReference":"Search.KnowledgeBaseSearchIndexReference","com.azure.search.documents.knowledgebases.models.KnowledgeBaseWebReference":"Search.KnowledgeBaseWebReference","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntent":"Search.KnowledgeRetrievalIntent","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalIntentType":"Search.KnowledgeRetrievalIntentType","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalLowReasoningEffort":"Search.KnowledgeRetrievalLowReasoningEffort","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalMediumReasoningEffort":"Search.KnowledgeRetrievalMediumReasoningEffort","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalMinimalReasoningEffort":"Search.KnowledgeRetrievalMinimalReasoningEffort","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalOutputMode":"Search.KnowledgeRetrievalOutputMode","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffort":"Search.KnowledgeRetrievalReasoningEffort","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalReasoningEffortKind":"Search.KnowledgeRetrievalReasoningEffortKind","com.azure.search.documents.knowledgebases.models.KnowledgeRetrievalSemanticIntent":"Search.KnowledgeRetrievalSemanticIntent","com.azure.search.documents.knowledgebases.models.KnowledgeSourceAzureOpenAIVectorizer":"Search.KnowledgeSourceAzureOpenAIVectorizer","com.azure.search.documents.knowledgebases.models.KnowledgeSourceIngestionParameters":"Search.KnowledgeSourceIngestionParameters","com.azure.search.documents.knowledgebases.models.KnowledgeSourceParams":"Search.KnowledgeSourceParams","com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatistics":"Search.KnowledgeSourceStatistics","com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatus":"Search.KnowledgeSourceStatus","com.azure.search.documents.knowledgebases.models.KnowledgeSourceVectorizer":"Search.KnowledgeSourceVectorizer","com.azure.search.documents.knowledgebases.models.RemoteSharePointKnowledgeSourceParams":"Search.RemoteSharePointKnowledgeSourceParams","com.azure.search.documents.knowledgebases.models.SearchIndexKnowledgeSourceParams":"Search.SearchIndexKnowledgeSourceParams","com.azure.search.documents.knowledgebases.models.SharePointSensitivityLabelInfo":"Search.SharePointSensitivityLabelInfo","com.azure.search.documents.knowledgebases.models.SynchronizationState":"Search.SynchronizationState","com.azure.search.documents.knowledgebases.models.WebKnowledgeSourceParams":"Search.WebKnowledgeSourceParams","com.azure.search.documents.models.AutocompleteItem":"Search.AutocompleteItem","com.azure.search.documents.models.AutocompleteMode":"Search.AutocompleteMode","com.azure.search.documents.models.AutocompleteOptions":null,"com.azure.search.documents.models.AutocompleteResult":"Search.AutocompleteResult","com.azure.search.documents.models.DebugInfo":"Search.DebugInfo","com.azure.search.documents.models.DocumentDebugInfo":"Search.DocumentDebugInfo","com.azure.search.documents.models.FacetResult":"Search.FacetResult","com.azure.search.documents.models.HybridCountAndFacetMode":"Search.HybridCountAndFacetMode","com.azure.search.documents.models.HybridSearch":"Search.HybridSearch","com.azure.search.documents.models.IndexAction":"Search.IndexAction","com.azure.search.documents.models.IndexActionType":"Search.IndexActionType","com.azure.search.documents.models.IndexDocumentsBatch":"Search.IndexBatch","com.azure.search.documents.models.IndexDocumentsResult":"Search.IndexDocumentsResult","com.azure.search.documents.models.IndexingResult":"Search.IndexingResult","com.azure.search.documents.models.LookupDocument":"Search.LookupDocument","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.QueryResultDocumentInnerHit":"Search.QueryResultDocumentInnerHit","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.ScoringStatistics":"Search.ScoringStatistics","com.azure.search.documents.models.SearchDocumentsResult":"Search.SearchDocumentsResult","com.azure.search.documents.models.SearchMode":"Search.SearchMode","com.azure.search.documents.models.SearchOptions":null,"com.azure.search.documents.models.SearchRequest":"Search.SearchRequest","com.azure.search.documents.models.SearchResult":"Search.SearchResult","com.azure.search.documents.models.SearchScoreThreshold":"Search.SearchScoreThreshold","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.SemanticFieldState":"Search.SemanticFieldState","com.azure.search.documents.models.SemanticQueryRewritesResultType":"Search.SemanticQueryRewritesResultType","com.azure.search.documents.models.SemanticSearchResultsType":"Search.SemanticSearchResultsType","com.azure.search.documents.models.SingleVectorFieldResult":"Search.SingleVectorFieldResult","com.azure.search.documents.models.SuggestDocumentsResult":"Search.SuggestDocumentsResult","com.azure.search.documents.models.SuggestOptions":null,"com.azure.search.documents.models.SuggestResult":"Search.SuggestResult","com.azure.search.documents.models.TextResult":"Search.TextResult","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.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"},"generatedFiles":["src/main/java/com/azure/search/documents/SearchAsyncClient.java","src/main/java/com/azure/search/documents/SearchClient.java","src/main/java/com/azure/search/documents/SearchClientBuilder.java","src/main/java/com/azure/search/documents/SearchServiceVersion.java","src/main/java/com/azure/search/documents/SearchServiceVersion.java","src/main/java/com/azure/search/documents/SearchServiceVersion.java","src/main/java/com/azure/search/documents/SearchServiceVersion.java","src/main/java/com/azure/search/documents/implementation/KnowledgeBaseRetrievalClientImpl.java","src/main/java/com/azure/search/documents/implementation/SearchClientImpl.java","src/main/java/com/azure/search/documents/implementation/SearchIndexClientImpl.java","src/main/java/com/azure/search/documents/implementation/SearchIndexerClientImpl.java","src/main/java/com/azure/search/documents/implementation/models/AutocompletePostRequest.java","src/main/java/com/azure/search/documents/implementation/models/SearchPostRequest.java","src/main/java/com/azure/search/documents/implementation/models/SuggestPostRequest.java","src/main/java/com/azure/search/documents/implementation/models/package-info.java","src/main/java/com/azure/search/documents/implementation/package-info.java","src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java","src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java","src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java","src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java","src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java","src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java","src/main/java/com/azure/search/documents/indexes/models/AIFoundryModelCatalogName.java","src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountIdentity.java","src/main/java/com/azure/search/documents/indexes/models/AIServicesAccountKey.java","src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionParameters.java","src/main/java/com/azure/search/documents/indexes/models/AIServicesVisionVectorizer.java","src/main/java/com/azure/search/documents/indexes/models/AnalyzeResult.java","src/main/java/com/azure/search/documents/indexes/models/AnalyzeTextOptions.java","src/main/java/com/azure/search/documents/indexes/models/AnalyzedTokenInfo.java","src/main/java/com/azure/search/documents/indexes/models/AsciiFoldingTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/AzureActiveDirectoryApplicationCredentials.java","src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/AzureBlobKnowledgeSourceParameters.java","src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningParameters.java","src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningSkill.java","src/main/java/com/azure/search/documents/indexes/models/AzureMachineLearningVectorizer.java","src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIEmbeddingSkill.java","src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIModelName.java","src/main/java/com/azure/search/documents/indexes/models/AzureOpenAITokenizerParameters.java","src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizer.java","src/main/java/com/azure/search/documents/indexes/models/AzureOpenAIVectorizerParameters.java","src/main/java/com/azure/search/documents/indexes/models/BM25SimilarityAlgorithm.java","src/main/java/com/azure/search/documents/indexes/models/BinaryQuantizationCompression.java","src/main/java/com/azure/search/documents/indexes/models/BlobIndexerDataToExtract.java","src/main/java/com/azure/search/documents/indexes/models/BlobIndexerImageAction.java","src/main/java/com/azure/search/documents/indexes/models/BlobIndexerPDFTextRotationAlgorithm.java","src/main/java/com/azure/search/documents/indexes/models/BlobIndexerParsingMode.java","src/main/java/com/azure/search/documents/indexes/models/CharFilter.java","src/main/java/com/azure/search/documents/indexes/models/CharFilterName.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionCommonModelParameters.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionExtraParametersBehavior.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormat.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionResponseFormatType.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchema.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSchemaProperties.java","src/main/java/com/azure/search/documents/indexes/models/ChatCompletionSkill.java","src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/CjkBigramTokenFilterScripts.java","src/main/java/com/azure/search/documents/indexes/models/ClassicSimilarityAlgorithm.java","src/main/java/com/azure/search/documents/indexes/models/ClassicTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccount.java","src/main/java/com/azure/search/documents/indexes/models/CognitiveServicesAccountKey.java","src/main/java/com/azure/search/documents/indexes/models/CommonGramTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/ConditionalSkill.java","src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkill.java","src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingProperties.java","src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillChunkingUnit.java","src/main/java/com/azure/search/documents/indexes/models/ContentUnderstandingSkillExtractionOptions.java","src/main/java/com/azure/search/documents/indexes/models/CorsOptions.java","src/main/java/com/azure/search/documents/indexes/models/CreatedResources.java","src/main/java/com/azure/search/documents/indexes/models/CustomAnalyzer.java","src/main/java/com/azure/search/documents/indexes/models/CustomEntity.java","src/main/java/com/azure/search/documents/indexes/models/CustomEntityAlias.java","src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkill.java","src/main/java/com/azure/search/documents/indexes/models/CustomEntityLookupSkillLanguage.java","src/main/java/com/azure/search/documents/indexes/models/CustomNormalizer.java","src/main/java/com/azure/search/documents/indexes/models/DataChangeDetectionPolicy.java","src/main/java/com/azure/search/documents/indexes/models/DataDeletionDetectionPolicy.java","src/main/java/com/azure/search/documents/indexes/models/DataSourceCredentials.java","src/main/java/com/azure/search/documents/indexes/models/DefaultCognitiveServicesAccount.java","src/main/java/com/azure/search/documents/indexes/models/DictionaryDecompounderTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/DistanceScoringFunction.java","src/main/java/com/azure/search/documents/indexes/models/DistanceScoringParameters.java","src/main/java/com/azure/search/documents/indexes/models/DocumentExtractionSkill.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkill.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingProperties.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillChunkingUnit.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillExtractionOptions.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillMarkdownHeaderDepth.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputFormat.java","src/main/java/com/azure/search/documents/indexes/models/DocumentIntelligenceLayoutSkillOutputMode.java","src/main/java/com/azure/search/documents/indexes/models/DocumentKeysOrIds.java","src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilterSide.java","src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenFilterV2.java","src/main/java/com/azure/search/documents/indexes/models/EdgeNGramTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/ElisionTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/EntityLinkingSkill.java","src/main/java/com/azure/search/documents/indexes/models/EntityRecognitionSkillV3.java","src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnAlgorithmConfiguration.java","src/main/java/com/azure/search/documents/indexes/models/ExhaustiveKnnParameters.java","src/main/java/com/azure/search/documents/indexes/models/FieldMapping.java","src/main/java/com/azure/search/documents/indexes/models/FieldMappingFunction.java","src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringFunction.java","src/main/java/com/azure/search/documents/indexes/models/FreshnessScoringParameters.java","src/main/java/com/azure/search/documents/indexes/models/GetIndexStatisticsResult.java","src/main/java/com/azure/search/documents/indexes/models/HighWaterMarkChangeDetectionPolicy.java","src/main/java/com/azure/search/documents/indexes/models/HnswAlgorithmConfiguration.java","src/main/java/com/azure/search/documents/indexes/models/HnswParameters.java","src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkill.java","src/main/java/com/azure/search/documents/indexes/models/ImageAnalysisSkillLanguage.java","src/main/java/com/azure/search/documents/indexes/models/ImageDetail.java","src/main/java/com/azure/search/documents/indexes/models/IndexProjectionMode.java","src/main/java/com/azure/search/documents/indexes/models/IndexStatisticsSummary.java","src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/IndexedOneLakeKnowledgeSourceParameters.java","src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointContainerName.java","src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointKnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/IndexedSharePointKnowledgeSourceParameters.java","src/main/java/com/azure/search/documents/indexes/models/IndexerCurrentState.java","src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionEnvironment.java","src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionResult.java","src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatus.java","src/main/java/com/azure/search/documents/indexes/models/IndexerExecutionStatusDetail.java","src/main/java/com/azure/search/documents/indexes/models/IndexerPermissionOption.java","src/main/java/com/azure/search/documents/indexes/models/IndexerResyncBody.java","src/main/java/com/azure/search/documents/indexes/models/IndexerResyncOption.java","src/main/java/com/azure/search/documents/indexes/models/IndexerRuntime.java","src/main/java/com/azure/search/documents/indexes/models/IndexerStatus.java","src/main/java/com/azure/search/documents/indexes/models/IndexingMode.java","src/main/java/com/azure/search/documents/indexes/models/IndexingParameters.java","src/main/java/com/azure/search/documents/indexes/models/IndexingParametersConfiguration.java","src/main/java/com/azure/search/documents/indexes/models/IndexingSchedule.java","src/main/java/com/azure/search/documents/indexes/models/InputFieldMappingEntry.java","src/main/java/com/azure/search/documents/indexes/models/KeepTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkill.java","src/main/java/com/azure/search/documents/indexes/models/KeyPhraseExtractionSkillLanguage.java","src/main/java/com/azure/search/documents/indexes/models/KeywordMarkerTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/KeywordTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/KeywordTokenizerV2.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeBase.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseAzureOpenAIModel.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModel.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeBaseModelKind.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceContentExtractionMode.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceIngestionPermissionOption.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceKind.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceReference.java","src/main/java/com/azure/search/documents/indexes/models/KnowledgeSourceSynchronizationStatus.java","src/main/java/com/azure/search/documents/indexes/models/LanguageDetectionSkill.java","src/main/java/com/azure/search/documents/indexes/models/LengthTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzer.java","src/main/java/com/azure/search/documents/indexes/models/LexicalAnalyzerName.java","src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizer.java","src/main/java/com/azure/search/documents/indexes/models/LexicalNormalizerName.java","src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/LexicalTokenizerName.java","src/main/java/com/azure/search/documents/indexes/models/LimitTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/ListDataSourcesResult.java","src/main/java/com/azure/search/documents/indexes/models/ListIndexersResult.java","src/main/java/com/azure/search/documents/indexes/models/ListSkillsetsResult.java","src/main/java/com/azure/search/documents/indexes/models/ListSynonymMapsResult.java","src/main/java/com/azure/search/documents/indexes/models/LuceneStandardAnalyzer.java","src/main/java/com/azure/search/documents/indexes/models/LuceneStandardTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/LuceneStandardTokenizerV2.java","src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringFunction.java","src/main/java/com/azure/search/documents/indexes/models/MagnitudeScoringParameters.java","src/main/java/com/azure/search/documents/indexes/models/MappingCharFilter.java","src/main/java/com/azure/search/documents/indexes/models/MarkdownHeaderDepth.java","src/main/java/com/azure/search/documents/indexes/models/MarkdownParsingSubmode.java","src/main/java/com/azure/search/documents/indexes/models/MergeSkill.java","src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageStemmingTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/MicrosoftLanguageTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/MicrosoftStemmingTokenizerLanguage.java","src/main/java/com/azure/search/documents/indexes/models/MicrosoftTokenizerLanguage.java","src/main/java/com/azure/search/documents/indexes/models/NGramTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/NGramTokenFilterV2.java","src/main/java/com/azure/search/documents/indexes/models/NGramTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/NativeBlobSoftDeleteDeletionDetectionPolicy.java","src/main/java/com/azure/search/documents/indexes/models/OcrLineEnding.java","src/main/java/com/azure/search/documents/indexes/models/OcrSkill.java","src/main/java/com/azure/search/documents/indexes/models/OcrSkillLanguage.java","src/main/java/com/azure/search/documents/indexes/models/OutputFieldMappingEntry.java","src/main/java/com/azure/search/documents/indexes/models/PIIDetectionSkill.java","src/main/java/com/azure/search/documents/indexes/models/PIIDetectionSkillMaskingMode.java","src/main/java/com/azure/search/documents/indexes/models/PathHierarchyTokenizerV2.java","src/main/java/com/azure/search/documents/indexes/models/PatternAnalyzer.java","src/main/java/com/azure/search/documents/indexes/models/PatternCaptureTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/PatternReplaceCharFilter.java","src/main/java/com/azure/search/documents/indexes/models/PatternReplaceTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/PatternTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/PermissionFilter.java","src/main/java/com/azure/search/documents/indexes/models/PhoneticEncoder.java","src/main/java/com/azure/search/documents/indexes/models/PhoneticTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/RankingOrder.java","src/main/java/com/azure/search/documents/indexes/models/RegexFlags.java","src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/RemoteSharePointKnowledgeSourceParameters.java","src/main/java/com/azure/search/documents/indexes/models/RescoringOptions.java","src/main/java/com/azure/search/documents/indexes/models/ResourceCounter.java","src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationCompression.java","src/main/java/com/azure/search/documents/indexes/models/ScalarQuantizationParameters.java","src/main/java/com/azure/search/documents/indexes/models/ScoringFunction.java","src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionAggregation.java","src/main/java/com/azure/search/documents/indexes/models/ScoringFunctionInterpolation.java","src/main/java/com/azure/search/documents/indexes/models/ScoringProfile.java","src/main/java/com/azure/search/documents/indexes/models/SearchAlias.java","src/main/java/com/azure/search/documents/indexes/models/SearchField.java","src/main/java/com/azure/search/documents/indexes/models/SearchFieldDataType.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndex.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexFieldReference.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexKnowledgeSourceParameters.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexPermissionFilterOption.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexer.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerCache.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataContainer.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataIdentity.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataNoneIdentity.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceConnection.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataSourceType.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerDataUserAssignedIdentity.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerError.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjection.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionSelector.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerIndexProjectionsParameters.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStore.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreBlobProjectionSelector.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreFileProjectionSelector.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreObjectProjectionSelector.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreParameters.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjection.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreProjectionSelector.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerKnowledgeStoreTableProjectionSelector.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerLimits.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkill.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerSkillset.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerStatus.java","src/main/java/com/azure/search/documents/indexes/models/SearchIndexerWarning.java","src/main/java/com/azure/search/documents/indexes/models/SearchResourceEncryptionKey.java","src/main/java/com/azure/search/documents/indexes/models/SearchServiceCounters.java","src/main/java/com/azure/search/documents/indexes/models/SearchServiceLimits.java","src/main/java/com/azure/search/documents/indexes/models/SearchServiceStatistics.java","src/main/java/com/azure/search/documents/indexes/models/SearchSuggester.java","src/main/java/com/azure/search/documents/indexes/models/SemanticConfiguration.java","src/main/java/com/azure/search/documents/indexes/models/SemanticField.java","src/main/java/com/azure/search/documents/indexes/models/SemanticPrioritizedFields.java","src/main/java/com/azure/search/documents/indexes/models/SemanticSearch.java","src/main/java/com/azure/search/documents/indexes/models/SentimentSkillV3.java","src/main/java/com/azure/search/documents/indexes/models/ServiceIndexersRuntime.java","src/main/java/com/azure/search/documents/indexes/models/ShaperSkill.java","src/main/java/com/azure/search/documents/indexes/models/ShingleTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/SimilarityAlgorithm.java","src/main/java/com/azure/search/documents/indexes/models/SkillNames.java","src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/SnowballTokenFilterLanguage.java","src/main/java/com/azure/search/documents/indexes/models/SoftDeleteColumnDeletionDetectionPolicy.java","src/main/java/com/azure/search/documents/indexes/models/SplitSkill.java","src/main/java/com/azure/search/documents/indexes/models/SplitSkillEncoderModelName.java","src/main/java/com/azure/search/documents/indexes/models/SplitSkillLanguage.java","src/main/java/com/azure/search/documents/indexes/models/SplitSkillUnit.java","src/main/java/com/azure/search/documents/indexes/models/SqlIntegratedChangeTrackingPolicy.java","src/main/java/com/azure/search/documents/indexes/models/StemmerOverrideTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/StemmerTokenFilterLanguage.java","src/main/java/com/azure/search/documents/indexes/models/StopAnalyzer.java","src/main/java/com/azure/search/documents/indexes/models/StopwordsList.java","src/main/java/com/azure/search/documents/indexes/models/StopwordsTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/SynonymMap.java","src/main/java/com/azure/search/documents/indexes/models/SynonymTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/TagScoringFunction.java","src/main/java/com/azure/search/documents/indexes/models/TagScoringParameters.java","src/main/java/com/azure/search/documents/indexes/models/TextSplitMode.java","src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkill.java","src/main/java/com/azure/search/documents/indexes/models/TextTranslationSkillLanguage.java","src/main/java/com/azure/search/documents/indexes/models/TextWeights.java","src/main/java/com/azure/search/documents/indexes/models/TokenCharacterKind.java","src/main/java/com/azure/search/documents/indexes/models/TokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/TokenFilterName.java","src/main/java/com/azure/search/documents/indexes/models/TruncateTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/UaxUrlEmailTokenizer.java","src/main/java/com/azure/search/documents/indexes/models/UniqueTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/VectorEncodingFormat.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearch.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmConfiguration.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmKind.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchAlgorithmMetric.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompression.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionKind.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionRescoreStorageMethod.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchCompressionTarget.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchProfile.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizer.java","src/main/java/com/azure/search/documents/indexes/models/VectorSearchVectorizerKind.java","src/main/java/com/azure/search/documents/indexes/models/VisionVectorizeSkill.java","src/main/java/com/azure/search/documents/indexes/models/VisualFeature.java","src/main/java/com/azure/search/documents/indexes/models/WebApiHttpHeaders.java","src/main/java/com/azure/search/documents/indexes/models/WebApiSkill.java","src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizer.java","src/main/java/com/azure/search/documents/indexes/models/WebApiVectorizerParameters.java","src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSource.java","src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomain.java","src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceDomains.java","src/main/java/com/azure/search/documents/indexes/models/WebKnowledgeSourceParameters.java","src/main/java/com/azure/search/documents/indexes/models/WordDelimiterTokenFilter.java","src/main/java/com/azure/search/documents/indexes/models/package-info.java","src/main/java/com/azure/search/documents/indexes/package-info.java","src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalAsyncClient.java","src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClient.java","src/main/java/com/azure/search/documents/knowledgebases/KnowledgeBaseRetrievalClientBuilder.java","src/main/java/com/azure/search/documents/knowledgebases/models/AIServices.java","src/main/java/com/azure/search/documents/knowledgebases/models/AzureBlobKnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/CompletedSynchronizationState.java","src/main/java/com/azure/search/documents/knowledgebases/models/IndexedOneLakeKnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/IndexedSharePointKnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecord.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseActivityRecordType.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAgenticReasoningActivityRecord.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseAzureBlobReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorAdditionalInfo.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseErrorDetail.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseImageContent.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedOneLakeReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseIndexedSharePointReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessage.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContent.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageContentType.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageImageContent.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseMessageTextContent.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelAnswerSynthesisActivityRecord.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseModelQueryPlanningActivityRecord.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseReferenceType.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRemoteSharePointReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalRequest.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseRetrievalResponse.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseSearchIndexReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeBaseWebReference.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntent.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalIntentType.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalLowReasoningEffort.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalMediumReasoningEffort.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalMinimalReasoningEffort.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalOutputMode.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalReasoningEffort.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalReasoningEffortKind.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeRetrievalSemanticIntent.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceAzureOpenAIVectorizer.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceIngestionParameters.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatistics.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceStatus.java","src/main/java/com/azure/search/documents/knowledgebases/models/KnowledgeSourceVectorizer.java","src/main/java/com/azure/search/documents/knowledgebases/models/RemoteSharePointKnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/SearchIndexKnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/SharePointSensitivityLabelInfo.java","src/main/java/com/azure/search/documents/knowledgebases/models/SynchronizationState.java","src/main/java/com/azure/search/documents/knowledgebases/models/WebKnowledgeSourceParams.java","src/main/java/com/azure/search/documents/knowledgebases/models/package-info.java","src/main/java/com/azure/search/documents/knowledgebases/package-info.java","src/main/java/com/azure/search/documents/models/AutocompleteItem.java","src/main/java/com/azure/search/documents/models/AutocompleteMode.java","src/main/java/com/azure/search/documents/models/AutocompleteOptions.java","src/main/java/com/azure/search/documents/models/AutocompleteResult.java","src/main/java/com/azure/search/documents/models/DebugInfo.java","src/main/java/com/azure/search/documents/models/DocumentDebugInfo.java","src/main/java/com/azure/search/documents/models/FacetResult.java","src/main/java/com/azure/search/documents/models/HybridCountAndFacetMode.java","src/main/java/com/azure/search/documents/models/HybridSearch.java","src/main/java/com/azure/search/documents/models/IndexAction.java","src/main/java/com/azure/search/documents/models/IndexActionType.java","src/main/java/com/azure/search/documents/models/IndexDocumentsBatch.java","src/main/java/com/azure/search/documents/models/IndexDocumentsResult.java","src/main/java/com/azure/search/documents/models/IndexingResult.java","src/main/java/com/azure/search/documents/models/LookupDocument.java","src/main/java/com/azure/search/documents/models/QueryAnswerResult.java","src/main/java/com/azure/search/documents/models/QueryAnswerType.java","src/main/java/com/azure/search/documents/models/QueryCaptionResult.java","src/main/java/com/azure/search/documents/models/QueryCaptionType.java","src/main/java/com/azure/search/documents/models/QueryDebugMode.java","src/main/java/com/azure/search/documents/models/QueryLanguage.java","src/main/java/com/azure/search/documents/models/QueryResultDocumentInnerHit.java","src/main/java/com/azure/search/documents/models/QueryResultDocumentRerankerInput.java","src/main/java/com/azure/search/documents/models/QueryResultDocumentSemanticField.java","src/main/java/com/azure/search/documents/models/QueryResultDocumentSubscores.java","src/main/java/com/azure/search/documents/models/QueryRewritesDebugInfo.java","src/main/java/com/azure/search/documents/models/QueryRewritesType.java","src/main/java/com/azure/search/documents/models/QueryRewritesValuesDebugInfo.java","src/main/java/com/azure/search/documents/models/QuerySpellerType.java","src/main/java/com/azure/search/documents/models/QueryType.java","src/main/java/com/azure/search/documents/models/ScoringStatistics.java","src/main/java/com/azure/search/documents/models/SearchDocumentsResult.java","src/main/java/com/azure/search/documents/models/SearchMode.java","src/main/java/com/azure/search/documents/models/SearchOptions.java","src/main/java/com/azure/search/documents/models/SearchRequest.java","src/main/java/com/azure/search/documents/models/SearchResult.java","src/main/java/com/azure/search/documents/models/SearchScoreThreshold.java","src/main/java/com/azure/search/documents/models/SemanticDebugInfo.java","src/main/java/com/azure/search/documents/models/SemanticErrorMode.java","src/main/java/com/azure/search/documents/models/SemanticErrorReason.java","src/main/java/com/azure/search/documents/models/SemanticFieldState.java","src/main/java/com/azure/search/documents/models/SemanticQueryRewritesResultType.java","src/main/java/com/azure/search/documents/models/SemanticSearchResultsType.java","src/main/java/com/azure/search/documents/models/SingleVectorFieldResult.java","src/main/java/com/azure/search/documents/models/SuggestDocumentsResult.java","src/main/java/com/azure/search/documents/models/SuggestOptions.java","src/main/java/com/azure/search/documents/models/SuggestResult.java","src/main/java/com/azure/search/documents/models/TextResult.java","src/main/java/com/azure/search/documents/models/VectorFilterMode.java","src/main/java/com/azure/search/documents/models/VectorQuery.java","src/main/java/com/azure/search/documents/models/VectorQueryKind.java","src/main/java/com/azure/search/documents/models/VectorSimilarityThreshold.java","src/main/java/com/azure/search/documents/models/VectorThreshold.java","src/main/java/com/azure/search/documents/models/VectorThresholdKind.java","src/main/java/com/azure/search/documents/models/VectorizableImageBinaryQuery.java","src/main/java/com/azure/search/documents/models/VectorizableImageUrlQuery.java","src/main/java/com/azure/search/documents/models/VectorizableTextQuery.java","src/main/java/com/azure/search/documents/models/VectorizedQuery.java","src/main/java/com/azure/search/documents/models/VectorsDebugInfo.java","src/main/java/com/azure/search/documents/models/package-info.java","src/main/java/com/azure/search/documents/package-info.java","src/main/java/module-info.java"]} \ No newline at end of file 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 index 6ce09f5b6bba..b0ef3dc07169 100644 --- 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 @@ -4,13 +4,10 @@ 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; +import com.azure.search.documents.models.AutocompleteResult; /** * This sample is based on the hotels-sample index available to install from the portal. @@ -39,15 +36,13 @@ public static void main(String[] args) { } private static void autoCompleteWithOneTermContext(SearchClient searchClient) { + AutocompleteOptions params = new AutocompleteOptions("coffe m", "sg") + .setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode( - AutocompleteMode.ONE_TERM_WITH_CONTEXT); - - PagedIterableBase results = searchClient.autocomplete("coffee m", - "sg", params, Context.NONE); + AutocompleteResult results = searchClient.autocomplete(params); System.out.println("Received results with one term context:"); - results.forEach(result -> System.out.println(result.getText())); + results.getResults().forEach(result -> System.out.println(result.getText())); /* Output: * Received results with one term context: @@ -56,17 +51,16 @@ private static void autoCompleteWithOneTermContext(SearchClient searchClient) { } private static void autoCompleteWithHighlighting(SearchClient searchClient) { - AutocompleteOptions params = new AutocompleteOptions() + AutocompleteOptions params = new AutocompleteOptions("co", "sg") .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); + AutocompleteResult results = searchClient.autocomplete(params); System.out.println("Received results with highlighting:"); - results.forEach(result -> System.out.println(result.getText())); + results.getResults().forEach(result -> System.out.println(result.getText())); /* Output: * Received results with highlighting: @@ -75,16 +69,15 @@ private static void autoCompleteWithHighlighting(SearchClient searchClient) { } private static void autoCompleteWithFilterAndFuzzy(SearchClient searchClient) { - AutocompleteOptions params = new AutocompleteOptions() + AutocompleteOptions params = new AutocompleteOptions("su", "sg") .setAutocompleteMode(AutocompleteMode.ONE_TERM) .setUseFuzzyMatching(true) .setFilter("HotelId ne '6' and Category eq 'Budget'"); - PagedIterableBase results = searchClient.autocomplete("su", "sg", params, - Context.NONE); + AutocompleteResult results = searchClient.autocomplete(params); System.out.println("Received results with filter and fuzzy:"); - results.forEach(result -> System.out.println(result.getText())); + results.getResults().forEach(result -> System.out.println(result.getText())); /* Output: * Received results with filter and fuzzy: 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 index 1d9cd06f7cd8..519feb0cea7a 100644 --- 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 @@ -5,11 +5,7 @@ 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 { @@ -27,9 +23,10 @@ public static void main(String[] args) { // 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"); + SearchOptions searchOptions = new SearchOptions().setSessionId("Session-1").setFilter("Rating gt 3") + .setSearchText("hotel"); - SearchPagedIterable results = searchClient.search("hotel", searchOptions, null); - results.forEach(result -> System.out.println("Hotel Id: " + result.getDocument(Hotel.class).getHotelId())); + searchClient.search(searchOptions) + .forEach(result -> System.out.println("Hotel Id: " + result.getAdditionalProperties().get("HotelId"))); } } 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 index 635643e8fbcd..bcc3e8a6f961 100644 --- 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 @@ -4,12 +4,9 @@ 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; @@ -27,11 +24,9 @@ public static void main(String[] args) { .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); + List searchFields = SearchIndexClient.buildSearchFields(Hotel.class); 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 index ba5db7792750..bb49fdc298aa 100644 --- 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 @@ -5,6 +5,8 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; +import java.util.Map; + /** * Get a single document based on its key * This sample is based on the hotels-sample index available to install from the portal. @@ -29,7 +31,7 @@ public static void main(String[] args) { .buildClient(); // Retrieve a single document by key - SearchDocument document = client.getDocument("3", SearchDocument.class); + Map document = client.getDocument("3").getAdditionalProperties(); document.forEach((key, value) -> System.out.println(key + ":" + value)); } 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 index 030ec1b7fe75..2b9358846c7f 100644 --- 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 @@ -7,10 +7,10 @@ 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; + +import java.util.concurrent.CountDownLatch; /** * This example shows how to handle errors when the Azure AI Search service @@ -31,7 +31,7 @@ public class HttpResponseExceptionExample { private static final String INDEX_NAME = "hotels-sample-index"; - public static void main(String[] args) { + public static void main(String[] args) throws InterruptedException { handleErrorsWithSyncClient(); handleErrorsWithAsyncClient(); } @@ -48,15 +48,12 @@ private static void handleErrorsWithSyncClient() { try { // Perform a search on a non-existent field - SearchOptions searchOptions = new SearchOptions() + SearchOptions searchOptions = new SearchOptions().setSearchText("hotel") .setFilter("Non_Existent_Field eq 'Luxury'"); - Iterable results = client.search("hotel", - searchOptions, Context.NONE); - - for (SearchResult result : results) { + for (SearchResult result : client.search(searchOptions)) { // normal results processing - System.out.printf("Found hotel: %s%n", result.getDocument(SearchDocument.class).get("HotelName")); + System.out.printf("Found hotel: %s%n", result.getAdditionalProperties().get("hotelName")); } } catch (HttpResponseException ex) { // The exception contains the HTTP status code and the detailed message @@ -70,22 +67,22 @@ private static void handleErrorsWithSyncClient() { /** * With the async client, errors need to be handled when subscribing to the stream */ - private static void handleErrorsWithAsyncClient() { + private static void handleErrorsWithAsyncClient() throws InterruptedException { SearchAsyncClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) .buildAsyncClient(); - SearchOptions searchOptions = new SearchOptions() + SearchOptions searchOptions = new SearchOptions().setSearchText("hotel") .setFilter("Non_Existent_Field eq 'Luxury'"); - SearchPagedFlux results = client.search("hotel", searchOptions); - results + CountDownLatch latch = new CountDownLatch(1); + client.search(searchOptions) .subscribe( foo -> { // normal results processing - System.out.printf("Found hotel: %s%n", foo.getDocument(SearchDocument.class).get("HotelName")); + System.out.printf("Found hotel: %s%n", foo.getAdditionalProperties().get("hotelName")); }, err -> { if (err instanceof HttpResponseException) { @@ -102,12 +99,15 @@ private static void handleErrorsWithAsyncClient() { throw new RuntimeException(err); } }, - () -> System.out.println("completed")); + () -> { + latch.countDown(); + 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(); + latch.await(); } } 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 index 66af6fb7979d..7f6fb6dbfab7 100644 --- 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 @@ -4,8 +4,6 @@ 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; @@ -13,6 +11,7 @@ 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.GetIndexStatisticsResult; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; import com.azure.search.documents.indexes.models.MagnitudeScoringFunction; import com.azure.search.documents.indexes.models.MagnitudeScoringParameters; @@ -22,19 +21,15 @@ 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; @@ -61,10 +56,8 @@ 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)); + try { + System.out.println(searchServiceStatistics.toJsonString()); } catch (IOException ex) { ex.printStackTrace(); } @@ -110,7 +103,7 @@ private static void getServiceStatistics(SearchIndexClient client) { private static void getIndexStatistics(SearchIndexClient client) { SearchIndex testIndex = createTestIndex(); SearchIndex index = client.createOrUpdateIndex(testIndex); - SearchIndexStatistics result = client.getIndexStatistics(index.getName()); + GetIndexStatisticsResult result = client.getIndexStatistics(index.getName()); long documentCount = result.getDocumentCount(); long storageSize = result.getStorageSize(); @@ -133,160 +126,156 @@ private static SearchIndex createTestIndex() { 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), + .setKey(true) + .setSearchable(false) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("HotelName", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.FALSE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(false) + .setRetrievable(true), new SearchField("Description", SearchFieldDataType.STRING) - .setKey(Boolean.FALSE) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) + .setKey(false) + .setSearchable(true) + .setFilterable(false) + .setSortable(false) + .setFacetable(false) .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE) - .setHidden(Boolean.FALSE), + .setRetrievable(true), new SearchField("DescriptionFr", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) + .setSearchable(true) + .setFilterable(false) + .setSortable(false) + .setFacetable(false) .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE) - .setHidden(Boolean.FALSE), + .setRetrievable(true), new SearchField("Description_Custom", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.FALSE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.FALSE) + .setSearchable(true) + .setFilterable(false) + .setSortable(false) + .setFacetable(false) .setSearchAnalyzerName(LexicalAnalyzerName.STOP) .setIndexAnalyzerName(LexicalAnalyzerName.STOP) - .setHidden(Boolean.FALSE), + .setRetrievable(true), new SearchField("Category", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setSortable(false) + .setFacetable(true) + .setRetrievable(true), new SearchField("ParkingIncluded", SearchFieldDataType.BOOLEAN) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("LastRenovationDate", SearchFieldDataType.DATE_TIME_OFFSET) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("Rating", SearchFieldDataType.INT32) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("Address", SearchFieldDataType.COMPLEX) - .setFields(Arrays.asList( + .setFields( new SearchField("StreetAddress", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setRetrievable(true), new SearchField("City", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("StateProvince", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("Country", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("PostalCode", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - ) - ), + .setSearchable(true) + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(true)), new SearchField("Location", SearchFieldDataType.GEOGRAPHY_POINT) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.FALSE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setSortable(true) + .setFacetable(false) + .setRetrievable(true), new SearchField("Rooms", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)) - .setFields(Arrays.asList( + .setFields( new SearchField("Description", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE) + .setSearchable(true) + .setRetrievable(true) .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), new SearchField("DescriptionFr", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setHidden(Boolean.FALSE) + .setSearchable(true) + .setRetrievable(true) .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), new SearchField("Type", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("BaseRate", SearchFieldDataType.DOUBLE) - .setKey(Boolean.FALSE) - .setSearchable(Boolean.FALSE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setKey(false) + .setSearchable(false) + .setFilterable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("BedOptions", SearchFieldDataType.STRING) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setSearchable(true) + .setFilterable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("SleepsCount", SearchFieldDataType.INT32) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN) - .setFilterable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFilterable(true) + .setFacetable(true) + .setRetrievable(true), new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setSearchable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.FALSE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - ) - ), + .setSearchable(true) + .setFilterable(true) + .setSortable(false) + .setFacetable(true) + .setRetrievable(true)), new SearchField("TotalGuests", SearchFieldDataType.INT64) - .setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) - .setFacetable(Boolean.TRUE) - .setHidden(Boolean.TRUE), + .setFilterable(true) + .setSortable(true) + .setFacetable(true) + .setRetrievable(false), new SearchField("ProfitMargin", SearchFieldDataType.DOUBLE) ); return new SearchIndex("hotels", fieldList) - .setScoringProfiles(Arrays.asList( + .setScoringProfiles( new ScoringProfile("MyProfile") .setFunctionAggregation(ScoringFunctionAggregation.AVERAGE) .setFunctions(new MagnitudeScoringFunction("Rating", 2.0, @@ -298,31 +287,27 @@ private static SearchIndex createTestIndex() { .setInterpolation(ScoringFunctionInterpolation.LINEAR), new FreshnessScoringFunction("LastRenovationDate", 1.1, new FreshnessScoringParameters(Duration.ofDays(365))) - .setInterpolation(ScoringFunctionInterpolation.LOGARITHMIC) - ) + .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) - ), + .setInterpolation(ScoringFunctionInterpolation.LINEAR)), new ScoringProfile("ProfileThree") .setFunctionAggregation(ScoringFunctionAggregation.MINIMUM) .setFunctions(new MagnitudeScoringFunction("Rating", 3.0, new MagnitudeScoringParameters(0, 10) .setShouldBoostBeyondRangeByConstant(false)) - .setInterpolation(ScoringFunctionInterpolation.QUADRATIC) - ), + .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)))) + .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"))); + .setCorsOptions(new CorsOptions("http://tempuri.org", "http://localhost:80").setMaxAgeInSeconds(60L)) + .setSuggesters(new SearchSuggester("FancySuggester", "HotelName")); } /** 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 index 2af012dbadc7..8ce5bd9fa9a5 100644 --- 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 @@ -50,12 +50,9 @@ private static SearchAsyncClient createAdvancedClient() { .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName("hotels") - .serviceVersion(SearchServiceVersion.V2020_06_30) + .serviceVersion(SearchServiceVersion.getLatest()) .addPolicy(new RetryPolicy()) - .httpClient( - new NettyAsyncHttpClientBuilder() - .wiretap(true) - .build() - ).buildAsyncClient(); + .httpClient(new NettyAsyncHttpClientBuilder().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 index 3c374829de27..d2b8820a69df 100644 --- 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 @@ -5,13 +5,12 @@ 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.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. @@ -46,13 +45,13 @@ private static void basicIndexing() { .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")); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "200")), + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "300"))); // Perform index operations on a list of documents - IndexDocumentsResult result = client.mergeOrUploadDocuments(hotels); + IndexDocumentsResult result = client.indexDocuments(batch); System.out.printf("Indexed %s documents%n", result.getResults().size()); } @@ -66,9 +65,9 @@ private static void advancedIndexing() { .indexName(INDEX_NAME) .buildClient(); - IndexDocumentsBatch batch = new IndexDocumentsBatch() - .addMergeOrUploadActions(Collections.singletonList(new Hotel().setHotelId("100"))) - .addDeleteActions(Collections.singletonList(new Hotel().setHotelId("200"))); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(Collections.singletonMap("HotelId", "200"))); // Send a single batch that performs many different actions IndexDocumentsResult result = client.indexDocuments(batch); 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 index cbc29a9be53d..6a2d001ab93d 100644 --- 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 @@ -4,16 +4,17 @@ 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.HttpHeaderName; +import com.azure.core.http.rest.RequestOptions; 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.IndexDocumentsResult; -import java.util.ArrayList; -import java.util.List; +import java.util.Collections; import java.util.UUID; /** @@ -42,62 +43,57 @@ public static void main(String[] args) { 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")); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties( + Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "200")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "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); + String customRequestId = UUID.randomUUID().toString(); + RequestOptions requestOptions = new RequestOptions() + .setHeader(HttpHeaderName.X_MS_CLIENT_REQUEST_ID, customRequestId); // 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")); + System.out.printf("Sending request with 'x-ms-client-request-id': %s%n", customRequestId); // Perform index operations on a list of documents - Response response = client.mergeOrUploadDocumentsWithResponse(hotels, null, context); + Response response = client.indexDocumentsWithResponse(batch, null, requestOptions); 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")); + response.getHeaders().get(HttpHeaderName.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")); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties( + Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "200")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "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); + String customRequestId = UUID.randomUUID().toString(); + RequestOptions requestOptions = new RequestOptions() + .setHeader(HttpHeaderName.X_MS_CLIENT_REQUEST_ID, customRequestId); // 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")); + System.out.printf("Sending request with 'x-ms-client-request-id': %s%n", customRequestId); // Perform index operations on a list of documents - client.mergeDocumentsWithResponse(hotels, null) - .contextWrite(context) + client.indexDocumentsWithResponse(batch, null, requestOptions) .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")); + response.getHeaders().get(HttpHeaderName.X_MS_CLIENT_REQUEST_ID)); }).block(); } 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..c7de8a9b3d9e 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 @@ -4,11 +4,10 @@ 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.http.rest.RequestOptions; +import com.azure.core.util.BinaryData; 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; @@ -18,22 +17,22 @@ 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SearchPagedIterable; 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.LinkedHashMap; import java.util.List; +import java.util.Map; /** * Code samples for the README.md @@ -105,25 +104,24 @@ public void 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"); + RequestOptions requestOptions = new RequestOptions() + .setHeader("my-header1", "my-header1-value") + .setHeader("my-header2", "my-header2-value") + .setHeader("my-header3", "my-header3-value"); // Call API by passing headers in Context. - SearchIndex index = new SearchIndex(INDEX_NAME).setFields( + SearchIndex index = new SearchIndex(INDEX_NAME, 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)); + SEARCH_INDEX_CLIENT.createIndexWithResponse(BinaryData.fromObject(index), requestOptions); // Above three HttpHeader will be added in outgoing HttpRequest. } public void handleErrorsWithSyncClient() { // BEGIN: readme-sample-handleErrorsWithSyncClient try { - Iterable results = SEARCH_CLIENT.search("hotel"); + Iterable results = SEARCH_CLIENT.search(new SearchOptions().setSearchText("hotel")); } catch (HttpResponseException ex) { // The exception contains the HTTP status code and the detailed message // returned from the search service @@ -136,20 +134,16 @@ public void 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); + for (SearchResult searchResult : SEARCH_CLIENT.search(new SearchOptions().setSearchText("luxury"))) { + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", doc.get("HotelId"), doc.get("HotelName")); } // 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() { @@ -174,48 +168,53 @@ public Hotel setName(String name) { 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); + for (SearchResult searchResult : SEARCH_CLIENT.search(new SearchOptions().setSearchText("luxury"))) { + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", doc.get("Id"), doc.get("Name")); } // END: readme-sample-searchWithStronglyType } public void searchWithSearchOptions() { // BEGIN: readme-sample-searchWithSearchOptions - SearchOptions options = new SearchOptions() + SearchOptions options = new SearchOptions().setSearchText("luxury") .setFilter("rating ge 4") .setOrderBy("rating desc") .setTop(5); - SearchPagedIterable searchResultsIterable = SEARCH_CLIENT.search("luxury", options, Context.NONE); + SearchPagedIterable searchResultsIterable = SEARCH_CLIENT.search(options); // ... // END: readme-sample-searchWithSearchOptions } public void searchWithAsyncClient() { // BEGIN: readme-sample-searchWithAsyncClient - SEARCH_ASYNC_CLIENT.search("luxury") + SEARCH_ASYNC_CLIENT.search(new SearchOptions().setSearchText("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()); + Map hotel = result.getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.get("Id"), hotel.get("Name")); }); // 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()); + Map hotel = SEARCH_CLIENT.getDocument("1").getAdditionalProperties(); + System.out.printf("This is hotelId %s, and this is hotel name %s.%n", hotel.get("Id"), hotel.get("Name")); // 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"))); + Map hotel = new LinkedHashMap<>(); + hotel.put("Id", "783"); + hotel.put("Name", "Upload Inn"); + + Map hotel2 = new LinkedHashMap<>(); + hotel2.put("Id", "12"); + hotel2.put("Name", "Renovated Ranch"); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(hotel), + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(hotel2)); SEARCH_CLIENT.indexDocuments(batch); // END: readme-sample-batchDocumentsOperations } @@ -223,50 +222,48 @@ public void batchDocumentsOperations() { public void createIndex() { // BEGIN: readme-sample-createIndex List searchFieldList = new ArrayList<>(); - searchFieldList.add(new SearchField("hotelId", SearchFieldDataType.STRING) + searchFieldList.add(new SearchField("HotelId", SearchFieldDataType.STRING) .setKey(true) .setFilterable(true) .setSortable(true)); - - searchFieldList.add(new SearchField("hotelName", SearchFieldDataType.STRING) + searchFieldList.add(new SearchField("HotelName", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true)); - searchFieldList.add(new SearchField("description", SearchFieldDataType.STRING) + searchFieldList.add(new SearchField("Description", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.EU_LUCENE)); - searchFieldList.add(new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + 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) + 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) + new SearchField("StateProvince", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) .setSortable(true), - new SearchField("country", SearchFieldDataType.STRING) + new SearchField("Country", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) .setSortable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) + new SearchField("PostalCode", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) - .setSortable(true) - )); + .setSortable(true))); // Prepare suggester. - SearchSuggester suggester = new SearchSuggester("sg", Collections.singletonList("hotelName")); + SearchSuggester suggester = new SearchSuggester("sg", "hotelName"); // Prepare SearchIndex with index name and search fields. - SearchIndex index = new SearchIndex("hotels").setFields(searchFieldList).setSuggesters(suggester); + SearchIndex index = new SearchIndex("hotels", searchFieldList).setSuggesters(suggester); // Create an index SEARCH_INDEX_CLIENT.createIndex(index); // END: readme-sample-createIndex @@ -274,7 +271,7 @@ public void createIndex() { public void createIndexUseFieldBuilder() { // BEGIN: readme-sample-createIndexUseFieldBuilder - List searchFields = SearchIndexClient.buildSearchFields(Hotel.class, null); + List searchFields = SearchIndexClient.buildSearchFields(Hotel.class); SEARCH_INDEX_CLIENT.createIndex(new SearchIndex("index", searchFields)); // END: readme-sample-createIndexUseFieldBuilder } 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 index cc302b8b46ca..d989b2801996 100644 --- 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 @@ -20,11 +20,13 @@ 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.WebApiHttpHeaders; import com.azure.search.documents.indexes.models.WebApiSkill; -import com.azure.search.documents.models.Hotel; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.IndexDocumentsResult; -import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -82,11 +84,11 @@ private static void addCustomWebSkillset(SearchIndexerClient client) { 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) + .setHttpHeaders(new WebApiHttpHeaders().setAdditionalProperties(headers)) .setName("webapi-skill") .setDescription("A WebApi skill that can be used as a custom skillset"); - SearchIndexerSkillset skillset = new SearchIndexerSkillset(skillsetName, Collections.singletonList(webApiSkill)) + SearchIndexerSkillset skillset = new SearchIndexerSkillset(skillsetName, webApiSkill) .setDescription("Skillset for testing custom skillsets"); client.createOrUpdateSkillset(skillset); @@ -110,13 +112,13 @@ private static void getServiceStatistics(SearchIndexClient client) { 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")); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "200")), + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "300"))); // Perform index operations on a list of documents - IndexDocumentsResult result = client.mergeOrUploadDocuments(hotels); + IndexDocumentsResult result = client.indexDocuments(batch); System.out.printf("Indexed %s documents%n", result.getResults().size()); } @@ -130,7 +132,8 @@ private static void addSynonymMapToIndex(SearchIndexClient client) { SearchIndex index = client.getIndex(INDEX_NAME); List fields = index.getFields(); fields.get(1).setSynonymMapNames(synonymMapName); - index.setFields(fields); + index.getFields().clear(); + index.getFields().addAll(fields); client.createOrUpdateIndex(index); System.out.printf("Updated index %s with synonym map %s on field %s%n", INDEX_NAME, synonymMapName, "HotelName"); 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 index ece4284031ee..025356a2726f 100644 --- 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 @@ -4,26 +4,20 @@ 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.GetIndexStatisticsResult; 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.AutocompleteResult; import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SearchPagedIterable; +import com.azure.search.documents.models.SuggestDocumentsResult; 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) @@ -48,8 +42,9 @@ public static void main(String[] args) { 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()); + GetIndexStatisticsResult 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); @@ -70,49 +65,36 @@ public static void main(String[] args) { } private static void suggestQuery(SearchClient client) { - - SuggestOptions suggestOptions = new SuggestOptions() + SuggestOptions suggestOptions = new SuggestOptions("vew", SUGGESTER_NAME) .setUseFuzzyMatching(true); - PagedIterableBase suggestResult = client.suggest("vew", - SUGGESTER_NAME, suggestOptions, Context.NONE); - Iterator iterator = suggestResult.iterableByPage().iterator(); + SuggestDocumentsResult suggestResult = client.suggest(suggestOptions); 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()) - ) - ); + suggestResult.getResults().forEach(res -> System.out.printf(" Found match to: %s, match = %s%n", + res.getAdditionalProperties().get("HotelName"), res.getText())); } private static void autocompleteQuery(SearchClient client) { + AutocompleteOptions params = new AutocompleteOptions("co", SUGGESTER_NAME) + .setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode( - AutocompleteMode.ONE_TERM_WITH_CONTEXT); - - PagedIterableBase results = client.autocomplete("co", - SUGGESTER_NAME, params, Context.NONE); + AutocompleteResult results = client.autocomplete(params); System.out.println("Autocomplete with one term context results:"); - results.forEach(result -> System.out.println(result.getText())); + results.getResults().forEach(result -> System.out.println(result.getText())); } private static void searchQuery(SearchClient client) { - // search=Resort&searchfields=HotelName&$count=true - SearchOptions searchOptions = new SearchOptions() + SearchOptions searchOptions = new SearchOptions().setSearchText("Resort") .setIncludeTotalCount(true) .setSearchFields("HotelName"); - SearchPagedIterable searchResults = client.search("Resort", searchOptions, Context.NONE); + SearchPagedIterable searchResults = client.search(searchOptions); 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); - }); + searchResults.forEach(result -> + System.out.printf(" Hotel: %s%n", result.getAdditionalProperties().get("HotelName"))); } private static SearchClient createSearchClient() { 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 index b19f9b4ee6de..9041cd467589 100644 --- 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 @@ -6,7 +6,8 @@ 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.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SearchPagedFlux; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @@ -47,14 +48,12 @@ public static void main(String[] args) { 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()); - }); + SearchPagedFlux results = searchClient.search(new SearchOptions().setSearchText("searchText")); + results.subscribe(item -> { + // Convert the property bag received from the search query to an object of type Hotel + Hotel hotel = objectMapper.convertValue(item.getAdditionalProperties(), 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 index 3bc2a5542152..05698349b41d 100644 --- 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 @@ -5,11 +5,12 @@ 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; +import java.util.Map; + /** * This example shows how to perform basic searches using the Azure AI Search SDK for Java *

@@ -44,15 +45,10 @@ private static void searchWithSyncClient() { .buildClient(); // Perform a text-based search - for (SearchResult result : client.search("luxury hotel", - new SearchOptions(), Context.NONE)) { - + for (SearchResult result : client.search(new SearchOptions().setSearchText("luxury hotel"))) { // 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); + Map doc = result.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelName"), doc.get("Rating")); } } @@ -68,7 +64,7 @@ private static void searchWithAsyncClient() { .buildAsyncClient(); // Add additional options for the search - SearchOptions parameters = new SearchOptions() + SearchOptions parameters = new SearchOptions().setSearchText("hotel") .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") @@ -76,21 +72,15 @@ private static void searchWithAsyncClient() { .setIncludeTotalCount(true); // Perform a search and subscribe to the results and log additional information - Flux results = client.search("hotel", parameters) + Flux results = client.search(parameters) .log() - .doOnSubscribe(__ -> System.out.println("Subscribed to PagedFlux results")); + .doOnSubscribe(ignored -> 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")); + results.subscribe(result -> { + Map doc = result.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelName"), doc.get("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 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 index cde99934e311..96a6d27f3b1a 100644 --- 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 @@ -4,8 +4,11 @@ package com.azure.search.documents; import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.http.HttpHeaderName; 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.core.util.Context; import com.azure.search.documents.indexes.SearchIndexAsyncClient; import com.azure.search.documents.indexes.SearchIndexClient; @@ -13,22 +16,25 @@ 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.AnalyzeResult; import com.azure.search.documents.indexes.models.AnalyzeTextOptions; import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.CreateOrUpdateDataSourceConnectionOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateIndexerOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateSkillsetOptions; +import com.azure.search.documents.indexes.models.DataSourceCredentials; +import com.azure.search.documents.indexes.models.DocumentKeysOrIds; import com.azure.search.documents.indexes.models.FieldMapping; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; +import com.azure.search.documents.indexes.models.GetIndexStatisticsResult; import com.azure.search.documents.indexes.models.InputFieldMappingEntry; import com.azure.search.documents.indexes.models.LexicalTokenizerName; +import com.azure.search.documents.indexes.models.ListDataSourcesResult; +import com.azure.search.documents.indexes.models.ListIndexersResult; +import com.azure.search.documents.indexes.models.ListSkillsetsResult; +import com.azure.search.documents.indexes.models.ListSynonymMapsResult; import com.azure.search.documents.indexes.models.OcrSkill; import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; import com.azure.search.documents.indexes.models.SearchAlias; 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; @@ -37,27 +43,33 @@ 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.SkillNames; 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.AutocompleteResult; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; 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.LookupDocument; import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SearchResult; +import com.azure.search.documents.models.SearchPagedFlux; +import com.azure.search.documents.models.SearchPagedIterable; +import com.azure.search.documents.models.SearchPagedResponse; +import com.azure.search.documents.models.SuggestDocumentsResult; 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.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; @SuppressWarnings("unused") @@ -79,138 +91,151 @@ public void createSearchClientFromBuilder() { } /** - * Code snippet for {@link SearchClient#uploadDocuments(Iterable)}. + * Code snippet for {@link SearchClient#indexDocuments(IndexDocumentsBatch)}. */ public void uploadDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.uploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-upload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - IndexDocumentsResult result = SEARCH_CLIENT.uploadDocuments(Collections.singletonList(searchDocument)); + IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-upload } /** - * Code snippet for {@link SearchClient#uploadDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} + * Code snippet for + * {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void uploadDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-upload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.uploadDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); + Response resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse( + new IndexDocumentsBatch(new IndexAction().setActionType(IndexActionType.UPLOAD) + .setAdditionalProperties(searchDocument)), null, + new RequestOptions().setContext(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 + // END: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-upload } /** - * Code snippet for {@link SearchClient#mergeDocuments(Iterable)} + * Code snippet for {@link SearchClient#indexDocuments(IndexDocumentsBatch)} */ public void mergeDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.mergeDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-merge + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelName", "merge"); - IndexDocumentsResult result = SEARCH_CLIENT.mergeDocuments(Collections.singletonList(searchDocument)); + IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-merge } /** - * Code snippet for {@link SearchClient#mergeDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} + * Code snippet for {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void mergeDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-merge + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.mergeDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); + Response resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse( + new IndexDocumentsBatch(new IndexAction().setActionType(IndexActionType.MERGE) + .setAdditionalProperties(searchDocument)), null, + new RequestOptions().setContext(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 + // END: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-merge } /** - * Code snippet for {@link SearchClient#mergeOrUploadDocuments(Iterable)} + * Code snippet for {@link SearchClient#indexDocuments(IndexDocumentsBatch)} */ public void mergeOrUploadDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.mergeOrUploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-mergeOrUpload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - IndexDocumentsResult result = SEARCH_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument)); + IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-mergeOrUpload } /** - * Code snippet for {@link SearchClient#mergeOrUploadDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} + * Code snippet for {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void mergeOrUploadDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-mergeOrUpload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.mergeOrUploadDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); + Response resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse( + new IndexDocumentsBatch(new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD) + .setAdditionalProperties(searchDocument)), null, + new RequestOptions().setContext(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 + // END: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-mergeOrUpload } /** - * Code snippet for {@link SearchClient#deleteDocuments(Iterable)} + * Code snippet for {@link SearchClient#indexDocuments(IndexDocumentsBatch)} */ public void deleteDocuments() { - // BEGIN: com.azure.search.documents.SearchClient.deleteDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-delete + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - IndexDocumentsResult result = SEARCH_CLIENT.deleteDocuments(Collections.singletonList(searchDocument)); + IndexDocumentsResult result = SEARCH_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch-delete } /** - * Code snippet for {@link SearchClient#deleteDocumentsWithResponse(Iterable, IndexDocumentsOptions, Context)} + * Code snippet for {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void deleteDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions-Context - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-delete + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - Response resultResponse = SEARCH_CLIENT.deleteDocumentsWithResponse( - Collections.singletonList(searchDocument), null, new Context(KEY_1, VALUE_1)); + Response resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse( + new IndexDocumentsBatch(new IndexAction().setActionType(IndexActionType.DELETE) + .setAdditionalProperties(searchDocument)), null, + new RequestOptions().setContext(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 + // END: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-delete } /** @@ -218,15 +243,15 @@ public void deleteDocumentsWithResponse() { */ public void indexDocuments() { // BEGIN: com.azure.search.documents.SearchClient.indexDocuments#IndexDocumentsBatch - SearchDocument searchDocument1 = new SearchDocument(); + Map searchDocument1 = new LinkedHashMap<>(); searchDocument1.put("hotelId", "1"); searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); + Map searchDocument2 = new LinkedHashMap<>(); searchDocument2.put("hotelId", "2"); searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); + IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument1), + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(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(), @@ -236,53 +261,52 @@ public void indexDocuments() { } /** - * Code snippet for {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, Context)} + * Code snippet for {@link SearchClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void indexDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-Context - SearchDocument searchDocument1 = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions + Map searchDocument1 = new LinkedHashMap<>(); searchDocument1.put("hotelId", "1"); searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); + Map searchDocument2 = new LinkedHashMap<>(); searchDocument2.put("hotelId", "2"); searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); + IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument1), + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(searchDocument2)); Response resultResponse = SEARCH_CLIENT.indexDocumentsWithResponse(indexDocumentsBatch, - null, new Context(KEY_1, VALUE_1)); + null, new RequestOptions().setContext(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 + // END: com.azure.search.documents.SearchClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions } /** - * Code snippet for {@link SearchClient#getDocument(String, Class)} + * Code snippet for {@link SearchClient#getDocument(String)} */ 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 + // BEGIN: com.azure.search.documents.SearchClient.getDocuments#String + LookupDocument result = SEARCH_CLIENT.getDocument("hotelId"); + result.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, Document value %s", key, value)); + // END: com.azure.search.documents.SearchClient.getDocuments#String } /** - * Code snippet for {@link SearchClient#getDocumentWithResponse(String, Class, List, Context)} + * Code snippet for {@link SearchClient#getDocumentWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.SearchClient.getDocumentWithResponse#String-RequestOptions + Response resultResponse = SEARCH_CLIENT.getDocumentWithResponse("hotelId", + new RequestOptions().setContext(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 + LookupDocument document = resultResponse.getValue().toObject(LookupDocument.class); + document.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, Document value %s", key, value)); + // END: com.azure.search.documents.SearchClient.getDocumentWithResponse#String-RequestOptions } /** @@ -296,159 +320,103 @@ public void getDocumentCount() { } /** - * Code snippet for {@link SearchClient#getDocumentCountWithResponse(Context)} + * Code snippet for {@link SearchClient#getDocumentCountWithResponse(RequestOptions)} */ public void getDocumentCountWithResponse() { - // BEGIN: com.azure.search.documents.SearchClient.getDocumentCountWithResponse#Context - Response countResponse = SEARCH_CLIENT.getDocumentCountWithResponse(new Context(KEY_1, VALUE_1)); + // BEGIN: com.azure.search.documents.SearchClient.getDocumentCountWithResponse#RequestOptions + Response countResponse = SEARCH_CLIENT.getDocumentCountWithResponse( + new RequestOptions().setContext(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 + System.out.printf("There are %d documents in service.", Long.parseLong(countResponse.getValue().toString())); + // END: com.azure.search.documents.SearchClient.getDocumentCountWithResponse#RequestOptions } /** - * 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)} + * Code snippet for {@link SearchClient#search(SearchOptions)} */ 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()); + // BEGIN: com.azure.search.documents.SearchClient.search#SearchOptions + SearchPagedIterable searchPagedIterable = SEARCH_CLIENT.search(new SearchOptions() + .setSearchText("searchText").setOrderBy("hotelId desc")); + boolean firstPage = true; 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 (firstPage) { + System.out.printf("There are around %d results.", resultResponse.getCount()); + firstPage = false; + } + numberOfDocumentsReturned += resultResponse.getElements().stream().count(); + resultResponse.getElements().forEach(searchResult -> searchResult.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, document value %s", key, value))); if (numberOfDocumentsReturned >= SEARCH_SKIP_LIMIT) { // Reached the $skip limit, stop requesting more documents. break; } } - // END: com.azure.search.documents.SearchClient.search#String-SearchOptions-Context + // END: com.azure.search.documents.SearchClient.search#SearchOptions } /** - * 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)} + * Code snippet for {@link SearchClient#suggest(SuggestOptions)} */ 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()); + // BEGIN: com.azure.search.documents.SearchClient.suggest#SuggestOptions + SuggestDocumentsResult results = SEARCH_CLIENT.suggest(new SuggestOptions("searchText", "sg") + .setOrderBy("hotelId desc")); + for (SuggestResult result : results.getResults()) { + result.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, document value %s", key, value)); } - // END: com.azure.search.documents.SearchClient.autocomplete#String-String + // END: com.azure.search.documents.SearchClient.suggest#SuggestOptions } /** - * Code snippet for {@link SearchClient#autocomplete(String, String, AutocompleteOptions, Context)} + * Code snippet for {@link SearchClient#autocomplete(AutocompleteOptions)} */ 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) { + // BEGIN: com.azure.search.documents.SearchClient.autocomplete#AutocompleteOptions + AutocompleteResult results = SEARCH_CLIENT.autocomplete(new AutocompleteOptions("searchText", "sg") + .setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)); + for (AutocompleteItem result : results.getResults()) { System.out.printf("The complete term is %s", result.getText()); } - // END: com.azure.search.documents.SearchClient.autocomplete#String-String-AutocompleteOptions-Context + // END: com.azure.search.documents.SearchClient.autocomplete#AutocompleteOptions } private static final SearchAsyncClient SEARCH_ASYNC_CLIENT = new SearchClientBuilder().buildAsyncClient(); /** - * Code snippet for {@link SearchAsyncClient#uploadDocuments(Iterable)}. + * Code snippet for {@link SearchAsyncClient#indexDocuments(IndexDocumentsBatch)}. */ public void uploadDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.uploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-upload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.uploadDocuments(Collections.singletonList(searchDocument)) + SEARCH_ASYNC_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-upload } /** - * Code snippet for {@link SearchAsyncClient#uploadDocumentsWithResponse(Iterable, IndexDocumentsOptions)} + * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void uploadDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-upload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.uploadDocumentsWithResponse(Collections.singletonList(searchDocument), null) + SEARCH_ASYNC_CLIENT.indexDocumentsWithResponse(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument)), null, + null) .subscribe(resultResponse -> { System.out.println("The status code of the response is " + resultResponse.getStatusCode()); for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { @@ -456,34 +424,37 @@ public void uploadDocumentsWithResponseAsync() { indexingResult.isSucceeded()); } }); - // END: com.azure.search.documents.SearchAsyncClient.uploadDocumentsWithResponse#Iterable-IndexDocumentsOptions + // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-upload } /** - * Code snippet for {@link SearchAsyncClient#mergeDocuments(Iterable)} + * Code snippet for {@link SearchAsyncClient#indexDocuments(IndexDocumentsBatch)} */ public void mergeDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-merge + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelName", "merge"); - SEARCH_ASYNC_CLIENT.mergeDocuments(Collections.singletonList(searchDocument)) + SEARCH_ASYNC_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-merge } /** - * Code snippet for {@link SearchAsyncClient#mergeDocumentsWithResponse(Iterable, IndexDocumentsOptions)} + * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void mergeDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-merge + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.mergeDocumentsWithResponse(Collections.singletonList(searchDocument), null) + SEARCH_ASYNC_CLIENT.indexDocumentsWithResponse(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(searchDocument)), + null, null) .subscribe(resultResponse -> { System.out.println("The status code of the response is " + resultResponse.getStatusCode()); for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { @@ -491,36 +462,39 @@ public void mergeDocumentsWithResponseAsync() { indexingResult.isSucceeded()); } }); - // END: com.azure.search.documents.SearchAsyncClient.mergeDocumentsWithResponse#Iterable-IndexDocumentsOptions + // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-merge } /** - * Code snippet for {@link SearchAsyncClient#mergeOrUploadDocuments(Iterable)} + * Code snippet for {@link SearchAsyncClient#indexDocuments(IndexDocumentsBatch)} */ public void mergeOrUploadDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-mergeOrUpload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.mergeOrUploadDocuments(Collections.singletonList(searchDocument)) + SEARCH_ASYNC_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-mergeOrUpload } /** - * Code snippet for {@link SearchAsyncClient#mergeOrUploadDocumentsWithResponse(Iterable, IndexDocumentsOptions)} + * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void mergeOrUploadDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-mergeOrUpload + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.mergeOrUploadDocumentsWithResponse(Collections.singletonList(searchDocument), null) + SEARCH_ASYNC_CLIENT.indexDocumentsWithResponse(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE_OR_UPLOAD).setAdditionalProperties(searchDocument)), + null, null) .subscribe(resultResponse -> { System.out.println("The status code of the response is " + resultResponse.getStatusCode()); for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { @@ -528,37 +502,40 @@ public void mergeOrUploadDocumentsWithResponseAsync() { indexingResult.getKey(), indexingResult.isSucceeded()); } }); - // END: com.azure.search.documents.SearchAsyncClient.mergeOrUploadDocumentsWithResponse#Iterable-IndexDocumentsOptions + // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-mergeOrUpload } /** - * Code snippet for {@link SearchAsyncClient#deleteDocuments(Iterable)} + * Code snippet for {@link SearchAsyncClient#indexDocuments(IndexDocumentsBatch)} */ public void deleteDocumentsAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.deleteDocuments#Iterable - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-delete + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.deleteDocuments(Collections.singletonList(searchDocument)) + SEARCH_ASYNC_CLIENT.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(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 + // END: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch-delete } /** - * Code snippet for {@link SearchAsyncClient#deleteDocumentsWithResponse(Iterable, IndexDocumentsOptions)} + * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void deleteDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions - SearchDocument searchDocument = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-delete + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("hotelId", "1"); searchDocument.put("hotelName", "test"); - SEARCH_ASYNC_CLIENT.deleteDocumentsWithResponse(Collections.singletonList(searchDocument), null) + SEARCH_ASYNC_CLIENT.indexDocumentsWithResponse(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(searchDocument)), null, + null) .subscribe(resultResponse -> { System.out.println("The status code of the response is " + resultResponse.getStatusCode()); for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { @@ -566,7 +543,7 @@ public void deleteDocumentsWithResponseAsync() { indexingResult.isSucceeded()); } }); - // END: com.azure.search.documents.SearchAsyncClient.deleteDocumentsWithResponse#Iterable-IndexDocumentsOptions + // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions-delete } /** @@ -574,15 +551,15 @@ public void deleteDocumentsWithResponseAsync() { */ public void indexDocumentsAsync() { // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocuments#IndexDocumentsBatch - SearchDocument searchDocument1 = new SearchDocument(); + Map searchDocument1 = new LinkedHashMap<>(); searchDocument1.put("hotelId", "1"); searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); + Map searchDocument2 = new LinkedHashMap<>(); searchDocument2.put("hotelId", "2"); searchDocument2.put("hotelName", "test2"); - IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch<>(); - indexDocumentsBatch.addUploadActions(Collections.singletonList(searchDocument1)); - indexDocumentsBatch.addDeleteActions(Collections.singletonList(searchDocument2)); + IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument1), + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(searchDocument2)); SEARCH_ASYNC_CLIENT.indexDocuments(indexDocumentsBatch) .subscribe(result -> { for (IndexingResult indexingResult : result.getResults()) { @@ -594,20 +571,20 @@ public void indexDocumentsAsync() { } /** - * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions)} + * Code snippet for {@link SearchAsyncClient#indexDocumentsWithResponse(IndexDocumentsBatch, IndexDocumentsOptions, RequestOptions)} */ public void indexDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions - SearchDocument searchDocument1 = new SearchDocument(); + // BEGIN: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions + Map searchDocument1 = new LinkedHashMap<>(); searchDocument1.put("hotelId", "1"); searchDocument1.put("hotelName", "test1"); - SearchDocument searchDocument2 = new SearchDocument(); + Map searchDocument2 = new LinkedHashMap<>(); 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) + IndexDocumentsBatch indexDocumentsBatch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument1), + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(searchDocument2)); + SEARCH_ASYNC_CLIENT.indexDocumentsWithResponse(indexDocumentsBatch, null, null) .subscribe(resultResponse -> { System.out.println("The status code of the response is " + resultResponse.getStatusCode()); for (IndexingResult indexingResult : resultResponse.getValue().getResults()) { @@ -615,38 +592,33 @@ public void indexDocumentsWithResponseAsync() { indexingResult.isSucceeded()); } }); - // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions + // END: com.azure.search.documents.SearchAsyncClient.indexDocumentsWithResponse#IndexDocumentsBatch-IndexDocumentsOptions-RequestOptions } /** - * Code snippet for {@link SearchAsyncClient#getDocument(String, Class)} + * Code snippet for {@link SearchAsyncClient#getDocument(String)} */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocuments#String + SEARCH_ASYNC_CLIENT.getDocument("hotelId") + .subscribe(result -> result.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, Document value %s", key, value))); + // END: com.azure.search.documents.SearchAsyncClient.getDocuments#String } /** - * Code snippet for {@link SearchAsyncClient#getDocumentWithResponse(String, Class, List)} + * Code snippet for {@link SearchAsyncClient#getDocumentWithResponse(String, RequestOptions)} */ 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()); - } + // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse#String-RequestOptions + SEARCH_ASYNC_CLIENT.getDocumentWithResponse("hotelId", null) + .subscribe(response -> { + System.out.println("The status code of the response is " + response.getStatusCode()); + LookupDocument document = response.getValue().toObject(LookupDocument.class); + document.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, Document value %s", key, value)); }); - // END: com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse#String-Class-List + // END: com.azure.search.documents.SearchAsyncClient.getDocumentWithResponse#String-RequestOptions } /** @@ -660,122 +632,65 @@ public void getDocumentCountAsync() { } /** - * Code snippet for {@link SearchAsyncClient#getDocumentCountWithResponse()} + * Code snippet for {@link SearchAsyncClient#getDocumentCountWithResponse(RequestOptions)} */ public void getDocumentCountWithResponseAsync() { - // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse - SEARCH_ASYNC_CLIENT.getDocumentCountWithResponse() + // BEGIN: com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse#RequestOptions + SEARCH_ASYNC_CLIENT.getDocumentCountWithResponse(new RequestOptions()) .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()); + System.out.printf("There are %d documents in service.", + Long.parseLong(countResponse.getValue().toString())); }); - // END: com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse + // END: com.azure.search.documents.SearchAsyncClient.getDocumentCountWithResponse#RequestOptions } /** - * 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 -> { - // Reached the $skip limit, stop requesting more documents. - return numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT; - }) - .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)} + * Code snippet for {@link SearchAsyncClient#search(SearchOptions)} */ 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)); + // BEGIN: com.azure.search.documents.SearchAsyncClient.search#SearchOptions + SearchPagedFlux pagedFlux = SEARCH_ASYNC_CLIENT.search(new SearchOptions().setSearchText("searchText") + .setOrderBy("hotelId desc")); + AtomicBoolean firstPage = new AtomicBoolean(true); AtomicLong numberOfDocumentsReturned = new AtomicLong(); pagedFlux.byPage() + .doOnNext(page -> { + if (firstPage.getAndSet(false)) { + System.out.printf("There are around %d results.", page.getCount()); + } + }) .takeUntil(page -> { // Reached the $skip limit, stop requesting more documents. - return numberOfDocumentsReturned.addAndGet(page.getValue().size()) >= SEARCH_SKIP_LIMIT; + return numberOfDocumentsReturned.addAndGet(page.getElements().stream().count()) >= SEARCH_SKIP_LIMIT; }) - .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 + .subscribe(page -> page.getElements().forEach(searchDocument -> searchDocument.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, document value %s", key, value)))); + // END: com.azure.search.documents.SearchAsyncClient.search#SearchOptions } /** - * Code snippet for {@link SearchAsyncClient#suggest(String, String, SuggestOptions)} + * Code snippet for {@link SearchAsyncClient#suggest(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 + // BEGIN: com.azure.search.documents.SearchAsyncClient.suggest#SuggestOptions + SEARCH_ASYNC_CLIENT.suggest(new SuggestOptions("searchText", "sg").setOrderBy("hotelId desc")) + .subscribe(results -> results.getResults().forEach(result -> result.getAdditionalProperties() + .forEach((key, value) -> System.out.printf("Document key %s, document value %s", key, value)))); + // END: com.azure.search.documents.SearchAsyncClient.suggest#SuggestOptions } /** - * Code snippet for {@link SearchAsyncClient#autocomplete(String, String, AutocompleteOptions)} + * Code snippet for {@link SearchAsyncClient#autocomplete(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 + // BEGIN: com.azure.search.documents.SearchAsyncClient.autocomplete#AutocompleteOptions + SEARCH_ASYNC_CLIENT.autocomplete(new AutocompleteOptions("searchText", "sg") + .setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT)) + .subscribe(results -> results.getResults().forEach(result -> + System.out.printf("The complete term is %s", result.getText()))); + // END: com.azure.search.documents.SearchAsyncClient.autocomplete#AutocompleteOptions } /** @@ -812,11 +727,9 @@ public void createSearchIndexClientFromBuilder() { */ public void createSearchIndex() { // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createIndex#SearchIndex - List searchFields = Arrays.asList( + SearchIndex searchIndex = new SearchIndex("searchIndex", new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); + new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)); 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()); @@ -824,21 +737,20 @@ public void createSearchIndex() { } /** - * Code snippet for {@link SearchIndexClient#createIndexWithResponse(SearchIndex, Context)}. + * Code snippet for {@link SearchIndexClient#createIndexWithResponse(BinaryData, RequestOptions)}. */ public void createSearchIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse#SearchIndex-Context - List searchFields = Arrays.asList( + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse#BinaryData-RequestOptions + SearchIndex searchIndex = new SearchIndex("searchIndex", new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); + new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)); - Response indexFromServiceResponse = - SEARCH_INDEX_CLIENT.createIndexWithResponse(searchIndex, new Context(KEY_1, VALUE_1)); + Response response = SEARCH_INDEX_CLIENT.createIndexWithResponse(BinaryData.fromObject(searchIndex), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndex responseIndex = response.getValue().toObject(SearchIndex.class); 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 + response.getStatusCode(), responseIndex.getName()); + // END: com.azure.search.documents.indexes.SearchIndexClient.createIndexWithResponse#BinaryData-RequestOptions } /** @@ -854,16 +766,17 @@ public void getSearchIndex() { } /** - * Code snippet for {@link SearchIndexClient#getIndexWithResponse(String, Context)}} + * Code snippet for {@link SearchIndexClient#getIndexWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndexWithResponse#String-RequestOptions + Response response = SEARCH_INDEX_CLIENT.getIndexWithResponse("searchIndex", + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndex index = response.getValue().toObject(SearchIndex.class); 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 + response.getStatusCode(), index.getName()); + // END: com.azure.search.documents.indexes.SearchIndexClient.getIndexWithResponse#String-RequestOptions } /** @@ -871,24 +784,24 @@ public void getSearchIndexWithResponse() { */ public void getSearchIndexStatistics() { // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatistics#String - SearchIndexStatistics statistics = SEARCH_INDEX_CLIENT.getIndexStatistics("searchIndex"); + GetIndexStatisticsResult 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)} + * Code snippet for {@link SearchIndexClient#getIndexStatisticsWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatisticsWithResponse#String-RequestOptions + Response response = SEARCH_INDEX_CLIENT.getIndexStatisticsWithResponse("searchIndex", + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + GetIndexStatisticsResult statistics = response.getValue().toObject(GetIndexStatisticsResult.class); 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 + response.getStatusCode(), statistics.getDocumentCount(), statistics.getStorageSize()); + // END: com.azure.search.documents.indexes.SearchIndexClient.getIndexStatisticsWithResponse#String-RequestOptions } /** @@ -904,19 +817,19 @@ public void listIndexes() { // 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#listIndexes(RequestOptions)} +// */ +// 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()} @@ -930,19 +843,19 @@ public void listIndexNames() { // 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#listIndexNames(RequestOptions)} +// */ +// 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)} @@ -959,19 +872,19 @@ public void createOrUpdateIndex() { } /** - * Code snippet for {@link SearchIndexClient#createIndexWithResponse(SearchIndex, Context)} + * Code snippet for {@link SearchIndexClient#createOrUpdateIndexWithResponse(SearchIndex, RequestOptions)} */ public void createOrUpdateIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse#SearchIndex-boolean-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse#SearchIndex-RequestOptions 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)); + indexFromService.setSuggesters(new SearchSuggester("sg", "hotelName")); + Response updatedIndexResponse = SEARCH_INDEX_CLIENT.createOrUpdateIndexWithResponse( + indexFromService, new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, indexFromService.getETag()) + .addQueryParam("allowIndexDowntime", "false").setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateIndexWithResponse#SearchIndex-RequestOptions } /** @@ -984,15 +897,16 @@ public void deleteSearchIndex() { } /** - * Code snippet for {@link SearchIndexClient#deleteIndexWithResponse(SearchIndex, boolean, Context)} + * Code snippet for {@link SearchIndexClient#deleteIndexWithResponse(String, RequestOptions)} */ public void deleteSearchIndexWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse#SearchIndex-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse#String-RequestOptions SearchIndex indexFromService = SEARCH_INDEX_CLIENT.getIndex("searchIndex"); - Response deleteResponse = SEARCH_INDEX_CLIENT.deleteIndexWithResponse(indexFromService, true, - new Context(KEY_1, VALUE_1)); + Response deleteResponse = SEARCH_INDEX_CLIENT.deleteIndexWithResponse(indexFromService.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, indexFromService.getETag()) + .setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexClient.deleteIndexWithResponse#String-RequestOptions } /** @@ -1000,27 +914,28 @@ public void deleteSearchIndexWithResponse() { */ 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) { + AnalyzeResult result = SEARCH_INDEX_CLIENT.analyzeText("searchIndex", + new AnalyzeTextOptions("The quick brown fox").setTokenizerName(LexicalTokenizerName.CLASSIC)); + for (AnalyzedTokenInfo tokenInfo : result.getTokens()) { 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)} + * Code snippet for {@link SearchIndexClient#analyzeTextWithResponse(String, BinaryData, RequestOptions)} */ 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) { + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.analyzeTextWithResponse#String-BinaryData-RequestOptions + Response response = SEARCH_INDEX_CLIENT.analyzeTextWithResponse("searchIndex", + BinaryData.fromObject(new AnalyzeTextOptions("The quick brown fox") + .setTokenizerName(LexicalTokenizerName.CLASSIC)), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + System.out.println("The status code of the response is " + response.getStatusCode()); + for (AnalyzedTokenInfo tokenInfo : response.getValue().toObject(AnalyzeResult.class).getTokens()) { 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 + // END: com.azure.search.documents.indexes.SearchIndexClient.analyzeTextWithResponse#String-BinaryData-RequestOptions } /** @@ -1037,18 +952,19 @@ public void createSynonymMap() { } /** - * Code snippet for {@link SearchIndexClient#createIndexWithResponse(SearchIndex, Context)}. + * Code snippet for {@link SearchIndexClient#createIndexWithResponse(BinaryData, RequestOptions)}. */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createSynonymMapWithResponse#BinaryData-RequestOptions + Response response = SEARCH_INDEX_CLIENT.createSynonymMapWithResponse( + BinaryData.fromObject(new SynonymMap("synonymMap", + "United States, United States of America, USA\nWashington, Wash. => WA")), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SynonymMap synonymMap = response.getValue().toObject(SynonymMap.class); 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 + + "The synonym map name is %s. The ETag of synonym map is %s.%n", response.getStatusCode(), + synonymMap.getName(), synonymMap.getETag()); + // END: com.azure.search.documents.indexes.SearchIndexClient.createSynonymMapWithResponse#BinaryData-RequestOptions } /** @@ -1064,16 +980,17 @@ public void getSynonymMap() { } /** - * Code snippet for {@link SearchIndexClient#getSynonymMapWithResponse(String, Context)}} + * Code snippet for {@link SearchIndexClient#getSynonymMapWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapWithResponse#String-RequestOptions + Response response = SEARCH_INDEX_CLIENT.getSynonymMapWithResponse("synonymMap", + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SynonymMap synonymMap = response.getValue().toObject(SynonymMap.class); 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 + + "The synonym map name is %s. The ETag of synonym map is %s.%n", response.getStatusCode(), + synonymMap.getName(), synonymMap.getETag()); + // END: com.azure.search.documents.indexes.SearchIndexClient.getSynonymMapWithResponse#String-RequestOptions } /** @@ -1081,53 +998,53 @@ public void getSynonymMapWithResponse() { */ public void listSynonymMaps() { // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listSynonymMaps - PagedIterable synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMaps(); - for (SynonymMap synonymMap: synonymMaps) { + ListSynonymMapsResult synonymMaps = SEARCH_INDEX_CLIENT.listSynonymMaps(); + for (SynonymMap synonymMap: synonymMaps.getSynonymMaps()) { 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#listSynonymMaps(RequestOptions)} +// */ +// 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(); + List 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#listSynonymMapNames(RequestOptions)} +// */ +// 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)} @@ -1135,7 +1052,8 @@ public void listSynonymMapNamesWithContext() { 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.getSynonyms().clear(); + synonymMap.getSynonyms().add("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()); @@ -1143,19 +1061,20 @@ public void createOrUpdateSynonymMap() { } /** - * Code snippet for {@link SearchIndexClient#createOrUpdateSynonymMapWithResponse(SynonymMap, boolean, Context)} + * Code snippet for {@link SearchIndexClient#createOrUpdateSynonymMapWithResponse(SynonymMap, RequestOptions)} */ public void createOrUpdateSynonymMapWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse#SynonymMap-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse#SynonymMap-RequestOptions 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)); + synonymMap.getSynonyms().clear(); + synonymMap.getSynonyms().add("United States, United States of America, USA, America\nWashington, Wash. => WA"); + Response updatedSynonymMap = SEARCH_INDEX_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, synonymMap.getETag()) + .setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateSynonymMapWithResponse#SynonymMap-RequestOptions } /** @@ -1168,15 +1087,16 @@ public void deleteSynonymMap() { } /** - * Code snippet for {@link SearchIndexClient#deleteSynonymMapWithResponse(SynonymMap, boolean, Context)} + * Code snippet for {@link SearchIndexClient#deleteSynonymMapWithResponse(String, RequestOptions)} */ public void deleteSynonymMapWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse#SynonymMap-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse#String-RequestOptions SynonymMap synonymMap = SEARCH_INDEX_CLIENT.getSynonymMap("synonymMap"); - Response response = SEARCH_INDEX_CLIENT.deleteSynonymMapWithResponse(synonymMap, true, - new Context(KEY_1, VALUE_1)); + Response response = SEARCH_INDEX_CLIENT.deleteSynonymMapWithResponse(synonymMap.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, synonymMap.getETag()) + .setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexClient.deleteSynonymMapWithResponse#String-RequestOptions } /** @@ -1191,16 +1111,16 @@ public void getServiceStatistics() { } /** - * Code snippet for {@link SearchIndexClient#getServiceStatisticsWithResponse(Context)} + * Code snippet for {@link SearchIndexClient#getServiceStatisticsWithResponse(RequestOptions)} */ public void getServiceStatisticsWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse#Context - Response serviceStatistics = - SEARCH_INDEX_CLIENT.getServiceStatisticsWithResponse(new Context(KEY_1, VALUE_1)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse#RequestOptions + Response response = SEARCH_INDEX_CLIENT.getServiceStatisticsWithResponse( + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchServiceStatistics statistics = response.getValue().toObject(SearchServiceStatistics.class); 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 + response.getStatusCode(), statistics.getCounters().getIndexCounter()); + // END: com.azure.search.documents.indexes.SearchIndexClient.getServiceStatisticsWithResponse#RequestOptions } private static final SearchIndexAsyncClient SEARCH_INDEX_ASYNC_CLIENT = new SearchIndexClientBuilder() @@ -1223,11 +1143,9 @@ public void createSearchIndexAsyncClientFromBuilder() { */ public void createSearchIndexAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndex#SearchIndex - List searchFields = Arrays.asList( + SearchIndex searchIndex = new SearchIndex("searchIndex", new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); + new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)); 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(), @@ -1236,21 +1154,21 @@ public void createSearchIndexAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#createIndexWithResponse(SearchIndex)}. + * Code snippet for {@link SearchIndexAsyncClient#createIndexWithResponse(BinaryData, RequestOptions)}. */ public void createSearchIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse#SearchIndex - List searchFields = Arrays.asList( + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse#BinaryData-RequestOptions + SearchIndex searchIndex = new SearchIndex("searchIndex", new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true) - ); - SearchIndex searchIndex = new SearchIndex("searchIndex", searchFields); + new SearchField("hotelName", SearchFieldDataType.STRING).setSearchable(true)); - SEARCH_INDEX_ASYNC_CLIENT.createIndexWithResponse(searchIndex) - .subscribe(indexFromServiceResponse -> + SEARCH_INDEX_ASYNC_CLIENT.createIndexWithResponse(BinaryData.fromObject(searchIndex), new RequestOptions()) + .subscribe(response -> { + SearchIndex index = response.getValue().toObject(SearchIndex.class); 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 + response.getStatusCode(), index.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createIndexWithResponse#BinaryData-RequestOptions } /** @@ -1266,15 +1184,17 @@ public void getSearchIndexAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#getIndexWithResponse(String)}} + * Code snippet for {@link SearchIndexAsyncClient#getIndexWithResponse(String, RequestOptions)}} */ public void getSearchIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse#String - SEARCH_INDEX_ASYNC_CLIENT.getIndexWithResponse("searchIndex") - .subscribe(indexFromServiceResponse -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse#String-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.getIndexWithResponse("searchIndex", new RequestOptions()) + .subscribe(response -> { + SearchIndex index = response.getValue().toObject(SearchIndex.class); 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 + response.getStatusCode(), index.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexWithResponse#String-RequestOptions } /** @@ -1290,16 +1210,18 @@ public void getSearchIndexStatisticsAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#getIndexStatisticsWithResponse(String)} + * Code snippet for {@link SearchIndexAsyncClient#getIndexStatisticsWithResponse(String, RequestOptions)} */ 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 + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatisticsWithResponse#String-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.getIndexStatisticsWithResponse("searchIndex", new RequestOptions()) + .subscribe(response -> { + GetIndexStatisticsResult statistics = response.getValue().toObject(GetIndexStatisticsResult.class); + 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", + response.getStatusCode(), statistics.getDocumentCount(), statistics.getStorageSize()); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getIndexStatisticsWithResponse#String-RequestOptions } /** @@ -1340,19 +1262,19 @@ public void createOrUpdateIndexAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#createIndexWithResponse(SearchIndex)} + * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateIndexWithResponse(SearchIndex, RequestOptions)} */ public void createOrUpdateIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse#SearchIndex-boolean-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse#SearchIndex-RequestOptions 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)) + .doOnNext(indexFromService -> indexFromService.setSuggesters(new SearchSuggester("sg", "hotelName"))) + .flatMap(indexFromService -> SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateIndexWithResponse(indexFromService, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, indexFromService.getETag()) + .addQueryParam("allowIndexDowntime", "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 + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateIndexWithResponse#SearchIndex-RequestOptions } /** @@ -1366,15 +1288,16 @@ public void deleteSearchIndexAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#deleteIndexWithResponse(SearchIndex, boolean)} + * Code snippet for {@link SearchIndexAsyncClient#deleteIndexWithResponse(String, RequestOptions)} */ public void deleteSearchIndexWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse#SearchIndex-boolean + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse#String-RequestOptions SEARCH_INDEX_ASYNC_CLIENT.getIndex("searchIndex") - .flatMap(indexFromService -> SEARCH_INDEX_ASYNC_CLIENT.deleteIndexWithResponse(indexFromService, true)) + .flatMap(indexFromService -> SEARCH_INDEX_ASYNC_CLIENT.deleteIndexWithResponse(indexFromService.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, indexFromService.getETag()))) .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 + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteIndexWithResponse#String-RequestOptions } /** @@ -1383,9 +1306,9 @@ public void deleteSearchIndexWithResponseAsync() { 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())); + new AnalyzeTextOptions("The quick brown fox").setTokenizerName(LexicalTokenizerName.CLASSIC)) + .subscribe(result -> result.getTokens().forEach(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 } @@ -1404,19 +1327,19 @@ public void createSynonymMapAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#createSynonymMapWithResponse(SynonymMap)} + * Code snippet for {@link SearchIndexAsyncClient#createSynonymMapWithResponse(BinaryData, RequestOptions)} */ 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 -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMapWithResponse#BinaryData-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.createSynonymMapWithResponse(BinaryData.fromObject(new SynonymMap("synonymMap", + "United States, United States of America, USA\nWashington, Wash. => WA")), new RequestOptions()) + .subscribe(response -> { + SynonymMap synonymMap = response.getValue().toObject(SynonymMap.class); 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 + + "The synonym map name is %s. The ETag of synonym map is %s.%n", response.getStatusCode(), + synonymMap.getName(), synonymMap.getETag()); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createSynonymMapWithResponse#BinaryData-RequestOptions } /** @@ -1432,16 +1355,18 @@ public void getSynonymMapAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#getSynonymMapWithResponse(String)}} + * Code snippet for {@link SearchIndexAsyncClient#getSynonymMapWithResponse(String, RequestOptions)}} */ 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 + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapWithResponse#String-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.getSynonymMapWithResponse("synonymMap", new RequestOptions()) + .subscribe(response -> { + SynonymMap synonymMap = response.getValue().toObject(SynonymMap.class); + 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", + response.getStatusCode(), synonymMap.getName(), synonymMap.getETag()); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getSynonymMapWithResponse#String-RequestOptions } /** @@ -1450,8 +1375,9 @@ public void getSynonymMapWithResponseAsync() { 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())); + .subscribe(result -> result.getSynonymMaps().forEach(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 } @@ -1471,8 +1397,11 @@ public void listSynonymMapNamesAsync() { 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")) + .doOnNext(synonymMap -> { + synonymMap.getSynonyms().clear(); + synonymMap.getSynonyms() + .add("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(), @@ -1481,21 +1410,23 @@ public void createOrUpdateSynonymMapAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateSynonymMapWithResponse(SynonymMap, boolean)} + * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateSynonymMapWithResponse(SynonymMap, RequestOptions)} */ public void createOrUpdateSynonymMapWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse#SynonymMap-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse#SynonymMap-RequestOptions SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("searchIndex") .flatMap(synonymMap -> { - synonymMap.setSynonyms( + synonymMap.getSynonyms().clear(); + synonymMap.getSynonyms().add( "United States, United States of America, USA, America\nWashington, Wash. => WA"); - return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, true); + return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateSynonymMapWithResponse(synonymMap, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, synonymMap.getETag())); }) .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 + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateSynonymMapWithResponse#SynonymMap-RequestOptions } /** @@ -1509,14 +1440,15 @@ public void deleteSynonymMapAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#deleteSynonymMapWithResponse(SynonymMap, boolean)} + * Code snippet for {@link SearchIndexAsyncClient#deleteSynonymMapWithResponse(String, RequestOptions)} */ public void deleteSynonymMapWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse#SynonymMap-boolean + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse#String-RequestOptions SEARCH_INDEX_ASYNC_CLIENT.getSynonymMap("synonymMap") - .flatMap(synonymMap -> SEARCH_INDEX_ASYNC_CLIENT.deleteSynonymMapWithResponse(synonymMap, true)) + .flatMap(synonymMap -> SEARCH_INDEX_ASYNC_CLIENT.deleteSynonymMapWithResponse(synonymMap.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, synonymMap.getETag()))) .subscribe(response -> System.out.println("The status code of the response is" + response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse#SynonymMap-boolean + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteSynonymMapWithResponse#String-RequestOptions } /** @@ -1531,17 +1463,18 @@ public void getServiceStatisticsAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#getServiceStatisticsWithResponse()} + * Code snippet for {@link SearchIndexAsyncClient#getServiceStatisticsWithResponse(RequestOptions)} */ 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 + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatisticsWithResponse#RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.getServiceStatisticsWithResponse(new RequestOptions()) + .subscribe(response -> { + SearchServiceStatistics statistics = response.getValue().toObject(SearchServiceStatistics.class); + System.out.printf( + "The status code of the response is %s.%n" + "There are %s search indexes in your service.%n", + response.getStatusCode(), statistics.getCounters().getIndexCounter()); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getServiceStatisticsWithResponse#RequestOptions } private static final SearchIndexerClient SEARCH_INDEXER_CLIENT = new SearchIndexerClientBuilder().buildClient(); @@ -1571,18 +1504,19 @@ public void createSearchIndexer() { } /** - * Code snippet for {@link SearchIndexerClient#createIndexerWithResponse(SearchIndexer, Context)}. + * Code snippet for {@link SearchIndexerClient#createIndexerWithResponse(BinaryData, RequestOptions)}. */ public void createSearchIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse#SearchIndexer-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse#BinaryData-RequestOptions SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource", "searchIndex"); - Response indexerFromServiceResponse = SEARCH_INDEXER_CLIENT.createIndexerWithResponse( - searchIndexer, new Context(KEY_1, VALUE_1)); + Response response = SEARCH_INDEXER_CLIENT.createIndexerWithResponse( + BinaryData.fromObject(searchIndexer), new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndexer indexer = response.getValue().toObject(SearchIndexer.class); 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 + response.getStatusCode(), indexer.getName()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.createIndexerWithResponse#BinaryData-RequestOptions } /** @@ -1598,16 +1532,17 @@ public void getSearchIndexer() { } /** - * Code snippet for {@link SearchIndexerClient#getIndexerWithResponse(String, Context)}} + * Code snippet for {@link SearchIndexerClient#getIndexerWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerWithResponse#String-RequestOptions + Response response = SEARCH_INDEXER_CLIENT.getIndexerWithResponse( + "searchIndexer", new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndexer indexer = response.getValue().toObject(SearchIndexer.class); 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 + response.getStatusCode(), indexer.getName()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerWithResponse#String-RequestOptions } @@ -1616,54 +1551,54 @@ public void getSearchIndexerWithResponse() { */ public void listIndexers() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listIndexers - PagedIterable indexers = SEARCH_INDEXER_CLIENT.listIndexers(); - for (SearchIndexer indexer: indexers) { + ListIndexersResult indexers = SEARCH_INDEXER_CLIENT.listIndexers(); + for (SearchIndexer indexer: indexers.getIndexers()) { 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#listIndexers(RequestOptions)} +// */ +// 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(); + List 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#listIndexerNames(RequestOptions)} +// */ +// 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)} @@ -1680,41 +1615,24 @@ public void createOrUpdateIndexer() { } /** - * 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#createOrUpdateIndexerWithResponse(CreateOrUpdateIndexerOptions, Context)} + * Code snippet for {@link SearchIndexerClient#createOrUpdateIndexerWithResponse(SearchIndexer, RequestOptions)} */ public void createOrUpdateIndexerWithResponse2() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse#CreateOrUpdateIndexerOptions-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse#SearchIndexer-RequestOptions SearchIndexer searchIndexerFromService = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); searchIndexerFromService.setFieldMappings(Collections.singletonList( new FieldMapping("hotelName").setTargetFieldName("HotelName"))); - CreateOrUpdateIndexerOptions options = new CreateOrUpdateIndexerOptions(searchIndexerFromService) - .setOnlyIfUnchanged(true) - .setCacheReprocessingChangeDetectionDisabled(false) - .setCacheResetRequirementsIgnored(true); Response indexerFromService = SEARCH_INDEXER_CLIENT.createOrUpdateIndexerWithResponse( - options, new Context(KEY_1, VALUE_1)); + searchIndexerFromService, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchIndexerFromService.getETag()) + .addQueryParam("ignoreResetRequirements", "true") + .addQueryParam("disableCacheReprocessingChangeDetection", "false") + .setContext(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#CreateOrUpdateIndexerOptions-Context + // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateIndexerWithResponse#SearchIndexer-RequestOptions } /** @@ -1727,15 +1645,16 @@ public void deleteSearchIndexer() { } /** - * Code snippet for {@link SearchIndexerClient#deleteIndexerWithResponse(SearchIndexer, boolean, Context)} + * Code snippet for {@link SearchIndexerClient#deleteIndexerWithResponse(String, RequestOptions)} */ public void deleteSearchIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse#SearchIndexer-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse#String-RequestOptions SearchIndexer searchIndexer = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); - Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteIndexerWithResponse(searchIndexer, true, - new Context(KEY_1, VALUE_1)); + Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteIndexerWithResponse(searchIndexer.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchIndexer.getETag()) + .setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteIndexerWithResponse#String-RequestOptions } /** @@ -1748,14 +1667,14 @@ public void resetIndexer() { } /** - * Code snippet for {@link SearchIndexerClient#resetIndexerWithResponse(String, Context)} + * Code snippet for {@link SearchIndexerClient#resetIndexerWithResponse(String, RequestOptions)} */ public void resetIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse#String-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse#String-RequestOptions Response response = SEARCH_INDEXER_CLIENT.resetIndexerWithResponse("searchIndexer", - new Context(KEY_1, VALUE_1)); + new RequestOptions().setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexerClient.resetIndexerWithResponse#String-RequestOptions } /** @@ -1768,14 +1687,14 @@ public void runIndexer() { } /** - * Code snippet for {@link SearchIndexerClient#runIndexerWithResponse(String, Context)} + * Code snippet for {@link SearchIndexerClient#runIndexerWithResponse(String, RequestOptions)} */ public void runIndexerWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse#String-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse#String-RequestOptions Response response = SEARCH_INDEXER_CLIENT.runIndexerWithResponse("searchIndexer", - new Context(KEY_1, VALUE_1)); + new RequestOptions().setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexerClient.runIndexerWithResponse#String-RequestOptions } /** @@ -1789,49 +1708,57 @@ public void getIndexerStatus() { } /** - * Code snippet for {@link SearchIndexerClient#getIndexerStatusWithResponse(String, Context)} + * Code snippet for {@link SearchIndexerClient#getIndexerStatusWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatusWithResponse#String-RequestOptions + Response response = SEARCH_INDEXER_CLIENT.getIndexerStatusWithResponse("searchIndexer", + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + + SearchIndexerStatus status = response.getValue().toObject(SearchIndexerStatus.class); 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 + response.getStatusCode(), status.getStatus()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.getIndexerStatusWithResponse#String-RequestOptions } /** - * Code snippet for {@link SearchIndexerClient#resetDocuments(String, Boolean, List, List)} + * Code snippet for {@link SearchIndexerClient#resetDocuments(String, Boolean, DocumentKeysOrIds)} */ public void resetDocuments() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetDocuments#String-Boolean-List-List + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetDocuments#String-Boolean-DocumentKeyOrIds // Reset the documents with keys 1234 and 4321. - SEARCH_INDEXER_CLIENT.resetDocuments("searchIndexer", false, Arrays.asList("1234", "4321"), null); + SEARCH_INDEXER_CLIENT.resetDocuments("searchIndexer", false, + new DocumentKeysOrIds().setDocumentKeys("1234", "4321")); // Clear the previous documents to be reset and replace them with documents 1235 and 5231. - SEARCH_INDEXER_CLIENT.resetDocuments("searchIndexer", true, Arrays.asList("1235", "5321"), null); - // END: com.azure.search.documents.indexes.SearchIndexerClient.resetDocuments#String-Boolean-List-List + SEARCH_INDEXER_CLIENT.resetDocuments("searchIndexer", true, + new DocumentKeysOrIds().setDocumentKeys("1235", "5321")); + // END: com.azure.search.documents.indexes.SearchIndexerClient.resetDocuments#String-Boolean-DocumentKeyOrIds } /** - * Code snippet for {@link SearchIndexerClient#resetDocumentsWithResponse(SearchIndexer, Boolean, List, List, Context)} + * Code snippet for {@link SearchIndexerClient#resetDocumentsWithResponse(String, RequestOptions)} */ public void resetDocumentsWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetDocumentsWithResponse#SearchIndexer-Boolean-List-List-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetDocumentsWithResponse#String-RequestOptions SearchIndexer searchIndexer = SEARCH_INDEXER_CLIENT.getIndexer("searchIndexer"); // Reset the documents with keys 1234 and 4321. - Response resetDocsResult = SEARCH_INDEXER_CLIENT.resetDocumentsWithResponse(searchIndexer, false, - Arrays.asList("1234", "4321"), null, new Context(KEY_1, VALUE_1)); + Response resetDocsResult = SEARCH_INDEXER_CLIENT.resetDocumentsWithResponse(searchIndexer.getName(), + new RequestOptions().addQueryParam("overwrite", "false") + .setBody(BinaryData.fromObject(new DocumentKeysOrIds().setDocumentKeys("1234", "4321"))) + .setContext(new Context(KEY_1, VALUE_1))); System.out.printf("Requesting documents to be reset completed with status code %d.%n", resetDocsResult.getStatusCode()); // Clear the previous documents to be reset and replace them with documents 1235 and 5231. - resetDocsResult = SEARCH_INDEXER_CLIENT.resetDocumentsWithResponse(searchIndexer, true, - Arrays.asList("1235", "5321"), null, new Context(KEY_1, VALUE_1)); + resetDocsResult = SEARCH_INDEXER_CLIENT.resetDocumentsWithResponse(searchIndexer.getName(), + new RequestOptions().addQueryParam("overwrite", "true") + .setBody(BinaryData.fromObject(new DocumentKeysOrIds().setDocumentKeys("1235", "5321"))) + .setContext(new Context(KEY_1, VALUE_1))); System.out.printf("Overwriting the documents to be reset completed with status code %d.%n", resetDocsResult.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.resetDocumentsWithResponse#SearchIndexer-Boolean-List-List-Context + // END: com.azure.search.documents.indexes.SearchIndexerClient.resetDocumentsWithResponse#String-RequestOptions } /** @@ -1840,7 +1767,8 @@ public void resetDocumentsWithResponse() { 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}", + com.azure.search.documents.indexes.models.SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString("{connectionString}"), new com.azure.search.documents.indexes.models.SearchIndexerDataContainer("container")); SearchIndexerDataSourceConnection dataSourceFromService = SEARCH_INDEXER_CLIENT.createDataSourceConnection(dataSource); @@ -1850,19 +1778,22 @@ public void createDataSource() { } /** - * Code snippet for {@link SearchIndexerClient#createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, Context)}. + * Code snippet for {@link SearchIndexerClient#createDataSourceConnectionWithResponse(BinaryData, RequestOptions)}. */ public void createDataSourceWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse#BinaryData-RequestOptions SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource", - SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}", + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString("{connectionString}"), new SearchIndexerDataContainer("container")); - Response dataSourceFromService = - SEARCH_INDEXER_CLIENT.createDataSourceConnectionWithResponse(dataSource, new Context(KEY_1, VALUE_1)); + Response response = SEARCH_INDEXER_CLIENT.createDataSourceConnectionWithResponse( + BinaryData.fromObject(dataSource), new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndexerDataSourceConnection responseDataSource = response.getValue() + .toObject(SearchIndexerDataSourceConnection.class); 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 + response.getStatusCode(), responseDataSource.getName()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.createDataSourceConnectionWithResponse#BinaryData-RequestOptions } /** @@ -1878,17 +1809,19 @@ public void getDataSource() { } /** - * Code snippet for {@link SearchIndexerClient#getDataSourceConnectionWithResponse(String, Context)} + * Code snippet for {@link SearchIndexerClient#getDataSourceConnectionWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionWithResponse#String-RequestOptions + Response response = + SEARCH_INDEXER_CLIENT.getDataSourceConnectionWithResponse("dataSource", + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndexerDataSourceConnection dataSource = response.getValue() + .toObject(SearchIndexerDataSourceConnection.class); 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 + response.getStatusCode(), dataSource.getName()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.getDataSourceConnectionWithResponse#String-RequestOptions } @@ -1897,105 +1830,74 @@ public void getDataSourceWithResponse() { */ public void listDataSources() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listDataSourceConnections - PagedIterable dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnections(); - for (SearchIndexerDataSourceConnection dataSource: dataSources) { + ListDataSourcesResult dataSources = SEARCH_INDEXER_CLIENT.listDataSourceConnections(); + for (SearchIndexerDataSourceConnection dataSource: dataSources.getDataSources()) { 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#listDataSourceConnections(RequestOptions)} +// */ +// 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(); + List 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#listDataSourceConnectionNames()} +// */ +// 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#createOrUpdateDataSourceConnectionWithResponse(CreateOrUpdateDataSourceConnectionOptions, Context)} + * Code snippet for {@link SearchIndexerClient#createOrUpdateDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, RequestOptions)} */ public void createOrUpdateDataSourceWithResponse2() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse#CreateOrUpdateDataSourceConnectionOptions-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-RequestOptions SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); - CreateOrUpdateDataSourceConnectionOptions options = new CreateOrUpdateDataSourceConnectionOptions(dataSource) - .setOnlyIfUnchanged(true) - .setCacheResetRequirementsIgnored(true); + dataSource.getContainer().setQuery("newquery"); Response updateDataSource = SEARCH_INDEXER_CLIENT - .createOrUpdateDataSourceConnectionWithResponse(options, new Context(KEY_1, VALUE_1)); + .createOrUpdateDataSourceConnectionWithResponse(dataSource, new RequestOptions() + .setHeader(HttpHeaderName.IF_MATCH, dataSource.getETag()) + .addQueryParam("ignoreResetRequirements", "true") + .setContext(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#CreateOrUpdateDataSourceConnectionOptions-Context + // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-RequestOptions } /** @@ -2008,16 +1910,17 @@ public void deleteDataSource() { } /** - * Code snippet for {@link SearchIndexerClient#deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, boolean, Context)} + * Code snippet for {@link SearchIndexerClient#deleteDataSourceConnectionWithResponse(String, RequestOptions)} */ public void deleteDataSourceWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse#String-RequestOptions SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteDataSourceConnectionWithResponse(dataSource, true, - new Context(KEY_1, VALUE_1)); + Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteDataSourceConnectionWithResponse( + dataSource.getName(), new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, dataSource.getETag()) + .setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteDataSourceConnectionWithResponse#String-RequestOptions } /** @@ -2026,23 +1929,18 @@ public void deleteDataSourceWithResponse() { public void createSearchIndexerSkillset() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createSkillset#SearchIndexerSkillset List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); + new InputFieldMappingEntry("image").setSource("/document/normalized_images/*")); List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); + new OutputFieldMappingEntry("text").setTargetName("mytext"), + new OutputFieldMappingEntry("layoutText").setTargetName("myLayoutText")); SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) + new OcrSkill(inputs, outputs) .setShouldDetectOrientation(true) .setDefaultLanguageCode(null) .setName("myocr") .setDescription("Extracts text (plain and structured) from image.") - .setContext("/document/normalized_images/*"))); + .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()); @@ -2050,33 +1948,31 @@ public void createSearchIndexerSkillset() { } /** - * Code snippet for {@link SearchIndexerClient#createSkillsetWithResponse(SearchIndexerSkillset, Context)}. + * Code snippet for {@link SearchIndexerClient#createSkillsetWithResponse(BinaryData, RequestOptions)}. */ public void createSearchIndexerSkillsetWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse#SearchIndexerSkillset-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse#BinaryData-RequestOptions List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); + new InputFieldMappingEntry("image").setSource("/document/normalized_images/*")); List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); + new OutputFieldMappingEntry("text").setTargetName("mytext"), + new OutputFieldMappingEntry("layoutText").setTargetName("myLayoutText")); SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) + 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)); + .setContext("/document/normalized_images/*")); + Response response = + SEARCH_INDEXER_CLIENT.createSkillsetWithResponse(BinaryData.fromObject(searchIndexerSkillset), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + + SearchIndexerSkillset skillset = response.getValue().toObject(SearchIndexerSkillset.class); 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 + response.getStatusCode(), skillset.getName()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.createSkillsetWithResponse#BinaryData-RequestOptions } /** @@ -2092,16 +1988,17 @@ public void getSearchIndexerSkillset() { } /** - * Code snippet for {@link SearchIndexerClient#getSkillsetWithResponse(String, Context)} + * Code snippet for {@link SearchIndexerClient#getSkillsetWithResponse(String, RequestOptions)} */ 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)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetWithResponse#String-RequestOptions + Response response = SEARCH_INDEXER_CLIENT.getSkillsetWithResponse( + "searchIndexerSkillset", new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchIndexerSkillset skillset = response.getValue().toObject(SearchIndexerSkillset.class); 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 + response.getStatusCode(), skillset.getName()); + // END: com.azure.search.documents.indexes.SearchIndexerClient.getSkillsetWithResponse#String-RequestOptions } @@ -2110,56 +2007,53 @@ public void getSearchIndexerSkillsetWithResponse() { */ public void listIndexerSkillset() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsets - PagedIterable indexerSkillsets = SEARCH_INDEXER_CLIENT.listSkillsets(); - for (SearchIndexerSkillset skillset: indexerSkillsets) { + ListSkillsetsResult indexerSkillsets = SEARCH_INDEXER_CLIENT.listSkillsets(); + for (SearchIndexerSkillset skillset: indexerSkillsets.getSkillsets()) { 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#listSkillsets(RequestOptions)} +// */ +// 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(); + List 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#listSkillsetNames()} +// */ +// public void listIndexerSkillsetNamesWithContext() { +// // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.listSkillsetNamesWithResponse#Context +// List 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.listSkillsetNamesWithResponse#Context +// } /** * Code snippet for {@link SearchIndexerClient#createOrUpdateSkillset(SearchIndexerSkillset)} @@ -2175,39 +2069,23 @@ public void createOrUpdateIndexerSkillset() { } /** - * 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#createOrUpdateSkillsetWithResponse(CreateOrUpdateSkillsetOptions, Context)} + * Code snippet for {@link SearchIndexerClient#createOrUpdateSkillsetWithResponse(SearchIndexerSkillset, RequestOptions)} */ public void createOrUpdateIndexerSkillsetWithResponse2() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse#CreateOrUpdateSkillsetOptions-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-RequestOptions SearchIndexerSkillset indexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); indexerSkillset.setDescription("This is new description!"); - CreateOrUpdateSkillsetOptions options = new CreateOrUpdateSkillsetOptions(indexerSkillset) - .setOnlyIfUnchanged(true) - .setCacheReprocessingChangeDetectionDisabled(false) - .setCacheResetRequirementsIgnored(true); - Response updateSkillsetResponse = SEARCH_INDEXER_CLIENT.createOrUpdateSkillsetWithResponse( - options, new Context(KEY_1, VALUE_1)); + Response updateSkillsetResponse = SEARCH_INDEXER_CLIENT + .createOrUpdateSkillsetWithResponse(indexerSkillset, new RequestOptions() + .setHeader(HttpHeaderName.IF_MATCH, indexerSkillset.getETag()) + .addQueryParam("ignoreResetRequirements", "true") + .addQueryParam("disableCacheReprocessingChangeDetection", "false") + .setContext(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#CreateOrUpdateSkillsetOptions-Context + // END: com.azure.search.documents.indexes.SearchIndexerClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-RequestOptions } /** @@ -2220,15 +2098,17 @@ public void deleteSearchIndexerSkillset() { } /** - * Code snippet for {@link SearchIndexerClient#deleteSkillsetWithResponse(SearchIndexerSkillset, boolean, Context)} + * Code snippet for {@link SearchIndexerClient#deleteSkillsetWithResponse(String, RequestOptions)} */ public void deleteSearchIndexerSkillsetWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse#String-RequestOptions SearchIndexerSkillset searchIndexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); - Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset, true, - new Context(KEY_1, VALUE_1)); + Response deleteResponse = SEARCH_INDEXER_CLIENT.deleteSkillsetWithResponse( + searchIndexerSkillset.getName(), new RequestOptions() + .setHeader(HttpHeaderName.IF_MATCH, searchIndexerSkillset.getETag()) + .setContext(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 + // END: com.azure.search.documents.indexes.SearchIndexerClient.deleteSkillsetWithResponse#String-RequestOptions } private static final SearchIndexerAsyncClient SEARCH_INDEXER_ASYNC_CLIENT = new SearchIndexerClientBuilder() @@ -2261,17 +2141,20 @@ public void createSearchIndexerAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#createIndexerWithResponse(SearchIndexer)}. + * Code snippet for {@link SearchIndexerAsyncClient#createIndexerWithResponse(BinaryData, RequestOptions)}. */ public void createSearchIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse#SearchIndexer + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse#BinaryData-RequestOptions SearchIndexer searchIndexer = new SearchIndexer("searchIndexer", "dataSource", "searchIndex"); - SEARCH_INDEXER_ASYNC_CLIENT.createIndexerWithResponse(searchIndexer) - .subscribe(indexerFromServiceResponse -> + SEARCH_INDEXER_ASYNC_CLIENT.createIndexerWithResponse(BinaryData.fromObject(searchIndexer), + new RequestOptions()) + .subscribe(response -> { + SearchIndexer indexer = response.getValue().toObject(SearchIndexer.class); 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 + response.getStatusCode(), indexer.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse#BinaryData-RequestOptions } /** @@ -2287,15 +2170,17 @@ public void getSearchIndexerAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#getIndexerWithResponse(String)}} + * Code snippet for {@link SearchIndexerAsyncClient#getIndexerWithResponse(String, RequestOptions)}} */ public void getSearchIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getIndexerWithResponse("searchIndexer") - .subscribe(indexerFromServiceResponse -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse#String-RequestOptions + SEARCH_INDEXER_ASYNC_CLIENT.getIndexerWithResponse("searchIndexer", new RequestOptions()) + .subscribe(response -> { + SearchIndexer indexer = response.getValue().toObject(SearchIndexer.class); 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 + response.getStatusCode(), indexer.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse#String-RequestOptions } @@ -2305,9 +2190,9 @@ public void getSearchIndexerWithResponseAsync() { public void listIndexersAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexers SEARCH_INDEXER_ASYNC_CLIENT.listIndexers() - .subscribe(indexer -> + .subscribe(result -> result.getIndexers().forEach(indexer -> System.out.printf("The indexer name is %s. The ETag of indexer is %s.%n", indexer.getName(), - indexer.getETag())); + indexer.getETag()))); // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexers } @@ -2339,45 +2224,25 @@ public void createOrUpdateIndexerAsync() { } /** - * 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#createOrUpdateIndexerWithResponse(CreateOrUpdateIndexerOptions)} + * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateIndexerWithResponse(SearchIndexer, RequestOptions)} */ public void createOrUpdateIndexerWithResponseAsync2() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse#CreateOrUpdateIndexerOptions + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse#SearchIndexer-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") .flatMap(searchIndexerFromService -> { searchIndexerFromService.setFieldMappings(Collections.singletonList( new FieldMapping("hotelName").setTargetFieldName("HotelName"))); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexerWithResponse( - new CreateOrUpdateIndexerOptions(searchIndexerFromService) - .setOnlyIfUnchanged(true) - .setCacheReprocessingChangeDetectionDisabled(false) - .setCacheResetRequirementsIgnored(true)); + return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateIndexerWithResponse(searchIndexerFromService, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchIndexerFromService.getETag()) + .addQueryParam("ignoreResetRequirements", "true") + .addQueryParam("disableCacheReprocessingChangeDetection", "false")); }) .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#CreateOrUpdateIndexerOptions + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse#SearchIndexer-RequestOptions } /** @@ -2391,16 +2256,17 @@ public void deleteSearchIndexerAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteIndexerWithResponse(SearchIndexer, boolean)} + * Code snippet for {@link SearchIndexerAsyncClient#deleteIndexerWithResponse(String, RequestOptions)} */ public void deleteSearchIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse#SearchIndexer-boolean + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse#String-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") .flatMap(searchIndexer -> - SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexerWithResponse(searchIndexer, true)) + SEARCH_INDEXER_ASYNC_CLIENT.deleteIndexerWithResponse(searchIndexer.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchIndexer.getETag()))) .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 + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse#String-RequestOptions } /** @@ -2414,14 +2280,14 @@ public void resetIndexerAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#resetIndexerWithResponse(String)} + * Code snippet for {@link SearchIndexerAsyncClient#resetIndexerWithResponse(String, RequestOptions)} */ public void resetIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.resetIndexerWithResponse("searchIndexer") + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String-RequestOptions + SEARCH_INDEXER_ASYNC_CLIENT.resetIndexerWithResponse("searchIndexer", new RequestOptions()) .subscribe(response -> System.out.println("The status code of the response is " + response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String-RequestOptions } /** @@ -2435,14 +2301,14 @@ public void runIndexerAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#runIndexerWithResponse(String)} + * Code snippet for {@link SearchIndexerAsyncClient#runIndexerWithResponse(String, RequestOptions)} */ public void runIndexerWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.runIndexerWithResponse("searchIndexer") + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String-RequestOptions + SEARCH_INDEXER_ASYNC_CLIENT.runIndexerWithResponse("searchIndexer", new RequestOptions()) .subscribe(response -> System.out.println("The status code of the response is " + response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String-RequestOptions } /** @@ -2457,50 +2323,56 @@ public void getIndexerStatusAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#getIndexerStatusWithResponse(String)} + * Code snippet for {@link SearchIndexerAsyncClient#getIndexerStatusWithResponse(String, RequestOptions)} */ public void getIndexerStatusWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getIndexerStatusWithResponse("searchIndexer") - .subscribe(response -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse#String-RequestOptions + SEARCH_INDEXER_ASYNC_CLIENT.getIndexerStatusWithResponse("searchIndexer", new RequestOptions()) + .subscribe(response -> { + SearchIndexerStatus status = response.getValue().toObject(SearchIndexerStatus.class); 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 + response.getStatusCode(), status.getStatus()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse#String-RequestOptions } /** - * Code snippet for {@link SearchIndexerAsyncClient#resetDocuments(String, Boolean, List, List)} + * Code snippet for {@link SearchIndexerAsyncClient#resetDocuments(String, Boolean, DocumentKeysOrIds)} */ public void resetDocumentsAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocuments#String-Boolean-List-List + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocuments#String-Boolean-DocumentKeysOrIds // Reset the documents with keys 1234 and 4321. - SEARCH_INDEXER_ASYNC_CLIENT.resetDocuments("searchIndexer", false, Arrays.asList("1234", "4321"), null) + SEARCH_INDEXER_ASYNC_CLIENT.resetDocuments("searchIndexer", false, + new DocumentKeysOrIds().setDocumentKeys("1234", "4321")) // Clear the previous documents to be reset and replace them with documents 1235 and 5231. - .then(SEARCH_INDEXER_ASYNC_CLIENT.resetDocuments("searchIndexer", true, Arrays.asList("1235", "5321"), null)) + .then(SEARCH_INDEXER_ASYNC_CLIENT.resetDocuments("searchIndexer", true, + new DocumentKeysOrIds().setDocumentKeys("1235", "5321"))) .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocuments#String-Boolean-List-List + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocuments#String-Boolean-DocumentKeysOrIds } /** - * Code snippet for {@link SearchIndexerAsyncClient#resetDocumentsWithResponse(SearchIndexer, Boolean, List, List)} + * Code snippet for {@link SearchIndexerAsyncClient#resetDocumentsWithResponse(String, RequestOptions)} */ public void resetDocumentsWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocumentsWithResponse#SearchIndexer-Boolean-List-List + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocumentsWithResponse#String-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getIndexer("searchIndexer") - .flatMap(searchIndexer -> SEARCH_INDEXER_ASYNC_CLIENT.resetDocumentsWithResponse(searchIndexer, false, - Arrays.asList("1234", "4321"), null) + .flatMap(searchIndexer -> SEARCH_INDEXER_ASYNC_CLIENT.resetDocumentsWithResponse(searchIndexer.getName(), + new RequestOptions().addQueryParam("overwrite", "false") + .setBody(BinaryData.fromObject(new DocumentKeysOrIds().setDocumentKeys("1234", "4321")))) .flatMap(resetDocsResult -> { System.out.printf("Requesting documents to be reset completed with status code %d.%n", resetDocsResult.getStatusCode()); // Clear the previous documents to be reset and replace them with documents 1235 and 5231. - return SEARCH_INDEXER_ASYNC_CLIENT.resetDocumentsWithResponse(searchIndexer, true, - Arrays.asList("1235", "5321"), null); + return SEARCH_INDEXER_ASYNC_CLIENT.resetDocumentsWithResponse(searchIndexer.getName(), + new RequestOptions().addQueryParam("overwrite", "true") + .setBody(BinaryData.fromObject(new DocumentKeysOrIds().setDocumentKeys("1235", "5321")))); })) .subscribe(resetDocsResult -> System.out.printf("Overwriting the documents to be reset completed with status code %d.%n", resetDocsResult.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocumentsWithResponse#SearchIndexer-Boolean-List-List + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetDocumentsWithResponse#String-RequestOptions } /** @@ -2509,8 +2381,9 @@ public void resetDocumentsWithResponseAsync() { 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")); + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString("{connectionString}"), + new 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", @@ -2519,18 +2392,23 @@ public void createDataSourceAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#createDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection)}. + * Code snippet for {@link SearchIndexerAsyncClient#createDataSourceConnectionWithResponse(BinaryData, RequestOptions)}. */ public void createDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse#BinaryData-RequestOptions SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("dataSource", - SearchIndexerDataSourceType.AZURE_BLOB, "{connectionString}", + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString("{connectionString}"), new SearchIndexerDataContainer("container")); - SEARCH_INDEXER_ASYNC_CLIENT.createDataSourceConnectionWithResponse(dataSource) - .subscribe(dataSourceFromService -> + SEARCH_INDEXER_ASYNC_CLIENT.createDataSourceConnectionWithResponse(BinaryData.fromObject(dataSource), + new RequestOptions()) + .subscribe(response -> { + SearchIndexerDataSourceConnection responseDataSource = response.getValue() + .toObject(SearchIndexerDataSourceConnection.class); 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 + response.getStatusCode(), responseDataSource.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse#BinaryData-RequestOptions } /** @@ -2546,15 +2424,18 @@ public void getDataSourceAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#getDataSourceConnectionWithResponse(String)} + * Code snippet for {@link SearchIndexerAsyncClient#getDataSourceConnectionWithResponse(String, RequestOptions)} */ public void getDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnectionWithResponse("dataSource") - .subscribe(dataSource -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse#String-RequestOptions + SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnectionWithResponse("dataSource", new RequestOptions()) + .subscribe(response -> { + SearchIndexerDataSourceConnection dataSource = response.getValue() + .toObject(SearchIndexerDataSourceConnection.class); 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 + response.getStatusCode(), dataSource.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse#String-RequestOptions } @@ -2564,10 +2445,9 @@ public void getDataSourceWithResponseAsync() { public void listDataSourcesAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnections SEARCH_INDEXER_ASYNC_CLIENT.listDataSourceConnections() - .subscribe(dataSource -> + .subscribe(result -> result.getDataSources().forEach(dataSource -> System.out.printf("The dataSource name is %s. The ETag of dataSource is %s.%n", - dataSource.getName(), dataSource.getETag()) - ); + dataSource.getName(), dataSource.getETag()))); // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnections } @@ -2587,7 +2467,7 @@ public void listDataSourceNamesAsync() { public void createOrUpdateDataSourceAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection SearchIndexerDataSourceConnection dataSource = SEARCH_INDEXER_CLIENT.getDataSourceConnection("dataSource"); - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); + dataSource.getContainer().setQuery("newquery"); SearchIndexerDataSourceConnection updateDataSource = SEARCH_INDEXER_CLIENT .createOrUpdateDataSourceConnection(dataSource); @@ -2597,40 +2477,22 @@ public void createOrUpdateDataSourceAsync() { } /** - * 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#createOrUpdateDataSourceConnectionWithResponse(CreateOrUpdateDataSourceConnectionOptions)} + * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, RequestOptions)} */ public void createOrUpdateDataSourceWithResponseAsync2() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse#CreateOrUpdateDataSourceConnectionOptions + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource") .flatMap(dataSource -> { - dataSource.setContainer(new SearchIndexerDataContainer("updatecontainer")); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateDataSourceConnectionWithResponse( - new CreateOrUpdateDataSourceConnectionOptions(dataSource) - .setOnlyIfUnchanged(true) - .setCacheResetRequirementsIgnored(true)); + dataSource.getContainer().setQuery("newquery"); + return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateDataSourceConnectionWithResponse(dataSource, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, dataSource.getETag()) + .addQueryParam("ignoreResetRequirements", "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#CreateOrUpdateDataSourceConnectionOptions + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-RequestOptions } /** @@ -2644,15 +2506,16 @@ public void deleteDataSourceAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection, boolean)} + * Code snippet for {@link SearchIndexerAsyncClient#deleteDataSourceConnectionWithResponse(String, RequestOptions)} */ public void deleteDataSourceWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse#String-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getDataSourceConnection("dataSource") - .flatMap(dataSource -> SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnectionWithResponse(dataSource, true)) + .flatMap(dataSource -> SEARCH_INDEXER_ASYNC_CLIENT.deleteDataSourceConnectionWithResponse( + dataSource.getName(), new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, dataSource.getETag()))) .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 + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse#String-RequestOptions } /** @@ -2661,16 +2524,11 @@ public void deleteDataSourceWithResponseAsync() { public void createSearchIndexerSkillsetAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillset#SearchIndexerSkillset List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); + new InputFieldMappingEntry("image").setSource("/document/normalized_images/*")); List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); + new OutputFieldMappingEntry("text").setTargetName("mytext"), + new OutputFieldMappingEntry("layoutText").setTargetName("myLayoutText")); SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", Collections.singletonList(new OcrSkill(inputs, outputs) .setShouldDetectOrientation(true) @@ -2686,33 +2544,31 @@ public void createSearchIndexerSkillsetAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#createSkillsetWithResponse(SearchIndexerSkillset)}. + * Code snippet for {@link SearchIndexerAsyncClient#createSkillsetWithResponse(BinaryData, RequestOptions)}. */ public void createSearchIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse#SearchIndexerSkillset + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse#BinaryData-RequestOptions List inputs = Collections.singletonList( - new InputFieldMappingEntry("image") - .setSource("/document/normalized_images/*") - ); + new InputFieldMappingEntry("image").setSource("/document/normalized_images/*")); List outputs = Arrays.asList( - new OutputFieldMappingEntry("text") - .setTargetName("mytext"), - new OutputFieldMappingEntry("layoutText") - .setTargetName("myLayoutText") - ); + new OutputFieldMappingEntry("text").setTargetName("mytext"), + new OutputFieldMappingEntry("layoutText").setTargetName("myLayoutText")); SearchIndexerSkillset searchIndexerSkillset = new SearchIndexerSkillset("searchIndexerSkillset", - Collections.singletonList(new OcrSkill(inputs, outputs) + 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 -> + .setContext("/document/normalized_images/*")); + SEARCH_INDEXER_ASYNC_CLIENT.createSkillsetWithResponse(BinaryData.fromObject(searchIndexerSkillset), + new RequestOptions()) + .subscribe(response -> { + SearchIndexerSkillset skillset = response.getValue().toObject(SearchIndexerSkillset.class); 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 + response.getStatusCode(), skillset.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse#BinaryData-RequestOptions } /** @@ -2728,15 +2584,17 @@ public void getSearchIndexerSkillsetAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#getSkillsetWithResponse(String)} + * Code snippet for {@link SearchIndexerAsyncClient#getSkillsetWithResponse(String, RequestOptions)} */ public void getSearchIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse#String - SEARCH_INDEXER_ASYNC_CLIENT.getSkillsetWithResponse("searchIndexerSkillset") - .subscribe(skillsetWithResponse -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse#String-RequestOptions + SEARCH_INDEXER_ASYNC_CLIENT.getSkillsetWithResponse("searchIndexerSkillset", new RequestOptions()) + .subscribe(response -> { + SearchIndexerSkillset skillset = response.getValue().toObject(SearchIndexerSkillset.class); 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 + response.getStatusCode(), skillset.getName()); + }); + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse#String-RequestOptions } /** @@ -2745,9 +2603,9 @@ public void getSearchIndexerSkillsetWithResponseAsync() { public void listIndexerSkillsetAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsets SEARCH_INDEXER_ASYNC_CLIENT.listSkillsets() - .subscribe(skillset -> + .subscribe(result -> result.getSkillsets().forEach(skillset -> System.out.printf("The skillset name is %s. The ETag of skillset is %s.%n", skillset.getName(), - skillset.getETag())); + skillset.getETag()))); // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsets } @@ -2777,43 +2635,24 @@ public void createOrUpdateIndexerSkillsetAsync() { } /** - * 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#createOrUpdateSkillsetWithResponse(CreateOrUpdateSkillsetOptions)} + * Code snippet for {@link SearchIndexerAsyncClient#createOrUpdateSkillsetWithResponse(SearchIndexerSkillset, RequestOptions)} */ public void createOrUpdateIndexerSkillsetWithResponseAsync2() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse#CreateOrUpdateSkillsetOptions + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") .flatMap(indexerSkillset -> { indexerSkillset.setDescription("This is new description!"); - return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateSkillsetWithResponse( - new CreateOrUpdateSkillsetOptions(indexerSkillset) - .setOnlyIfUnchanged(true) - .setCacheReprocessingChangeDetectionDisabled(false) - .setCacheResetRequirementsIgnored(true)); + return SEARCH_INDEXER_ASYNC_CLIENT.createOrUpdateSkillsetWithResponse(indexerSkillset, + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, indexerSkillset.getETag()) + .addQueryParam("ignoreResetRequirements", "true") + .addQueryParam("disableCacheReprocessingChangeDetection", "false")); }) .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#CreateOrUpdateSkillsetOptions + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-RequestOptions } /** @@ -2827,64 +2666,70 @@ public void deleteSearchIndexerSkillsetAsync() { } /** - * Code snippet for {@link SearchIndexerAsyncClient#deleteSkillsetWithResponse(SearchIndexerSkillset, boolean)} + * Code snippet for {@link SearchIndexerAsyncClient#deleteSkillsetWithResponse(String, RequestOptions)} */ public void deleteSearchIndexerSkillsetWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse#String-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") .flatMap(searchIndexerSkillset -> - SEARCH_INDEXER_ASYNC_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset, true)) + SEARCH_INDEXER_ASYNC_CLIENT.deleteSkillsetWithResponse(searchIndexerSkillset.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchIndexerSkillset.getETag()))) .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 + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse#String-RequestOptions } /** - * Code snippet for {@link SearchIndexerClient#resetSkills(String, List)} + * Code snippet for {@link SearchIndexerClient#resetSkills(String, SkillNames)} */ public void resetSkills() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetSkills#String-List + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetSkills#String-SkillNames // Reset the "myOcr" and "myText" skills. - SEARCH_INDEXER_CLIENT.resetSkills("searchIndexerSkillset", Arrays.asList("myOcr", "myText")); - // END: com.azure.search.documents.indexes.SearchIndexerClient.resetSkills#String-List + SEARCH_INDEXER_CLIENT.resetSkills("searchIndexerSkillset", new SkillNames().setSkillNames("myOcr", "myText")); + // END: com.azure.search.documents.indexes.SearchIndexerClient.resetSkills#String-SkillNames } /** - * Code snippet for {@link SearchIndexerClient#resetSkillsWithResponse(SearchIndexerSkillset, List, Context)} + * Code snippet for {@link SearchIndexerClient#resetSkillsWithResponse(String, BinaryData, RequestOptions)} */ public void resetSkillsWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetSkillsWithResponse#SearchIndexerSkillset-List-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexerClient.resetSkillsWithResponse#String-BinaryData-RequestOptions SearchIndexerSkillset searchIndexerSkillset = SEARCH_INDEXER_CLIENT.getSkillset("searchIndexerSkillset"); // Reset the "myOcr" and "myText" skills. - Response resetSkillsResponse = SEARCH_INDEXER_CLIENT.resetSkillsWithResponse(searchIndexerSkillset, - Arrays.asList("myOcr", "myText"), new Context(KEY_1, VALUE_1)); + Response resetSkillsResponse = SEARCH_INDEXER_CLIENT.resetSkillsWithResponse( + searchIndexerSkillset.getName(), + BinaryData.fromObject(new SkillNames().setSkillNames("myOcr", "myText")), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); System.out.printf("Resetting skills completed with status code %d.%n", resetSkillsResponse.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexerClient.resetSkillsWithResponse#SearchIndexerSkillset-List-Context + // END: com.azure.search.documents.indexes.SearchIndexerClient.resetSkillsWithResponse#String-BinaryData-RequestOptions } /** - * Code snippet for {@link SearchIndexerAsyncClient#resetSkills(String, List)} + * Code snippet for {@link SearchIndexerAsyncClient#resetSkills(String, SkillNames)} */ public void resetSkillsAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkills#String-List + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkills#String-SkillNames // Reset the "myOcr" and "myText" skills. - SEARCH_INDEXER_ASYNC_CLIENT.resetSkills("searchIndexerSkillset", Arrays.asList("myOcr", "myText")) + SEARCH_INDEXER_ASYNC_CLIENT.resetSkills("searchIndexerSkillset", + new SkillNames().setSkillNames("myOcr", "myText")) .subscribe(); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkills#String-List + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkills#String-SkillNames } /** - * Code snippet for {@link SearchIndexerAsyncClient#resetSkillsWithResponse(SearchIndexerSkillset, List)} + * Code snippet for {@link SearchIndexerAsyncClient#resetSkillsWithResponse(String, BinaryData, RequestOptions)} */ public void resetSkillsWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkillsWithResponse#SearchIndexerSkillset-List + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkillsWithResponse#String-BinaryData-RequestOptions SEARCH_INDEXER_ASYNC_CLIENT.getSkillset("searchIndexerSkillset") - .flatMap(searchIndexerSkillset -> SEARCH_INDEXER_ASYNC_CLIENT.resetSkillsWithResponse(searchIndexerSkillset, - Arrays.asList("myOcr", "myText"))) + .flatMap(searchIndexerSkillset -> SEARCH_INDEXER_ASYNC_CLIENT.resetSkillsWithResponse( + searchIndexerSkillset.getName(), + BinaryData.fromObject(new SkillNames().setSkillNames("myOcr", "myText")), + new RequestOptions())) .subscribe(resetSkillsResponse -> System.out.printf("Resetting skills completed with status code %d.%n", resetSkillsResponse.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkillsWithResponse#SearchIndexerSkillset-List + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetSkillsWithResponse#String-BinaryData-RequestOptions } /** @@ -2892,23 +2737,25 @@ public void resetSkillsWithResponseAsync() { */ public void createAliasAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createAlias#SearchAlias - SEARCH_INDEX_ASYNC_CLIENT.createAlias(new SearchAlias("my-alias", Collections.singletonList("index-to-alias"))) + SEARCH_INDEX_ASYNC_CLIENT.createAlias(new SearchAlias("my-alias", "index-to-alias")) .subscribe(searchAlias -> System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(), searchAlias.getIndexes().get(0))); // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createAlias#SearchAlias } /** - * Code snippet for {@link SearchIndexAsyncClient#createAliasWithResponse(SearchAlias)}. + * Code snippet for {@link SearchIndexAsyncClient#createAliasWithResponse(BinaryData, RequestOptions)}. */ public void createAliasWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createAliasWithResponse#SearchAlias - SEARCH_INDEX_ASYNC_CLIENT.createAliasWithResponse(new SearchAlias("my-alias", - Collections.singletonList("index-to-alias"))) - .subscribe(response -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createAliasWithResponse#BinaryData-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.createAliasWithResponse( + BinaryData.fromObject(new SearchAlias("my-alias", "index-to-alias")), new RequestOptions()) + .subscribe(response -> { + SearchAlias searchAlias = response.getValue().toObject(SearchAlias.class); System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.", - response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0))); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createAliasWithResponse#SearchAlias + response.getStatusCode(), searchAlias.getName(), searchAlias.getIndexes().get(0)); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createAliasWithResponse#BinaryData-RequestOptions } /** @@ -2916,24 +2763,25 @@ public void createAliasWithResponseAsync() { */ public void createAlias() { // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createAlias#SearchAlias - SearchAlias searchAlias = SEARCH_INDEX_CLIENT.createAlias(new SearchAlias("my-alias", - Collections.singletonList("index-to-alias"))); + SearchAlias searchAlias = SEARCH_INDEX_CLIENT.createAlias(new SearchAlias("my-alias", "index-to-alias")); System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(), searchAlias.getIndexes().get(0)); // END: com.azure.search.documents.indexes.SearchIndexClient.createAlias#SearchAlias } /** - * Code snippet for {@link SearchIndexClient#createAliasWithResponse(SearchAlias, Context)}. + * Code snippet for {@link SearchIndexClient#createAliasWithResponse(BinaryData, RequestOptions)}. */ public void createAliasWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createAliasWithResponse#SearchAlias-Context - Response response = SEARCH_INDEX_CLIENT.createAliasWithResponse(new SearchAlias("my-alias", - Collections.singletonList("index-to-alias")), new Context(KEY_1, VALUE_1)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createAliasWithResponse#BinaryData-RequestOptions + Response response = SEARCH_INDEX_CLIENT.createAliasWithResponse( + BinaryData.fromObject(new SearchAlias("my-alias", "index-to-alias")), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchAlias searchAlias = response.getValue().toObject(SearchAlias.class); System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.", - response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)); - // END: com.azure.search.documents.indexes.SearchIndexClient.createAliasWithResponse#SearchAlias-Context + response.getStatusCode(), searchAlias.getName(), searchAlias.getIndexes().get(0)); + // END: com.azure.search.documents.indexes.SearchIndexClient.createAliasWithResponse#BinaryData-RequestOptions } @@ -2942,37 +2790,37 @@ public void createAliasWithResponse() { */ public void createOrUpdateAliasAsync() { // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAlias#SearchAlias - SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAlias( - new SearchAlias("my-alias", Collections.singletonList("index-to-alias"))) + SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAlias(new SearchAlias("my-alias", "index-to-alias")) .flatMap(searchAlias -> { System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(), searchAlias.getIndexes().get(0)); return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAlias(new SearchAlias(searchAlias.getName(), - Collections.singletonList("new-index-to-alias"))); + "new-index-to-alias")); }).subscribe(searchAlias -> System.out.printf("Updated alias '%s' to aliases index '%s'.", searchAlias.getName(), searchAlias.getIndexes().get(0))); // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAlias#SearchAlias } /** - * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateAliasWithResponse(SearchAlias, boolean)}. + * Code snippet for {@link SearchIndexAsyncClient#createOrUpdateAliasWithResponse(SearchAlias, RequestOptions)}. */ public void createOrUpdateAliasWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAliasWithResponse#SearchAlias-boolean - SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAliasWithResponse( - new SearchAlias("my-alias", Collections.singletonList("index-to-alias")), false) + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAliasWithResponse#SearchAlias-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAliasWithResponse(new SearchAlias("my-alias", "index-to-alias"), + new RequestOptions()) .flatMap(response -> { System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.", response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)); return SEARCH_INDEX_ASYNC_CLIENT.createOrUpdateAliasWithResponse( - new SearchAlias(response.getValue().getName(), Collections.singletonList("new-index-to-alias")) - .setETag(response.getValue().getETag()), true); + new SearchAlias(response.getValue().getName(), "new-index-to-alias") + .setETag(response.getValue().getETag()), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, response.getValue().getETag())); }).subscribe(response -> System.out.printf("Response status code %d. Updated alias '%s' that aliases index '%s'.", response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0))); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAliasWithResponse#SearchAlias-boolean + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.createOrUpdateAliasWithResponse#SearchAlias-RequestOptions } /** @@ -2981,13 +2829,13 @@ public void createOrUpdateAliasWithResponseAsync() { public void createOrUpdateAlias() { // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAlias#SearchAlias SearchAlias searchAlias = SEARCH_INDEX_CLIENT.createOrUpdateAlias( - new SearchAlias("my-alias", Collections.singletonList("index-to-alias"))); + new SearchAlias("my-alias", "index-to-alias")); System.out.printf("Created alias '%s' that aliases index '%s'.", searchAlias.getName(), searchAlias.getIndexes().get(0)); searchAlias = SEARCH_INDEX_CLIENT.createOrUpdateAlias(new SearchAlias(searchAlias.getName(), - Collections.singletonList("new-index-to-alias"))); + "new-index-to-alias")); System.out.printf("Updated alias '%s' to aliases index '%s'.", searchAlias.getName(), searchAlias.getIndexes().get(0)); @@ -2995,23 +2843,26 @@ public void createOrUpdateAlias() { } /** - * Code snippet for {@link SearchIndexClient#createOrUpdateAliasWithResponse(SearchAlias, boolean, Context)}. + * Code snippet for {@link SearchIndexClient#createOrUpdateAliasWithResponse(SearchAlias, RequestOptions)}. */ public void createOrUpdateAliasWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAliasWithResponse#SearchAlias-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAliasWithResponse#SearchAlias-RequestOptions Response response = SEARCH_INDEX_CLIENT.createOrUpdateAliasWithResponse( - new SearchAlias("my-alias", Collections.singletonList("index-to-alias")), false, new Context(KEY_1, VALUE_1)); + new SearchAlias("my-alias", "index-to-alias"), + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); System.out.printf("Response status code %d. Created alias '%s' that aliases index '%s'.", response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)); response = SEARCH_INDEX_CLIENT.createOrUpdateAliasWithResponse( - new SearchAlias(response.getValue().getName(), Collections.singletonList("new-index-to-alias")) - .setETag(response.getValue().getETag()), true, new Context(KEY_1, VALUE_1)); + new SearchAlias(response.getValue().getName(), "new-index-to-alias") + .setETag(response.getValue().getETag()), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, response.getValue().getETag()) + .setContext(new Context(KEY_1, VALUE_1))); System.out.printf("Response status code %d. Updated alias '%s' that aliases index '%s'.", response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)); - // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAliasWithResponse#SearchAlias-boolean-Context + // END: com.azure.search.documents.indexes.SearchIndexClient.createOrUpdateAliasWithResponse#SearchAlias-RequestOptions } /** @@ -3026,15 +2877,17 @@ public void getAliasAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#getAliasWithResponse(String)}. + * Code snippet for {@link SearchIndexAsyncClient#getAliasWithResponse(String, RequestOptions)}. */ public void getAliasWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getAliasWithResponse#String - SEARCH_INDEX_ASYNC_CLIENT.getAliasWithResponse("my-alias") - .subscribe(response -> + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.getAliasWithResponse#String-RequestOptions + SEARCH_INDEX_ASYNC_CLIENT.getAliasWithResponse("my-alias", new RequestOptions()) + .subscribe(response -> { + SearchAlias searchAlias = response.getValue().toObject(SearchAlias.class); System.out.printf("Response status code %d. Retrieved alias '%s' that aliases index '%s'.", - response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0))); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getAliasWithResponse#String + response.getStatusCode(), searchAlias.getName(), searchAlias.getIndexes().get(0)); + }); + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.getAliasWithResponse#String-RequestOptions } /** @@ -3050,15 +2903,17 @@ public void getAlias() { } /** - * Code snippet for {@link SearchIndexClient#getAliasWithResponse(String, Context)}. + * Code snippet for {@link SearchIndexClient#getAliasWithResponse(String, RequestOptions)}. */ public void getAliasWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getAliasWithResponse#String-Context - Response response = SEARCH_INDEX_CLIENT.getAliasWithResponse("my-alias", new Context(KEY_1, VALUE_1)); + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.getAliasWithResponse#String-RequestOptions + Response response = SEARCH_INDEX_CLIENT.getAliasWithResponse("my-alias", + new RequestOptions().setContext(new Context(KEY_1, VALUE_1))); + SearchAlias searchAlias = response.getValue().toObject(SearchAlias.class); System.out.printf("Response status code %d. Retrieved alias '%s' that aliases index '%s'.", - response.getStatusCode(), response.getValue().getName(), response.getValue().getIndexes().get(0)); - // END: com.azure.search.documents.indexes.SearchIndexClient.getAliasWithResponse#String-Context + response.getStatusCode(), searchAlias.getName(), searchAlias.getIndexes().get(0)); + // END: com.azure.search.documents.indexes.SearchIndexClient.getAliasWithResponse#String-RequestOptions } /** @@ -3072,15 +2927,16 @@ public void deleteAliasAsync() { } /** - * Code snippet for {@link SearchIndexAsyncClient#deleteAliasWithResponse(SearchAlias, boolean)}. + * Code snippet for {@link SearchIndexAsyncClient#deleteAliasWithResponse(String, RequestOptions)}. */ public void deleteAliasWithResponseAsync() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAliasWithResponse#SearchAlias-boolean + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAliasWithResponse#String-RequestOptions SEARCH_INDEX_ASYNC_CLIENT.getAlias("my-alias") - .flatMap(searchAlias -> SEARCH_INDEX_ASYNC_CLIENT.deleteAliasWithResponse(searchAlias, true)) + .flatMap(searchAlias -> SEARCH_INDEX_ASYNC_CLIENT.deleteAliasWithResponse(searchAlias.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchAlias.getETag()))) .subscribe(response -> System.out.printf("Response status code %d. Deleted alias 'my-alias'.", response.getStatusCode())); - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAliasWithResponse#SearchAlias-boolean + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient.deleteAliasWithResponse#String-RequestOptions } /** @@ -3095,17 +2951,18 @@ public void deleteAlias() { } /** - * Code snippet for {@link SearchIndexClient#deleteAliasWithResponse(SearchAlias, boolean, Context)}. + * Code snippet for {@link SearchIndexClient#deleteAliasWithResponse(String, RequestOptions)}. */ public void deleteAliasWithResponse() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteAliasWithResponse#SearchAlias-boolean-Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.deleteAliasWithResponse#String-RequestOptions SearchAlias searchAlias = SEARCH_INDEX_CLIENT.getAlias("my-alias"); - Response response = SEARCH_INDEX_CLIENT.deleteAliasWithResponse(searchAlias, true, - new Context(KEY_1, VALUE_1)); + Response response = SEARCH_INDEX_CLIENT.deleteAliasWithResponse(searchAlias.getName(), + new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, searchAlias.getETag()) + .setContext(new Context(KEY_1, VALUE_1))); System.out.printf("Response status code %d. Deleted alias 'my-alias'.", response.getStatusCode()); - // END: com.azure.search.documents.indexes.SearchIndexClient.deleteAliasWithResponse#SearchAlias-boolean-Context + // END: com.azure.search.documents.indexes.SearchIndexClient.deleteAliasWithResponse#String-RequestOptions } /** @@ -3132,13 +2989,16 @@ public void listAliases() { } /** - * Code snippet for {@link SearchIndexClient#listAliases(Context)}. + * Code snippet for {@link SearchIndexClient#listAliases(RequestOptions)}. */ public void listAliasesWithContext() { - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listAliases#Context - SEARCH_INDEX_CLIENT.listAliases(new Context(KEY_1, VALUE_1)) - .forEach(searchAlias -> System.out.printf("Listed alias '%s' that aliases index '%s'.", - searchAlias.getName(), searchAlias.getIndexes().get(0))); - // END: com.azure.search.documents.indexes.SearchIndexClient.listAliases#Context + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient.listAliases#RequestOptions + SEARCH_INDEX_CLIENT.listAliases(new RequestOptions().setContext(new Context(KEY_1, VALUE_1))) + .forEach(binaryData -> { + SearchAlias searchAlias = binaryData.toObject(SearchAlias.class); + System.out.printf("Listed alias '%s' that aliases index '%s'.", + searchAlias.getName(), searchAlias.getIndexes().get(0)); + }); + // END: com.azure.search.documents.indexes.SearchIndexClient.listAliases#RequestOptions } } 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 index 264e0b6fb49d..5735c4926891 100644 --- 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 @@ -6,10 +6,6 @@ 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 @@ -46,57 +42,49 @@ public static void main(String[] args) { 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 -> { + searchClient.search(new SearchOptions().setFacets("Rooms/BaseRate,values:5|8|10")) + .byPage().doOnNext(page -> page.getFacets().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(); + .blockLast(); } 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()); + searchClient.search(new SearchOptions().setMinimumCoverage(80.0)).byPage() + .doOnNext(page -> System.out.println("Coverage = " + page.getCoverage())) + .blockLast(); } 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()); + searchClient.search(new SearchOptions().setIncludeTotalCount(true)).byPage() + .doOnNext(page -> System.out.println("Count = " + page.getCount())) + .blockLast(); } 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))))); + searchClient.search(null).byPage() + .doOnNext(searchPagedResponse -> searchPagedResponse.getElements() + .forEach(result -> result.getAdditionalProperties() + .forEach((field, value) -> System.out.println((field + ":" + value))))) + .blockLast(); } private static void searchResultsAsList(SearchAsyncClient searchClient) { // Converting search results to list - searchClient.search("*") + searchClient.search(null) .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))) - ) + .doOnNext(result -> result.getAdditionalProperties() + .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 index 6a360734c99e..fddf2c8ea018 100644 --- 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 @@ -5,12 +5,7 @@ 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 @@ -47,52 +42,39 @@ public static void main(String[] args) { 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 -> { + searchClient.search(new SearchOptions().setFacets("Rooms/BaseRate,values:5|8|10")).streamByPage() + .forEach(page -> page.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()); + searchClient.search(new SearchOptions().setMinimumCoverage(80.0)).streamByPage() + .forEach(page -> System.out.println("Coverage = " + page.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()); + searchClient.search(new SearchOptions().setMinimumCoverage(80.0)).streamByPage() + .forEach(page -> System.out.println("Count = " + page.getCount())); } 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))) - ); + searchClient.search(null).stream().forEach(result -> result.getAdditionalProperties() + .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))) - ); + searchClient.search(null).forEach(result -> result.getAdditionalProperties() + .forEach((field, value) -> System.out.println((field + ":" + value)))); } } 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 index 6bd6e1b86280..40224098a3b2 100644 --- 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 @@ -4,14 +4,10 @@ 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; /** @@ -43,17 +39,13 @@ public static void main(String[] args) { } private static void suggestWithHighlights(SearchClient searchClient) { - SuggestOptions suggestOptions = new SuggestOptions() + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg") .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(); + List response = searchClient.suggest(suggestOptions).getResults(); System.out.println("Received results with highlight:"); response.forEach(r -> System.out.println(r.getText())); @@ -66,14 +58,9 @@ private static void suggestWithHighlights(SearchClient searchClient) { } 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(); + SuggestOptions suggestOptions = new SuggestOptions("hitel", "sg").setUseFuzzyMatching(true); - List response = iterator.next().getValue(); + List response = searchClient.suggest(suggestOptions).getResults(); System.out.println("Received results with fuzzy option:"); response.forEach(r -> System.out.println(r.getText())); 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 index e28530b425fd..9afd6fa80a4a 100644 --- 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 @@ -4,16 +4,14 @@ 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.JsonProviders; 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; @@ -21,23 +19,25 @@ 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; 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.ByteArrayOutputStream; import java.io.IOException; -import java.time.Duration; +import java.io.UncheckedIOException; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; import static com.azure.search.documents.TestHelpers.waitForIndexing; @@ -84,31 +84,30 @@ public static void main(String[] args) { */ 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")))))); + SearchIndex searchIndex = new SearchIndex(INDEX_NAME, + 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(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()); + searchClient.indexDocuments(new IndexDocumentsBatch(getIndexDocuments().stream() + .map(doc -> new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(doc)) + .collect(Collectors.toList()))); waitForIndexing(); @@ -122,67 +121,55 @@ public static SearchClient createSearchIndex(SearchIndexClient searchIndexClient */ 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()); + .setSearchText("Is there any hotel located on the main commercial artery of the city in the heart of New York?") + .setSemanticConfigurationName("my-semantic-config") + .setAnswers(QueryAnswerType.EXTRACTIVE) + .setCaptions(QueryCaptionType.EXTRACTIVE) + .setSemanticErrorHandling(SemanticErrorMode.PARTIAL) + .setSemanticMaxWaitInMilliseconds(5000); + + AtomicInteger count = new AtomicInteger(); + searchClient.search(searchOptions).streamByPage().forEach(page -> { + System.out.println("Semantic Hybrid Search Results:"); + System.out.println("Semantic Query Rewrites Result Type: " + page.getSemanticQueryRewritesResultType()); + System.out.println("Semantic Results Type: " + page.getSemanticPartialResponseType()); + + if (page.getSemanticPartialResponseReason() != null) { + System.out.println("Semantic Error Reason: " + page.getSemanticPartialResponseReason()); + } - if (semanticSearchResults.getErrorReason() != null) { - System.out.println("Semantic Error Reason: " + semanticSearchResults.getErrorReason()); - } + System.out.println("Query Answers:"); + for (QueryAnswerResult result : page.getAnswers()) { + System.out.println("Answer Highlights: " + result.getHighlights()); + System.out.println("Answer Text: " + result.getText()); + } - 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 : page.getElements()) { + count.incrementAndGet(); + Map doc = result.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelId"), doc.get("HotelName")); - 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()); + if (result.getCaptions() != null) { + QueryCaptionResult caption = result.getCaptions().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); + System.out.println("Total number of search results: " + count.get()); } /** * 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() { @@ -265,20 +252,20 @@ public static Hotel fromJson(JsonReader jsonReader) throws IOException { * * @return A list of hotels. */ - public static List getIndexDocuments() { - return Arrays.asList( + public static List> getIndexDocuments() { + List hotels = 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.") + + "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.") + + "noisy rooms riddled with cockroaches.") .setCategory("Budget"), new Hotel() .setHotelId("3") @@ -294,11 +281,24 @@ public static List getIndexDocuments() { .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.") + + "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")); + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeArray(hotels, JsonWriter::writeJson); + } + + try (JsonReader jsonReader = JsonProviders.createReader(outputStream.toByteArray())) { + return jsonReader.readArray(elem -> elem.readMap(JsonReader::readUntyped)); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + // Add more hotel documents here... } } 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 index baf426fded00..5160c2ade00c 100644 --- 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 @@ -5,16 +5,14 @@ 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.JsonProviders; 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; @@ -25,27 +23,31 @@ 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; 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.SearchPagedIterable; 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.ByteArrayOutputStream; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; import static com.azure.search.documents.TestHelpers.waitForIndexing; @@ -98,48 +100,47 @@ public static void main(String[] args) { */ 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)) + SearchIndex searchIndex = new SearchIndex(INDEX_NAME, + 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() + .setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config"))) + .setSemanticSearch(new SemanticSearch().setConfigurations(new SemanticConfiguration("my-semantic-config", + new SemanticPrioritizedFields() .setTitleField(new SemanticField("HotelName")) .setContentFields(new SemanticField("Description")) - .setKeywordsFields(new SemanticField("Category")))))); + .setKeywordsFields(new SemanticField("Category"))))); searchIndexClient.createOrUpdateIndex(searchIndex); SearchClient searchClient = searchIndexClient.getSearchClient(INDEX_NAME); - searchClient.uploadDocuments(getIndexDocuments()); + searchClient.indexDocuments(new IndexDocumentsBatch(getIndexDocuments().stream() + .map(doc -> new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(doc)) + .collect(Collectors.toList()))); waitForIndexing(); @@ -155,20 +156,19 @@ 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) + .setKNearestNeighbors(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); + SearchPagedIterable searchResults = searchClient.search(new SearchOptions() + .setVectorQueries(vectorizableQuery)); 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()); + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelId"), doc.get("HotelName")); } System.out.println("Total number of search results: " + count); } @@ -182,22 +182,21 @@ 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) + .setKNearestNeighbors(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); + SearchPagedIterable searchResults = searchClient.search(new SearchOptions() + .setVectorQueries(vectorizableQuery) + .setVectorFilterMode(VectorFilterMode.POST_FILTER) + .setFilter("Category eq 'Luxury'")); 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()); + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelId"), doc.get("HotelName")); } System.out.println("Total number of search results: " + count); } @@ -211,19 +210,20 @@ 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) + .setKNearestNeighbors(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); + SearchPagedIterable searchResults = searchClient.search(new SearchOptions() + .setSearchText("Top hotels in town") + .setVectorQueries(vectorizableQuery)); 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()); + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelId"), doc.get("HotelName")); } System.out.println("Total number of search results: " + count); } @@ -240,81 +240,76 @@ 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) + .setKNearestNeighbors(3) // Set the fields to compare the vector against. This is a comma-delimited list of field names. .setFields("DescriptionVector"); - SearchOptions searchOptions = new SearchOptions() + SearchOptions searchOptions = new SearchOptions().setSearchText( + "Is there any hotel located on the main commercial artery of the city in the heart of New York?") .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:"); + .setVectorQueries(vectorizableQuery) + .setSemanticConfigurationName("my-semantic-config") + .setAnswers(QueryAnswerType.EXTRACTIVE) + .setCaptions(QueryCaptionType.EXTRACTIVE); + + AtomicInteger count = new AtomicInteger(); + searchClient.search(searchOptions).streamByPage().forEach(page -> { + System.out.println("Semantic Hybrid Search Results:"); + + System.out.println("Query Answer:"); + for (QueryAnswerResult result : page.getAnswers()) { + System.out.println("Answer Highlights: " + result.getHighlights()); + System.out.println("Answer Text: " + result.getText()); + } - 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 : page.getElements()) { + count.incrementAndGet(); + Map doc = result.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelId"), doc.get("HotelName")); - 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()); + if (result.getCaptions() != null) { + QueryCaptionResult caption = result.getCaptions().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); + System.out.println("Total number of search results: " + count.get()); } 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) + .setKNearestNeighbors(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) + .setKNearestNeighbors(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) + .setKNearestNeighbors(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); + SearchPagedIterable searchResults = searchClient.search(new SearchOptions() + .setVectorQueries(firstVectorizableQuery, secondVectorizableQuery, thirdVectorizableQuery)); 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()); + Map doc = searchResult.getAdditionalProperties(); + System.out.printf("%s: %s%n", doc.get("HotelId"), doc.get("HotelName")); } System.out.println("Total number of search results: " + count); } @@ -323,15 +318,10 @@ public static void multiVectorSearch(SearchClient searchClient) { * 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() { @@ -426,8 +416,8 @@ public static VectorHotel fromJson(JsonReader jsonReader) throws IOException { * * @return A list of hotels. */ - public static List getIndexDocuments() { - return Arrays.asList( + public static List> getIndexDocuments() { + List hotels = Arrays.asList( new VectorHotel() .setHotelId("1") .setHotelName("Fancy Stay") @@ -465,6 +455,19 @@ public static List getIndexDocuments() { .setDescriptionVector(VectorSearchEmbeddings.HOTEL9_VECTORIZE_DESCRIPTION) .setCategory("Boutique")); + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeArray(hotels, JsonWriter::writeJson); + } + + try (JsonReader jsonReader = JsonProviders.createReader(outputStream.toByteArray())) { + return jsonReader.readArray(elem -> elem.readMap(JsonReader::readUntyped)); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + // 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 index 0777707dd1ac..30534794631e 100644 --- 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 @@ -9,36 +9,38 @@ 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.JsonProviders; 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SearchPagedIterable; 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.ByteArrayOutputStream; import java.io.IOException; +import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; /** * This sample demonstrates how to create a vector fields index with reduced dimensions, upload reduced embeddings into @@ -98,36 +100,36 @@ public static SearchIndex defineVectorIndex() { 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)) + return new SearchIndex(indexName, 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( + .setVectorizers(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))))); + .setModelName(AzureOpenAIModelName.TEXT_EMBEDDING3LARGE)))); } public static void createVectorIndex(SearchIndex vectorIndex) { @@ -149,17 +151,11 @@ public static void createVectorIndex(SearchIndex vectorIndex) { * 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() { @@ -312,7 +308,22 @@ public static List getHotelDocuments() { } public static void indexDocuments(SearchClient searchClient, List hotelDocuments) { - searchClient.indexDocuments(new IndexDocumentsBatch().addUploadActions(hotelDocuments)); + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeArray(hotelDocuments, JsonWriter::writeJson); + } + + try (JsonReader jsonReader = JsonProviders.createReader(outputStream.toByteArray())) { + List actions = jsonReader.readArray(elem -> new IndexAction() + .setActionType(IndexActionType.UPLOAD) + .setAdditionalProperties(elem.readMap(JsonReader::readUntyped))); + searchClient.indexDocuments(new IndexDocumentsBatch(actions)); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } /** @@ -321,18 +332,18 @@ public static void indexDocuments(SearchClient searchClient, List h * 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); + SearchPagedIterable response = searchClient.search(new SearchOptions() + .setVectorQueries(new VectorizableTextQuery("Luxury hotels in town") + .setKNearestNeighbors(3) + .setFields("DescriptionVector"))); 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()); + Map doc = result.getAdditionalProperties(); + System.out.println(doc.get("HotelId") + ": " + doc.get("HotelName")); } 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 index 43f73403d16c..9e85d1d7230e 100644 --- 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 @@ -5,15 +5,16 @@ 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 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.IndexDocumentsBatch; +import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SuggestOptions; -import java.util.ArrayList; import java.util.Collections; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; @SuppressWarnings("unused") public class SearchAsyncClientJavaDocSnippets { @@ -36,13 +37,13 @@ private static SearchAsyncClient createSearchAsyncClientWithSearchClientBuilder( */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-upload + searchAsyncClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "200")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "300")) + )).block(); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-upload } /** @@ -50,12 +51,12 @@ public static void uploadDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-merge + searchAsyncClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(Collections.singletonMap("HotelId", "200")) + )).block(); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-merge } /** @@ -63,11 +64,11 @@ public static void mergeDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-delete + searchAsyncClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.DELETE).setAdditionalProperties(Collections.singletonMap("HotelId", "100")) + )).block(); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-delete } /** @@ -75,12 +76,14 @@ public static void deleteDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.getDocument#String + searchAsyncClient.getDocument("100") + .doOnNext(document -> { + if (document.getAdditionalProperties() != null) { + System.out.printf("Retrieved Hotel %s%n", document.getAdditionalProperties().get("HotelId")); + } + }).block(); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.getDocument#String } /** @@ -88,25 +91,25 @@ public static void getDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.search#SearchOptions + Map searchDocument = new LinkedHashMap<>(); + searchDocument.put("HotelId", "8"); + searchDocument.put("Description", "budget"); + searchDocument.put("DescriptionFr", "motel"); + + Map searchDocument2 = new LinkedHashMap<>(); + searchDocument2.put("HotelId", "9"); + searchDocument2.put("Description", "budget"); + searchDocument2.put("DescriptionFr", "motel"); + + searchAsyncClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument2) + )).block(); + + searchAsyncClient.search(new SearchOptions().setSearchText("SearchText")).byPage() + .subscribe(page -> System.out.printf("There are %d results", page.getCount())); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.search#SearchOptions } /** @@ -114,12 +117,11 @@ public static void searchDocuments() { */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.suggest#SuggestOptions + searchAsyncClient.suggest(new SuggestOptions("searchText", "sg")) + .subscribe(results -> results.getResults() + .forEach(item -> System.out.printf("The text '%s' was found.%n", item.getText()))); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.suggest#SuggestOptions } /** @@ -127,12 +129,11 @@ public static void suggestDocuments() { */ 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 + // BEGIN: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.autocomplete#AutocompleteOptions + searchAsyncClient.autocomplete(new AutocompleteOptions("searchText", "sg")) + .subscribe(results -> results.getResults() + .forEach(item -> System.out.printf("The text '%s' was found.%n", item.getText()))); + // END: com.azure.search.documents.SearchAsyncClient-classLevelJavaDoc.autocomplete#AutocompleteOptions } } 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 index 00a3b5a83e6c..8caa70f395a6 100644 --- 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 @@ -5,17 +5,18 @@ 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 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.IndexDocumentsBatch; +import com.azure.search.documents.models.LookupDocument; +import com.azure.search.documents.models.SearchOptions; +import com.azure.search.documents.models.SuggestOptions; + import java.util.Collections; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; + @SuppressWarnings("unused") public class SearchClientJavaDocSnippets { @@ -37,13 +38,13 @@ private static SearchClient createSearchClientWithSearchClientBuilder() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-upload + searchClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "200")), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "300")) + )); + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-upload } /** @@ -51,12 +52,12 @@ public static void uploadDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-merge + searchClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(Collections.singletonMap("HotelId", "100")), + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(Collections.singletonMap("HotelId", "200")) + )); + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-merge } /** @@ -64,11 +65,11 @@ public static void mergeDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-delete + searchClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(Collections.singletonMap("HotelId", "100")) + )); + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.indexDocuments#IndexDocumentsBatch-delete } /** @@ -76,10 +77,12 @@ public static void deleteDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.getDocument#String + LookupDocument document = searchClient.getDocument("100"); + if (document.getAdditionalProperties() != null) { + System.out.printf("Retrieved Hotel %s%n", document.getAdditionalProperties().get("HotelId")); + } + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.getDocument#String } /** @@ -87,25 +90,24 @@ public static void getDocument() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.search#SearchOptions + Map searchDocument = new LinkedHashMap<>(); + searchDocument.put("HotelId", "8"); + searchDocument.put("Description", "budget"); + searchDocument.put("DescriptionFr", "motel"); + + Map searchDocument2 = new LinkedHashMap<>(); + searchDocument2.put("HotelId", "9"); + searchDocument2.put("Description", "budget"); + searchDocument2.put("DescriptionFr", "motel"); + + searchClient.indexDocuments(new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument), + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(searchDocument2))); + + searchClient.search(new SearchOptions().setSearchText("SearchText")).streamByPage() + .forEach(page -> System.out.printf("There are %d results.%n", page.getCount())); + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.search#SearchOptions } /** @@ -113,12 +115,10 @@ public static void searchDocuments() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.suggest#SuggestOptions + searchClient.suggest(new SuggestOptions("searchText", "sg")).getResults() + .forEach(item -> System.out.printf("The text '%s' was found.%n", item.getText())); + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.suggest#SuggestOptions } /** @@ -126,12 +126,10 @@ public static void suggestDocuments() { */ 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 + // BEGIN: com.azure.search.documents.SearchClient-classLevelJavaDoc.autocomplete#AutocompleteOptions + searchClient.autocomplete(new AutocompleteOptions("searchText", "sg")).getResults() + .forEach(item -> System.out.printf("The text '%s' was found.%n", item.getText())); + // END: com.azure.search.documents.SearchClient-classLevelJavaDoc.autocomplete#AutocompleteOptions } } 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 index 9fd2afd7f9ee..c71f2fa5a48c 100644 --- 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 @@ -6,12 +6,11 @@ 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.ListSynonymMapsResult; 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 { @@ -36,50 +35,49 @@ private static SearchIndexAsyncClient createSearchIndexAsyncClient() { 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) + SearchIndex searchIndex = new SearchIndex("indexName", + new SearchField("HotelId", SearchFieldDataType.STRING) .setKey(true) .setFilterable(true) .setSortable(true), - new SearchField("hotelName", SearchFieldDataType.STRING) + new SearchField("HotelName", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true), - new SearchField("description", SearchFieldDataType.STRING) + new SearchField("Description", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("descriptionFr", SearchFieldDataType.STRING) + new SearchField("DescriptionFr", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) .setSearchable(true) .setFilterable(true) .setFacetable(true), - new SearchField("address", SearchFieldDataType.COMPLEX) + new SearchField("Address", SearchFieldDataType.COMPLEX) .setFields( - new SearchField("streetAddress", SearchFieldDataType.STRING) + new SearchField("StreetAddress", SearchFieldDataType.STRING) .setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) + new SearchField("City", SearchFieldDataType.STRING) .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) + new SearchField("StateProvince", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("country", SearchFieldDataType.STRING) + new SearchField("Country", SearchFieldDataType.STRING) .setSearchable(true) .setSynonymMapNames("synonymMapName") .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) + new SearchField("PostalCode", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true) - .setFacetable(true)) - )); + .setFacetable(true))); searchIndexAsyncClient.createIndex(searchIndex).block(); // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createIndex#SearchIndex @@ -113,13 +111,14 @@ public static void getIndex() { */ public static void updateIndex() { searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateIndex#SearchIndex + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createOrUpdateIndex#SearchIndex SearchIndex searchIndex = searchIndexAsyncClient.getIndex("indexName").block(); if (searchIndex != null) { - searchIndex.setFields(new SearchField("newField", SearchFieldDataType.STRING)); + searchIndex.getFields().clear(); + searchIndex.getFields().add(new SearchField("newField", SearchFieldDataType.STRING)); searchIndexAsyncClient.createOrUpdateIndex(searchIndex); } - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateIndex#SearchIndex + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createOrUpdateIndex#SearchIndex } /** @@ -150,9 +149,8 @@ public static void createSynonymMap() { 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()) - ); + searchIndexAsyncClient.listSynonymMaps().map(ListSynonymMapsResult::getSynonymMaps).subscribe(synonymMaps -> + synonymMaps.forEach(synonymMap -> System.out.println("The synonymMap name is " + synonymMap.getName()))); // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.listSynonymMaps } @@ -174,13 +172,14 @@ public static void getSynonymMap() { */ public static void updateSynonymMap() { searchIndexAsyncClient = createSearchIndexAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateSynonymMap#SynonymMap + // BEGIN: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createOrUpdateSynonymMap#SynonymMap SynonymMap synonymMap = searchIndexAsyncClient.getSynonymMap("synonymMapName").block(); if (synonymMap != null) { - synonymMap.setSynonyms("hotel, motel, inn"); + synonymMap.getSynonyms().clear(); + synonymMap.getSynonyms().add("hotel, motel, inn"); searchIndexAsyncClient.createOrUpdateSynonymMap(synonymMap).block(); } - // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.updateSynonymMap#SynonymMap + // END: com.azure.search.documents.indexes.SearchIndexAsyncClient-classLevelJavaDoc.createOrUpdateSynonymMap#SynonymMap } /** 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 index c43f6ae6335d..985b8d9d8526 100644 --- 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 @@ -10,8 +10,6 @@ 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 { @@ -36,50 +34,49 @@ private static SearchIndexClient createSearchIndexClient() { 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) + SearchIndex searchIndex = new SearchIndex("indexName", + new SearchField("HotelId", SearchFieldDataType.STRING) .setKey(true) .setFilterable(true) .setSortable(true), - new SearchField("hotelName", SearchFieldDataType.STRING) + new SearchField("HotelName", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true), - new SearchField("description", SearchFieldDataType.STRING) + new SearchField("Description", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("descriptionFr", SearchFieldDataType.STRING) + new SearchField("DescriptionFr", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) .setSearchable(true) .setFilterable(true) .setFacetable(true), - new SearchField("address", SearchFieldDataType.COMPLEX) + new SearchField("Address", SearchFieldDataType.COMPLEX) .setFields( - new SearchField("streetAddress", SearchFieldDataType.STRING) + new SearchField("StreetAddress", SearchFieldDataType.STRING) .setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) + new SearchField("City", SearchFieldDataType.STRING) .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) + new SearchField("StateProvince", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("country", SearchFieldDataType.STRING) + new SearchField("Country", SearchFieldDataType.STRING) .setSearchable(true) .setSynonymMapNames("synonymMapName") .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) + new SearchField("PostalCode", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true) - .setFacetable(true)) - )); + .setFacetable(true))); searchIndexClient.createIndex(searchIndex); // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createIndex#SearchIndex @@ -113,13 +110,14 @@ public static void getIndex() { */ public static void updateIndex() { searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateIndex#SearchIndex + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createOrUpdateIndex#SearchIndex SearchIndex searchIndex = searchIndexClient.getIndex("indexName"); if (searchIndex != null) { - searchIndex.setFields(new SearchField("newField", SearchFieldDataType.STRING)); + searchIndex.getFields().clear(); + searchIndex.getFields().add(new SearchField("newField", SearchFieldDataType.STRING)); searchIndexClient.createOrUpdateIndex(searchIndex); } - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateIndex#SearchIndex + // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createOrUpdateIndex#SearchIndex } /** @@ -150,7 +148,8 @@ public static void createSynonymMap() { public static void listSynonymMaps() { searchIndexClient = createSearchIndexClient(); // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.listSynonymMaps - searchIndexClient.listSynonymMaps().forEach(synonymMap -> System.out.println(synonymMap.getName())); + searchIndexClient.listSynonymMaps().getSynonymMaps() + .forEach(synonymMap -> System.out.println(synonymMap.getName())); // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.listSynonymMaps } @@ -172,13 +171,14 @@ public static void getSynonymMap() { */ public static void updateSynonymMap() { searchIndexClient = createSearchIndexClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateSynonymMap#SynonymMap + // BEGIN: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createOrUpdateSynonymMap#SynonymMap SynonymMap synonymMap = searchIndexClient.getSynonymMap("synonymMapName"); if (synonymMap != null) { - synonymMap.setSynonyms("inn,hotel,motel"); + synonymMap.getSynonyms().clear(); + synonymMap.getSynonyms().add("inn,hotel,motel"); searchIndexClient.createOrUpdateSynonymMap(synonymMap); } - // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.updateSynonymMap#SynonymMap + // END: com.azure.search.documents.indexes.SearchIndexClient-classLevelJavaDoc.createOrUpdateSynonymMap#SynonymMap } /** 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 index cd5e59a21150..e5a6cb27026b 100644 --- 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 @@ -6,6 +6,8 @@ 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.ListIndexersResult; +import com.azure.search.documents.indexes.models.ListSkillsetsResult; import com.azure.search.documents.indexes.models.OcrSkill; import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; import com.azure.search.documents.indexes.models.SearchIndexer; @@ -56,9 +58,8 @@ public static void createIndexer() { 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()) - ); + searchIndexerAsyncClient.listIndexers().map(ListIndexersResult::getIndexers).subscribe(indexers -> + indexers.forEach(indexer -> System.out.printf("Retrieved indexer name: %s%n", indexer.getName()))); // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.listIndexers } @@ -80,7 +81,7 @@ public static void getIndexer() { */ public static void updateIndexer() { searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateIndexer#SearchIndexer + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.createOrUpdateIndexer#SearchIndexer SearchIndexer indexer = searchIndexerAsyncClient.getIndexer("example-indexer").block(); if (indexer != null) { System.out.printf("Retrieved indexer name: %s%n", indexer.getName()); @@ -93,7 +94,7 @@ public static void updateIndexer() { } } - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateIndexer#SearchIndexer + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.createOrUpdateIndexer#SearchIndexer } /** @@ -156,14 +157,14 @@ public static void createSkillset() { 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())); + System.out.printf("Creating OCR skillset '%s'%n", 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())); + System.out.printf("Name: %s%n", createdSkillset.getName()); + System.out.printf("ETag: %s%n", createdSkillset.getETag()); } // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.createSkillset#SearchIndexerSkillset } @@ -174,9 +175,8 @@ public static void createSkillset() { 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()) - ); + searchIndexerAsyncClient.listSkillsets().map(ListSkillsetsResult::getSkillsets).subscribe(skillsets -> + skillsets.forEach(skillset -> System.out.printf("Retrieved skillset name: %s%n", skillset.getName()))); // END: com.azure.search.documents.SearchIndexerAsyncClient-classLevelJavaDoc.listSkillsets } @@ -198,7 +198,7 @@ public static void getSkillset() { */ public static void updateSkillset() { searchIndexerAsyncClient = createSearchIndexerAsyncClient(); - // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset + // BEGIN: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.createOrUpdateSkillset#SearchIndexerSkillset SearchIndexerSkillset skillset = searchIndexerAsyncClient.getSkillset("example-skillset").block(); if (skillset != null) { System.out.printf("Retrieved skillset name: %s%n", skillset.getName()); @@ -209,7 +209,7 @@ public static void updateSkillset() { updatedSkillset.getDescription()); } } - // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset + // END: com.azure.search.documents.indexes.SearchIndexerAsyncClient-classLevelJavaDoc.createOrUpdateSkillset#SearchIndexerSkillset } /** 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 index 57e48b2b42e5..869d25e43b12 100644 --- 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 @@ -52,9 +52,8 @@ public static void createIndexer() { 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()) - ); + searchIndexerClient.listIndexers().getIndexers() + .forEach(indexer -> System.out.printf("Retrieved indexer name: %s%n", indexer.getName())); // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.listIndexers } @@ -74,13 +73,13 @@ public static void getIndexer() { */ public static void updateIndexer() { searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.updateIndexer#SearchIndexer + // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createOrUpdateIndexer#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 + // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createOrUpdateIndexer#SearchIndexer } /** @@ -144,13 +143,13 @@ public static void createSkillset() { 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())); + System.out.printf("Creating OCR skillset '%s'%n", 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.printf("Name: %s%n", createdSkillset.getName()); + System.out.printf("ETag: %s%n", createdSkillset.getETag()); // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createSkillset#SearchIndexerSkillset } @@ -161,9 +160,8 @@ public static void createSkillset() { 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()) - ); + searchIndexerClient.listSkillsets().getSkillsets() + .forEach(skillset -> System.out.printf("Retrieved skillset name: %s%n", skillset.getName())); // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.listSkillsets } @@ -183,13 +181,13 @@ public static void getSkillset() { */ public static void updateSkillset() { searchIndexerClient = createSearchIndexerClient(); - // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.updateSkillset#SearchIndexerSkillset + // BEGIN: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createOrUpdateSkillset#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 + // END: com.azure.search.documents.SearchIndexerClient-classLevelJavaDoc.createOrUpdateSkillset#SearchIndexerSkillset } /** 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 index 59f4ceefd235..db17f9566e1a 100644 --- 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 @@ -5,30 +5,32 @@ 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.BasicField; 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.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; +import com.azure.search.documents.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.LinkedHashMap; import java.util.List; +import java.util.Map; + @SuppressWarnings("unused") public class SearchPackageInfoJavaDocSnippets { @@ -84,10 +86,10 @@ public SearchClient createSearchClient() { 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")); + for (SearchResult result : searchClient.search(new SearchOptions().setSearchText("luxury"))) { + Map document = result.getAdditionalProperties(); + 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 } @@ -98,11 +100,16 @@ public static class Hotel { private String hotelId; private String hotelName; - @SimpleField(isKey = true) + @BasicField(name = "HotelId", isKey = BasicField.BooleanHelper.TRUE) public String getHotelId() { return this.hotelId; } + @BasicField( + name = "HotelName", + isSearchable = BasicField.BooleanHelper.TRUE, + isFilterable = BasicField.BooleanHelper.TRUE, + analyzerName = "en.lucene") public String getHotelName() { return this.hotelName; } @@ -127,10 +134,10 @@ public void searchModelClass() { // 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()); + for (SearchResult result : searchClient.search(new SearchOptions().setSearchText("luxury"))) { + Map hotel = result.getAdditionalProperties(); + System.out.printf("Hotel ID: %s%n", hotel.get("HotelId")); + System.out.printf("Hotel Name: %s%n", hotel.get("HotelName")); } // END: com.azure.search.documents.packageInfo-SearchClient.search#String-Object-Class-Method @@ -142,14 +149,13 @@ public void searchModelClass() { public void searchWithOptions() { SearchClient searchClient = createSearchClient(); // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#SearchOptions - SearchOptions options = new SearchOptions() + SearchOptions options = new SearchOptions().setSearchText("luxury") .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()); + searchClient.search(options).forEach(result -> { + System.out.printf("Hotel ID: %s%n", result.getAdditionalProperties().get("HotelId")); + System.out.printf("Hotel Name: %s%n", result.getAdditionalProperties().get("HotelName")); }); // END: com.azure.search.documents.packageInfo-SearchClient.search#SearchOptions } @@ -161,7 +167,7 @@ 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); + List searchFields = SearchIndexClient.buildSearchFields(Hotel.class); searchIndexClient.createIndex(new SearchIndex("hotels", searchFields)); // END: com.azure.search.documents.packageInfo-SearchIndexClient.createIndex#SearchIndex } @@ -174,50 +180,49 @@ public void createSearchIndexWithSearchField() { // 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("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) + 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)) + 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) + 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) + new SearchField("StateProvince", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) .setSortable(true), - new SearchField("country", SearchFieldDataType.STRING) + new SearchField("Country", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) .setSortable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) + new SearchField("PostalCode", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setFacetable(true) - .setSortable(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); + SearchIndex index = new SearchIndex("hotels", searchFieldList).setSuggesters(suggester); // Create an index searchIndexClient.createIndex(index); // END: com.azure.search.documents.packageInfo-SearchIndexClient.createIndex#String-List-boolean @@ -228,11 +233,11 @@ public void createSearchIndexWithSearchField() { */ 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 + // BEGIN: com.azure.search.documents.packageInfo-SearchClient.getDocument#String + Map hotel = searchClient.getDocument("1").getAdditionalProperties(); + System.out.printf("Hotel ID: %s%n", hotel.get("HotelId")); + System.out.printf("Hotel Name: %s%n", hotel.get("HotelName")); + // END: com.azure.search.documents.packageInfo-SearchClient.getDocument#String } /** @@ -241,11 +246,17 @@ public void getDocument() { 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"))); + Map hotel = new LinkedHashMap<>(); + hotel.put("HotelId", "783"); + hotel.put("HotelName", "Upload Inn"); + + Map hotel2 = new LinkedHashMap<>(); + hotel2.put("HotelId", "12"); + hotel2.put("HotelName", "Renovated Ranch"); + + IndexDocumentsBatch batch = new IndexDocumentsBatch( + new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(hotel), + new IndexAction().setActionType(IndexActionType.MERGE).setAdditionalProperties(hotel2)); searchClient.indexDocuments(batch); // END: com.azure.search.documents.packageInfo-SearchClient.uploadDocuments#Iterable-boolean-boolean } @@ -271,12 +282,10 @@ public SearchClient createSearchClientInNationalCloud() { */ public void handleSearchError() { SearchClient searchClient = createSearchClient(); - // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#String-Object-Class-Error + // BEGIN: com.azure.search.documents.packageInfo-SearchClient.search#SearchOptions-error try { - Iterable results = searchClient.search("hotel"); - results.forEach(result -> { - System.out.println(result.getDocument(Hotel.class).getHotelName()); - }); + searchClient.search(new SearchOptions().setSearchText("hotel")) + .forEach(result -> System.out.println(result.getAdditionalProperties().get("hotelName"))); } catch (HttpResponseException ex) { // The exception contains the HTTP status code and the detailed message // returned from the search service @@ -284,7 +293,7 @@ public void handleSearchError() { 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 + // END: com.azure.search.documents.packageInfo-SearchClient.search#SearchOptions-error } } 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 index 6de3b143f9dd..1e8e44393ed0 100644 --- 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 @@ -10,8 +10,6 @@ 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 @@ -29,50 +27,49 @@ public static void main(String[] args) { // Configure the index using SearchFields String indexName = "hotels"; - SearchIndex newIndex = new SearchIndex(indexName, Arrays.asList( - new SearchField("hotelId", SearchFieldDataType.STRING) + SearchIndex newIndex = new SearchIndex(indexName, + new SearchField("HotelId", SearchFieldDataType.STRING) .setKey(true) .setFilterable(true) .setSortable(true), - new SearchField("hotelName", SearchFieldDataType.STRING) + new SearchField("HotelName", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true), - new SearchField("description", SearchFieldDataType.STRING) + new SearchField("Description", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), - new SearchField("descriptionFr", SearchFieldDataType.STRING) + new SearchField("DescriptionFr", SearchFieldDataType.STRING) .setSearchable(true) .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE), - new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) .setSearchable(true) .setFilterable(true) .setFacetable(true), - new SearchField("address", SearchFieldDataType.COMPLEX) + new SearchField("Address", SearchFieldDataType.COMPLEX) .setFields( - new SearchField("streetAddress", SearchFieldDataType.STRING) + new SearchField("StreetAddress", SearchFieldDataType.STRING) .setSearchable(true), - new SearchField("city", SearchFieldDataType.STRING) + new SearchField("City", SearchFieldDataType.STRING) .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("stateProvince", SearchFieldDataType.STRING) + new SearchField("StateProvince", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("country", SearchFieldDataType.STRING) + new SearchField("Country", SearchFieldDataType.STRING) .setSearchable(true) .setSynonymMapNames("synonymMapName") .setFilterable(true) .setSortable(true) .setFacetable(true), - new SearchField("postalCode", SearchFieldDataType.STRING) + new SearchField("PostalCode", SearchFieldDataType.STRING) .setSearchable(true) .setFilterable(true) .setSortable(true) - .setFacetable(true)) - )); + .setFacetable(true))); // Create index. client.createIndex(newIndex); 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 index e8cdf0d211a7..5bebb66b44fd 100644 --- 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 @@ -5,7 +5,6 @@ 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; @@ -31,13 +30,12 @@ public static void main(String[] args) { .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()); + // with @BasicField or @ComplexField. + List indexFields = SearchIndexClient.buildSearchFields(Hotel.class); + indexFields.add( + new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true).setFilterable(true).setSortable(true)); 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); + SearchIndex newIndex = new SearchIndex(indexName, indexFields); // Create index. client.createIndex(newIndex); // Cleanup index resource. @@ -48,22 +46,25 @@ public static void main(String[] args) { * A hotel. */ public static final class Hotel { - @SimpleField(isKey = true, isFilterable = true, isSortable = true) private final String hotelId; - @SearchableField(isFilterable = true, isSortable = true) + @BasicField( + name = "HotelName", + isSearchable = BasicField.BooleanHelper.TRUE, + isSortable = BasicField.BooleanHelper.TRUE) private String hotelName; - @SearchableField(analyzerName = "en.lucene") + @BasicField(name = "Description", isSearchable = BasicField.BooleanHelper.TRUE) private String description; - @SearchableField(analyzerName = "fr.lucene") + @BasicField(name = "DescriptionFr") private String descriptionFr; - @SearchableField(isFilterable = true, isFacetable = true) + @BasicField( + name = "Tags", isFacetable = BasicField.BooleanHelper.TRUE, isFilterable = BasicField.BooleanHelper.TRUE) private List tags; - // Complex fields are included automatically in an index if not ignored. + @ComplexField(name = "Address") private Address address; /** @@ -189,23 +190,27 @@ public Hotel setAddress(Address address) { * An address. */ public static final class Address { - @SearchableField + @BasicField(name = "StreetAddress") private String streetAddress; - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField( + name = "City", isFacetable = BasicField.BooleanHelper.TRUE, isFilterable = BasicField.BooleanHelper.TRUE) private String city; - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField( + name = "StateProvince", + isFacetable = BasicField.BooleanHelper.TRUE, + isFilterable = BasicField.BooleanHelper.TRUE) private String stateProvince; - @SearchableField( - synonymMapNames = { "synonymMapName" }, - isFilterable = true, - isSortable = true, - isFacetable = true) + @BasicField( + name = "Country", isFacetable = BasicField.BooleanHelper.TRUE, isFilterable = BasicField.BooleanHelper.TRUE) private String country; - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField( + name = "PostalCode", + isFacetable = BasicField.BooleanHelper.TRUE, + isFilterable = BasicField.BooleanHelper.TRUE) private String postalCode; /** 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 index faeb6f8ea207..49b8f820381b 100644 --- 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 @@ -60,17 +60,15 @@ private static void createOrUpdateIndexer(SearchIndexerAsyncClient searchIndexer .setFieldMappings(fieldMappings) .setSchedule(indexingSchedule); - System.out.println(String.format("Creating Indexer: %s", indexer.getName())); - Response response = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse( - indexer, false - ).block(); + System.out.printf("Creating Indexer: %s%n", indexer.getName()); + Response response = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, null) + .block(); if (response != null) { - System.out.println(String.format("Response code: %s", response.getStatusCode())); + System.out.printf("Response code: %s%n", response.getStatusCode()); SearchIndexer createdIndexer = response.getValue(); - System.out.println(String - .format("Created indexer name: %s, ETag: %s", createdIndexer.getName(), createdIndexer.getETag())); + System.out.printf("Created indexer name: %s, ETag: %s%n", 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 index ed5b550e4846..f5d5fe3dd26c 100644 --- 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 @@ -10,6 +10,7 @@ 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.WebApiHttpHeaders; import com.azure.search.documents.indexes.models.WebApiSkill; import java.util.Arrays; @@ -67,15 +68,13 @@ private static void createOcrSkillset(SearchIndexerClient searchIndexerClient) { 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())); + System.out.printf("Creating OCR skillset '%s'%n", 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"); + System.out.printf("Name: %s%n", createdSkillset.getName()); + System.out.printf("ETag: %s%n%n", createdSkillset.getETag()); } private static void createCustomSkillset(SearchIndexerClient searchIndexerClient) { @@ -83,32 +82,27 @@ private static void createCustomSkillset(SearchIndexerClient searchIndexerClient headers.put("Ocp-Apim-Subscription-Key", "foobar"); List inputs = Collections.singletonList( - new InputFieldMappingEntry("text") - .setSource("/document/mytext") - ); + new InputFieldMappingEntry("text").setSource("/document/mytext")); List outputs = Collections.singletonList( - new OutputFieldMappingEntry("textItems") - .setTargetName("myTextItems") - ); + 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) + .setHttpHeaders(new WebApiHttpHeaders().setAdditionalProperties(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)) + SearchIndexerSkillset skillset = new SearchIndexerSkillset(CUSTOM_SKILLSET_NAME, webApiSkill) .setDescription("Skillset for testing custom skillsets"); - System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); + System.out.printf("Creating custom skillset '%s'%n", 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())); + System.out.printf("Name: %s%n", createdSkillset.getName()); + System.out.printf("ETag: %s%n", createdSkillset.getETag()); } private static void cleanupSkillset(SearchIndexerClient searchIndexerClient) { 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 index f7e7cffd7d5c..523dfc5c2319 100644 --- 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 @@ -4,10 +4,11 @@ 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.DataSourceCredentials; import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; +import com.azure.search.documents.indexes.models.ListDataSourcesResult; import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; @@ -53,11 +54,11 @@ public static void main(String[] args) { /* * Get all existing data sources; list should include the ones we just created. * */ - PagedIterable dataSources = client.listDataSourceConnections(); - for (SearchIndexerDataSourceConnection dataSource : dataSources) { + ListDataSourcesResult result = client.listDataSourceConnections(); + for (SearchIndexerDataSourceConnection dataSource : result.getDataSources()) { if (names.contains(dataSource.getName())) { - System.out.println(String.format("Found data source %s of type %s", dataSource.getName(), - dataSource.getType().toString())); + System.out.printf("Found data source %s of type %s%n", dataSource.getName(), + dataSource.getType().toString()); } } @@ -70,17 +71,14 @@ public static void main(String[] args) { } private static void deleteDataSource(SearchIndexerClient client, String dataSourceName) { - try { - client.deleteDataSourceConnection(dataSourceName); - } catch (Exception ex) { - System.err.println(ex.toString()); - } + client.deleteDataSourceConnection(dataSourceName); } private static SearchIndexerDataSourceConnection createSampleDatasource(SearchIndexerDataSourceType type, String connectionString, SearchIndexerDataContainer container, DataChangeDetectionPolicy dataChangeDetectionPolicy) { - return new SearchIndexerDataSourceConnection(generateDataSourceName(), type, connectionString, container) + return new SearchIndexerDataSourceConnection(generateDataSourceName(), type, + new DataSourceCredentials().setConnectionString(connectionString), container) .setDataChangeDetectionPolicy(dataChangeDetectionPolicy); } @@ -93,12 +91,7 @@ private static String createDataSource( SearchIndexerDataSourceConnection dataSource = createSampleDatasource(type, connectionString, container, dataChangeDetectionPolicy); - try { - client.createOrUpdateDataSourceConnection(dataSource); - } catch (Exception ex) { - System.err.println(ex.toString()); - } - return dataSource.getName(); + return client.createOrUpdateDataSourceConnection(dataSource).getName(); } private static String createTableStorageDataSource(SearchIndexerClient client) { @@ -144,6 +137,6 @@ private static String createSqlDataSource(SearchIndexerClient client) { } private static String generateDataSourceName() { - return "datasource" + UUID.randomUUID().toString(); + return "datasource" + UUID.randomUUID(); } } 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 index 600375ad4ba8..d33f871c2111 100644 --- 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 @@ -5,8 +5,8 @@ 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.DataSourceCredentials; +import com.azure.search.documents.indexes.models.EntityRecognitionSkillV3; import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; import com.azure.search.documents.indexes.models.IndexingSchedule; import com.azure.search.documents.indexes.models.InputFieldMappingEntry; @@ -124,7 +124,7 @@ private static SearchIndexerSkillset createSkillset(SearchIndexerClient client) ); - SearchIndexerSkill skill = new EntityRecognitionSkill(inputs, outputs, EntityRecognitionSkillVersion.V3) + SearchIndexerSkill skill = new EntityRecognitionSkillV3(inputs, outputs) .setName("#1") .setDescription("Entity Recognition Skill") .setContext("/document/Description"); @@ -139,38 +139,38 @@ private static SearchIndexerSkillset createSkillset(SearchIndexerClient client) 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), + .setKey(true) + .setFacetable(true) + .setFilterable(true) + .setRetrievable(true) + .setSearchable(false) + .setSortable(false), new SearchField("HotelName", SearchFieldDataType.STRING) - .setFacetable(Boolean.FALSE) - .setFilterable(Boolean.FALSE) - .setHidden(Boolean.FALSE) - .setKey(Boolean.FALSE) - .setSearchable(Boolean.TRUE) - .setSortable(Boolean.FALSE) + .setFacetable(false) + .setFilterable(false) + .setRetrievable(true) + .setKey(false) + .setSearchable(true) + .setSortable(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) + .setSearchable(true) + .setFilterable(false) + .setRetrievable(true) + .setSortable(false) + .setFacetable(false) .setAnalyzerName(LexicalAnalyzerName.EN_MICROSOFT), new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) - .setFacetable(Boolean.TRUE) - .setFilterable(Boolean.TRUE) - .setHidden(Boolean.FALSE) - .setSearchable(Boolean.TRUE) + .setFacetable(true) + .setFilterable(true) + .setRetrievable(true) + .setSearchable(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"))); + index.setSuggesters(new SearchSuggester(SUGGESTER_NAME, "Tags")); return client.createOrUpdateIndex(index); } @@ -182,7 +182,8 @@ private static SearchIndexerDataSourceConnection createCosmosDataSource(SearchIn new HighWaterMarkChangeDetectionPolicy("_ts"); SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection(DATASOURCE_NAME, - SearchIndexerDataSourceType.COSMOS_DB, COSMOS_CONNECTION_STRING, dataContainer) + SearchIndexerDataSourceType.COSMOS_DB, + new DataSourceCredentials().setConnectionString(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 index 4b01610e6577..ac0b3a8e63e2 100644 --- 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 @@ -4,12 +4,9 @@ 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 { /** @@ -34,17 +31,13 @@ public static void main(String[] args) { } private static void listIndexers(SearchIndexerAsyncClient indexerAsyncClient) { - PagedResponse response = indexerAsyncClient.listIndexers() - .byPage().blockFirst(); - - if (response != null) { + indexerAsyncClient.listIndexersWithResponse(null).subscribe(response -> { System.out.printf("Response code: %s%n", response.getStatusCode()); - List indexers = response.getValue(); System.out.println("Found the following indexers:"); - for (SearchIndexer indexer : indexers) { + for (SearchIndexer indexer : response.getValue().getIndexers()) { 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 index 7aa1133e926c..06131415717a 100644 --- 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 @@ -2,15 +2,17 @@ // 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.azure.json.JsonSerializable; +import com.azure.json.JsonWriter; +import com.azure.search.documents.indexes.BasicField; import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Objects; -public class Hotel { +public class Hotel implements JsonSerializable { private String hotelId; private List tags; @@ -19,7 +21,7 @@ public Hotel() { } @JsonProperty(value = "HotelId") - @SimpleField(isKey = true) + @BasicField(name = "HotelId", isKey = BasicField.BooleanHelper.TRUE) public String getHotelId() { return this.hotelId; } @@ -30,7 +32,11 @@ public Hotel setHotelId(String hotelId) { } @JsonProperty(value = "Tags") - @SearchableField(isFilterable = true, analyzerName = "en.lucene") + @BasicField( + name = "Tags", + isSearchable = BasicField.BooleanHelper.TRUE, + isFilterable = BasicField.BooleanHelper.TRUE, + analyzerName = "en.lucene") public List getTags() { return this.tags; } @@ -56,4 +62,12 @@ public boolean equals(Object o) { public int hashCode() { return Objects.hash(hotelId, tags); } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("HotelId", hotelId) + .writeArrayField("Tags", tags, JsonWriter::writeString) + .writeEndObject(); + } } 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 index 933e9e5e238b..e2a952b7db0f 100644 --- 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 @@ -3,35 +3,31 @@ 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.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; import com.azure.core.test.TestMode; -import com.azure.core.util.Context; +import com.azure.core.test.TestProxyTestBase; 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 com.azure.search.documents.models.AutocompleteResult; 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.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; @@ -70,40 +66,36 @@ protected static void cleanupClass() { @Test public void canAutocompleteThrowsWhenGivenBadSuggesterNameSync() { - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); - - PagedIterableBase results - = client.autocomplete("very po", "Invalid suggester", params, Context.NONE); + AutocompleteOptions options + = new AutocompleteOptions("very po", "Invalid suggester").setAutocompleteMode(AutocompleteMode.ONE_TERM); - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> results.iterableByPage().iterator().next()); + HttpResponseException ex = assertThrows(HttpResponseException.class, () -> client.autocomplete(options)); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); } @Test public void canAutocompleteThrowsWhenGivenBadSuggesterNameAsync() { - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); + AutocompleteOptions options + = new AutocompleteOptions("very po", "Invalid suggester").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()); - }); + StepVerifier.create(autocompleteWithResponseAsync(options)).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); + autocompleteAndValidateSync(client.autocomplete(new AutocompleteOptions("po", "sg")), expected, expected); } @Test public void canAutocompleteDefaultsToOneTermModeAsync() { List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg"), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(new AutocompleteOptions("po", "sg")), expected, expected); } @Test @@ -112,11 +104,10 @@ public void canAutocompleteOneTermWithContextSync() { 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); + AutocompleteOptions options = new AutocompleteOptions("looking for very po", "sg") + .setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT); - autocompleteAndValidateSync(client.autocomplete("looking for very po", "sg", params, Context.NONE), - expectedText, expectedQueryPlusText); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expectedText, expectedQueryPlusText); } @Test @@ -125,58 +116,50 @@ public void canAutocompleteOneTermWithContextAsync() { 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); + AutocompleteOptions options = new AutocompleteOptions("looking for very po", "sg") + .setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT); - autocompleteAndValidateAsync(asyncClient.autocomplete("looking for very po", "sg", params), expectedText, - expectedQueryPlusText); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expectedText, expectedQueryPlusText); } @Test public void canAutocompleteExcludesFieldsNotInSuggesterSync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); - params.setSearchFields("HotelName"); + AutocompleteOptions params + = new AutocompleteOptions("luxu", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setSearchFields("HotelName"); - Iterator results - = client.autocomplete("luxu", "sg", params, Context.NONE).iterableByPage().iterator(); + AutocompleteResult results = autocompleteWithResponseSync(params); - // One page, with 0 items - assertEquals(0, results.next().getValue().size()); - assertFalse(results.hasNext()); + assertEquals(0, results.getResults().size()); } @Test public void canAutocompleteExcludesFieldsNotInSuggesterAsync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); - params.setSearchFields("HotelName"); + AutocompleteOptions params + = new AutocompleteOptions("luxu", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setSearchFields("HotelName"); - StepVerifier.create(asyncClient.autocomplete("luxu", "sg", params).byPage()) - .assertNext(page -> assertEquals(0, page.getValue().size())) + StepVerifier.create(asyncClient.autocomplete(params)) + .assertNext(results -> assertEquals(0, results.getResults().size())) .verifyComplete(); } @Test public void canAutocompleteFuzzyIsOffByDefaultSync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); + AutocompleteOptions params = new AutocompleteOptions("pi", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM); - Iterator results - = client.autocomplete("pi", "sg", params, Context.NONE).iterableByPage().iterator(); + AutocompleteResult results = autocompleteWithResponseSync(params); - // One page, with 0 items - assertEquals(0, results.next().getValue().size()); - assertFalse(results.hasNext()); + assertEquals(0, results.getResults().size()); } @Test public void canAutocompleteFuzzyIsOffByDefaultAsync() { - AutocompleteOptions params = new AutocompleteOptions(); - params.setAutocompleteMode(AutocompleteMode.ONE_TERM); + AutocompleteOptions options + = new AutocompleteOptions("pi", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM); - StepVerifier.create(asyncClient.autocomplete("pi", "sg", params).byPage()) - .assertNext(page -> assertEquals(0, page.getValue().size())) + StepVerifier.create(asyncClient.autocomplete(options)) + .assertNext(results -> assertEquals(0, results.getResults().size())) .verifyComplete(); } @@ -184,18 +167,20 @@ public void canAutocompleteFuzzyIsOffByDefaultAsync() { public void canAutocompleteOneTermSync() { List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); + AutocompleteOptions options + = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM); - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test public void canAutocompleteOneTermAsync() { List expected = Arrays.asList("point", "police", "polite", "pool", "popular"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM); + AutocompleteOptions options + = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM); - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expected, expected); } @Test @@ -204,11 +189,11 @@ public void canAutocompleteStaticallyTypedDocumentsSync() { List expectedQueryPlusText = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular"); - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(false); + AutocompleteOptions options + = new AutocompleteOptions("very po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setUseFuzzyMatching(false); - autocompleteAndValidateSync(client.autocomplete("very po", "sg", params, Context.NONE), expectedText, - expectedQueryPlusText); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expectedText, expectedQueryPlusText); } @Test @@ -217,28 +202,27 @@ public void canAutocompleteStaticallyTypedDocumentsAsync() { List expectedQueryPlusText = Arrays.asList("very point", "very police", "very polite", "very pool", "very popular"); - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(false); + AutocompleteOptions options + = new AutocompleteOptions("very po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setUseFuzzyMatching(false); - autocompleteAndValidateAsync(asyncClient.autocomplete("very po", "sg", params), expectedText, - expectedQueryPlusText); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expectedText, expectedQueryPlusText); } @Test public void canAutocompleteThrowsWhenRequestIsMalformedSync() { - PagedIterableBase results = client.autocomplete("very po", ""); - - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> results.iterableByPage().iterator().next()); + HttpResponseException ex = assertThrows(HttpResponseException.class, + () -> client.autocomplete(new AutocompleteOptions("very po", ""))); 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()); - }); + StepVerifier.create(asyncClient.autocomplete(new AutocompleteOptions("very po", ""))) + .verifyErrorSatisfies(throwable -> { + HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); + }); } @Test @@ -246,9 +230,10 @@ 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); + AutocompleteOptions options + = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.TWO_TERMS); - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test @@ -256,9 +241,10 @@ 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); + AutocompleteOptions options + = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.TWO_TERMS); - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expected, expected); } @Test @@ -266,13 +252,12 @@ public void testAutocompleteCanUseHitHighlightingSync() { List expectedText = Arrays.asList("pool", "popular"); List expectedQueryPlusText = Arrays.asList("pool", "popular"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) + AutocompleteOptions options = new AutocompleteOptions("po", "sg").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); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expectedText, expectedQueryPlusText); } @Test @@ -280,187 +265,207 @@ public void testAutocompleteCanUseHitHighlightingAsync() { List expectedText = Arrays.asList("pool", "popular"); List expectedQueryPlusText = Arrays.asList("pool", "popular"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) + AutocompleteOptions options = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) .setFilter("HotelName eq 'EconoStay' or HotelName eq 'Fancy Stay'") .setHighlightPreTag("") .setHighlightPostTag(""); - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expectedText, expectedQueryPlusText); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expectedText, expectedQueryPlusText); } @Test public void testAutocompleteWithMultipleSelectedFieldsSync() { List expected = Arrays.asList("model", "modern"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setSearchFields("HotelName", "Description"); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setSearchFields("HotelName", "Description"); - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test public void testAutocompleteWithMultipleSelectedFieldsAsync() { List expected = Arrays.asList("model", "modern"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) - .setSearchFields("HotelName", "Description"); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setSearchFields("HotelName", "Description"); - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), 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'"); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setSearchFields("HotelName") + .setFilter("HotelId eq '7'"); - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), 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'"); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setSearchFields("HotelName") + .setFilter("HotelId eq '7'"); - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expected, expected); } @Test public void testAutocompleteTopTrimsResultsSync() { List expected = Arrays.asList("point", "police"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setTop(2); + AutocompleteOptions options + = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM).setTop(2); - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test public void testAutocompleteTopTrimsResultsAsync() { List expected = Arrays.asList("point", "police"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setTop(2); + AutocompleteOptions options + = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM).setTop(2); - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expected, expected); } @Test public void testAutocompleteWithFilterSync() { List expected = Collections.singletonList("polite"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) + AutocompleteOptions options = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) .setFilter("search.in(HotelId, '6,7')"); - autocompleteAndValidateSync(client.autocomplete("po", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test public void testAutocompleteWithFilterAsync() { List expected = Collections.singletonList("polite"); - AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM) + AutocompleteOptions options = new AutocompleteOptions("po", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) .setFilter("search.in(HotelId, '6,7')"); - autocompleteAndValidateAsync(asyncClient.autocomplete("po", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expected, expected); } @Test public void testAutocompleteOneTermWithContextWithFuzzySync() { List expected = Collections.singletonList("very polite"); - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT) + AutocompleteOptions options + = new AutocompleteOptions("very polit", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT) .setUseFuzzyMatching(true); - autocompleteAndValidateSync(client.autocomplete("very polit", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test public void testAutocompleteOneTermWithContextWithFuzzyAsync() { List expected = Collections.singletonList("very polite"); - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT) + AutocompleteOptions options + = new AutocompleteOptions("very polit", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM_WITH_CONTEXT) .setUseFuzzyMatching(true); - autocompleteAndValidateAsync(asyncClient.autocomplete("very polit", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), expected, expected); } @Test public void testAutocompleteOneTermWithFuzzySync() { List expected = Arrays.asList("model", "modern"); - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(true); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setUseFuzzyMatching(true); - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), expected, expected); } @Test public void testAutocompleteOneTermWithFuzzyAsync() { List expected = Arrays.asList("model", "modern"); - AutocompleteOptions params - = new AutocompleteOptions().setAutocompleteMode(AutocompleteMode.ONE_TERM).setUseFuzzyMatching(true); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.ONE_TERM) + .setUseFuzzyMatching(true); - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), 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); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.TWO_TERMS) + .setUseFuzzyMatching(true); - autocompleteAndValidateSync(client.autocomplete("mod", "sg", params, Context.NONE), expected, expected); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), 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); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").setAutocompleteMode(AutocompleteMode.TWO_TERMS) + .setUseFuzzyMatching(true); - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); + autocompleteAndValidateAsync(asyncClient.autocomplete(options), 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'))"); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").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); + autocompleteAndValidateSync(autocompleteWithResponseSync(options), 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'))"); + AutocompleteOptions options + = new AutocompleteOptions("mod", "sg").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(options), expected, expected); + } + + private AutocompleteResult autocompleteWithResponseSync(AutocompleteOptions options) { + return client.autocompleteWithResponse(options, new RequestOptions()).getValue(); + } - autocompleteAndValidateAsync(asyncClient.autocomplete("mod", "sg", params), expected, expected); + private Mono autocompleteWithResponseAsync(AutocompleteOptions options) { + return asyncClient.autocompleteWithResponse(options, new RequestOptions()).map(Response::getValue); } - private void autocompleteAndValidateSync(AutocompletePagedIterable autocomplete, List expectedTexts, + private static void autocompleteAndValidateSync(AutocompleteResult autocomplete, List expectedTexts, List expectedQueryPlusText) { - validateResults(autocomplete.stream().collect(Collectors.toList()), expectedTexts, expectedQueryPlusText); + validateResults(autocomplete.getResults(), expectedTexts, expectedQueryPlusText); } - private void autocompleteAndValidateAsync(AutocompletePagedFlux autocomplete, List expectedTexts, + private static void autocompleteAndValidateAsync(Mono autocomplete, List expectedTexts, List expectedQueryPlusText) { - StepVerifier.create(autocomplete.collectList()) - .assertNext(results -> validateResults(results, expectedTexts, expectedQueryPlusText)) + StepVerifier.create(autocomplete) + .assertNext(results -> validateResults(results.getResults(), expectedTexts, expectedQueryPlusText)) .verifyComplete(); } 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 index b1f7ed92e913..249c806db02d 100644 --- 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 @@ -11,7 +11,10 @@ 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.http.rest.RequestOptions; +import com.azure.core.http.rest.Response; import com.azure.core.test.utils.MockTokenCredential; +import com.azure.core.util.BinaryData; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; import com.azure.search.documents.indexes.SearchIndexAsyncClient; @@ -27,6 +30,7 @@ import reactor.test.StepVerifier; import java.time.Duration; +import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -54,7 +58,7 @@ public void searchClient() { Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - verifySync(() -> client.getDocumentCountWithResponse(context), expectedRequestId); + verifySync(client::getDocumentCountWithResponse, context, expectedRequestId); } @Test @@ -71,7 +75,8 @@ public void searchAsyncClient() { reactor.util.context.Context subscriberContext = reactor.util.context.Context .of(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - verifyAsync(client.getDocumentCountWithResponse().contextWrite(subscriberContext), expectedRequestId); + verifyAsync(client.getDocumentCount().contextWrite(subscriberContext), expectedRequestId); + verifyAsync(client.getDocumentCountWithResponse(null).contextWrite(subscriberContext), expectedRequestId); } @Test @@ -87,7 +92,7 @@ public void searchIndexClient() { Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - verifySync(() -> client.getIndexWithResponse("index", context), expectedRequestId); + verifySync(options -> client.getIndexWithResponse("index", options), context, expectedRequestId); } @Test @@ -103,7 +108,9 @@ public void searchIndexAsyncClient() { 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); + verifyAsync(client.getIndexStatistics("index").contextWrite(subscriberContext), expectedRequestId); + verifyAsync(client.getIndexStatisticsWithResponse("index", null).contextWrite(subscriberContext), + expectedRequestId); } @Test @@ -119,7 +126,7 @@ public void searchIndexerClient() { Context context = new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, createRequestIdHeaders(expectedRequestId)); - verifySync(() -> client.getIndexerWithResponse("indexer", context), expectedRequestId); + verifySync(options -> client.getIndexerWithResponse("indexer", options), context, expectedRequestId); } @Test @@ -135,15 +142,18 @@ public void searchIndexerAsyncClient() { 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); + verifyAsync(client.getIndexer("indexer").contextWrite(subscriberContext), expectedRequestId); + verifyAsync(client.getIndexerWithResponse("indexer", null).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); + private static void verifySync(Function> requestRunner, Context context, + String expectedRequestId) { + RuntimeException ex + = assertThrows(RuntimeException.class, () -> requestRunner.apply(new RequestOptions().setContext(context))); assertEquals(expectedRequestId, ex.getMessage()); } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FacetAggregationTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FacetAggregationTests.java index a2bfad21e17f..718390f2826b 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FacetAggregationTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FacetAggregationTests.java @@ -3,7 +3,6 @@ package com.azure.search.documents; -import com.azure.core.exception.HttpResponseException; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.test.TestMode; @@ -11,6 +10,7 @@ import com.azure.core.util.BinaryData; import com.azure.json.JsonProviders; import com.azure.json.JsonReader; +import com.azure.search.documents.implementation.SearchUtils; import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.indexes.SearchIndexClientBuilder; import com.azure.search.documents.indexes.models.SearchIndex; @@ -19,14 +19,14 @@ import com.azure.search.documents.indexes.models.SemanticPrioritizedFields; import com.azure.search.documents.indexes.models.SemanticSearch; import com.azure.search.documents.models.FacetResult; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.QueryType; import com.azure.search.documents.models.SearchOptions; -import com.azure.search.documents.models.SemanticSearchOptions; -import com.azure.search.documents.util.SearchPagedIterable; - +import com.azure.search.documents.models.SearchPagedResponse; import org.junit.jupiter.api.AfterAll; 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; @@ -34,15 +34,14 @@ import java.io.IOException; import java.io.UncheckedIOException; 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.loadResource; 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.SAME_THREAD) @@ -84,7 +83,7 @@ public void facetRequestSerializationWithAllMetrics() { SearchOptions searchOptions = new SearchOptions().setFacets("Rating, metric: min", "Rating, metric: max", "Rating, metric: avg", "Rating, metric: sum", "Category, metric: cardinality"); - String serialized = BinaryData.fromObject(searchOptions).toString(); + String serialized = BinaryData.fromObject(SearchUtils.fromSearchOptions(searchOptions)).toString(); assertTrue(serialized.contains("Rating, metric: min"), "Should serialize min metric"); assertTrue(serialized.contains("Rating, metric: max"), "Should serialize max metric"); assertTrue(serialized.contains("Rating, metric: avg"), "Should serialize avg metric"); @@ -94,14 +93,12 @@ public void facetRequestSerializationWithAllMetrics() { @Test public void facetRequestSerializationWithMultipleMetricsOnSameField() { - - List facets = Arrays.asList("Rating, metric: min", "Rating, metric: max", "Rating, metric: avg"); - - SearchOptions searchOptions = new SearchOptions().setFacets(facets.toArray(new String[0])); + SearchOptions searchOptions + = new SearchOptions().setFacets("Rating, metric: min", "Rating, metric: max", "Rating, metric: avg"); List serializedFacets = searchOptions.getFacets(); assertNotNull(serializedFacets, "Facets should not be null"); - assertEquals(serializedFacets.size(), 3, "Facet size should be 3"); + assertEquals(3, serializedFacets.size(), "Facet size should be 3"); assertTrue(serializedFacets.contains("Rating, metric: min"), "Should include min metric"); assertTrue(serializedFacets.contains("Rating, metric: max"), "Should include max metric"); @@ -110,11 +107,14 @@ public void facetRequestSerializationWithMultipleMetricsOnSameField() { @Test public void facetQueryWithMinAggregation() { - SearchOptions searchOptions = new SearchOptions().setFacets(("Rating, metric : min")); + SearchOptions searchOptions = new SearchOptions().setSearchText("*").setFacets("Rating, metric : min"); - SearchPagedIterable results - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", searchOptions, null); - Map> facets = results.getFacets(); + Map> facets = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(searchOptions) + .streamByPage() + .findFirst() + .map(SearchPagedResponse::getFacets) + .orElseThrow(IllegalStateException::new); assertNotNull(facets, "Facets should not be null"); assertTrue(facets.containsKey("Rating"), "Rating facet should be present"); @@ -128,11 +128,14 @@ public void facetQueryWithMinAggregation() { @Test public void facetQueryWithMaxAggregation() { - SearchOptions searchOptions = new SearchOptions().setFacets(("Rating, metric : max")); + SearchOptions searchOptions = new SearchOptions().setSearchText("*").setFacets("Rating, metric : max"); - SearchPagedIterable results - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", searchOptions, null); - Map> facets = results.getFacets(); + Map> facets = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(searchOptions) + .streamByPage() + .findFirst() + .map(SearchPagedResponse::getFacets) + .orElseThrow(IllegalStateException::new); assertNotNull(facets, "Facets should not be null"); assertTrue(facets.containsKey("Rating"), "Rating facet should be present"); @@ -146,11 +149,14 @@ public void facetQueryWithMaxAggregation() { @Test public void facetQueryWithAvgAggregation() { - SearchOptions searchOptions = new SearchOptions().setFacets(("Rating, metric : avg")); + SearchOptions searchOptions = new SearchOptions().setSearchText("*").setFacets("Rating, metric : avg"); - SearchPagedIterable results - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", searchOptions, null); - Map> facets = results.getFacets(); + Map> facets = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(searchOptions) + .streamByPage() + .findFirst() + .map(SearchPagedResponse::getFacets) + .orElseThrow(IllegalStateException::new); assertNotNull(facets, "Facets should not be null"); assertTrue(facets.containsKey("Rating"), "Rating facet should be present"); @@ -164,11 +170,15 @@ public void facetQueryWithAvgAggregation() { @Test public void facetQueryWithCardinalityAggregation() { - SearchOptions searchOptions = new SearchOptions().setFacets(("Category, metric : cardinality")); + SearchOptions searchOptions + = new SearchOptions().setSearchText("*").setFacets("Category, metric : cardinality"); - SearchPagedIterable results - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", searchOptions, null); - Map> facets = results.getFacets(); + Map> facets = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(searchOptions) + .streamByPage() + .findFirst() + .map(SearchPagedResponse::getFacets) + .orElseThrow(IllegalStateException::new); assertNotNull(facets, "Facets should not be null"); assertTrue(facets.containsKey("Category"), "Category facet should be present"); @@ -182,12 +192,15 @@ public void facetQueryWithCardinalityAggregation() { @Test public void facetQueryWithMultipleMetricsOnSameFieldResponseShape() { - SearchOptions searchOptions - = new SearchOptions().setFacets("Rating, metric: min", "Rating, metric: max", "Rating, metric: avg"); + SearchOptions searchOptions = new SearchOptions().setSearchText("*") + .setFacets("Rating, metric: min", "Rating, metric: max", "Rating, metric: avg"); - SearchPagedIterable results - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", searchOptions, null); - Map> facets = results.getFacets(); + Map> facets = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(searchOptions) + .streamByPage() + .findFirst() + .map(SearchPagedResponse::getFacets) + .orElseThrow(IllegalStateException::new); assertNotNull(facets); assertTrue(facets.containsKey("Rating")); @@ -205,15 +218,22 @@ public void facetQueryWithMultipleMetricsOnSameFieldResponseShape() { @Test public void facetQueryWithCardinalityPrecisionThreshold() { - SearchOptions defaultThreshold = new SearchOptions().setFacets("Category, metric : cardinality"); - - SearchOptions maxThreshold - = new SearchOptions().setFacets("Category, metric : cardinality, precisionThreshold: 40000"); - - SearchPagedIterable defaultResults - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", defaultThreshold, null); - SearchPagedIterable maxResults - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", maxThreshold, null); + SearchOptions defaultThreshold + = new SearchOptions().setSearchText("*").setFacets("Category, metric : cardinality"); + + SearchOptions maxThreshold = new SearchOptions().setSearchText("*") + .setFacets("Category, metric : cardinality, precisionThreshold: 40000"); + + SearchPagedResponse defaultResults = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(defaultThreshold) + .streamByPage() + .findFirst() + .orElseThrow(IllegalStateException::new); + SearchPagedResponse maxResults = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(maxThreshold) + .streamByPage() + .findFirst() + .orElseThrow(IllegalStateException::new); assertNotNull(defaultResults.getFacets().get("Category")); assertNotNull(maxResults.getFacets().get("Category")); @@ -229,13 +249,16 @@ public void facetQueryWithCardinalityPrecisionThreshold() { @Test public void facetMetricsWithSemanticQuery() { - SearchOptions searchOptions = new SearchOptions() + SearchOptions searchOptions = new SearchOptions().setSearchText("*") .setFacets("Rating, metric: min", "Rating, metric: max", "Category, metric: cardinality") .setQueryType(QueryType.SEMANTIC) - .setSemanticSearchOptions(new SemanticSearchOptions().setSemanticConfigurationName("semantic-config")); - SearchPagedIterable results - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient().search("*", searchOptions, null); - Map> facets = results.getFacets(); + .setSemanticConfigurationName("semantic-config"); + Map> facets = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() + .search(searchOptions) + .streamByPage() + .findFirst() + .map(SearchPagedResponse::getFacets) + .orElseThrow(IllegalStateException::new); assertNotNull(facets, "Facets should not be null"); assertTrue(facets.containsKey("Rating"), "Rating facet should be present"); @@ -249,28 +272,25 @@ public void facetMetricsWithSemanticQuery() { assertTrue(hasCategoryMetrics, "Category metrics should work with semantic query"); } - @Test - @Disabled("Issues with responses based on record or playback mode") - public void facetMetricsApiVersionCompatibility() { - SearchClient prevVersionClient - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).serviceVersion(SearchServiceVersion.V2025_09_01) - .buildClient(); - - SearchOptions searchOptions = new SearchOptions().setFacets("Rating, metric: min"); - - HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { - prevVersionClient.search("*", searchOptions, null).iterator().hasNext(); - }); - - int statusCode = exception.getResponse().getStatusCode(); - assertTrue(statusCode == 400 || statusCode == 401, "Should return 400 Bad Request or 401 Unauthorized"); - assertTrue( - exception.getMessage().contains("'metric' faceting") - || exception.getMessage().contains("not supported") - || exception.getMessage().contains("401"), - "Should fail due to unsupported facet metrics in previous API version"); - - } + // @Test + // @Disabled("Issues with responses based on record or playback mode") + // public void facetMetricsApiVersionCompatibility() { + // SearchClient prevVersionClient + // = getSearchClientBuilder(HOTEL_INDEX_NAME, true).serviceVersion(SearchServiceVersion.V2025_09_01) + // .buildClient(); + // + // SearchOptions searchOptions = new SearchOptions().setFacets("Rating, metric: min"); + // + // HttpResponseException exception = assertThrows(HttpResponseException.class, () -> prevVersionClient.search("*", searchOptions, null).iterator().hasNext()); + // + // int statusCode = exception.getResponse().getStatusCode(); + // assertTrue(statusCode == 400 || statusCode == 401, "Should return 400 Bad Request or 401 Unauthorized"); + // assertTrue( + // exception.getMessage().contains("'metric' faceting") + // || exception.getMessage().contains("not supported") + // || exception.getMessage().contains("401"), + // "Should fail due to unsupported facet metrics in previous API version"); + // } private static SearchIndexClient setupIndex() { try (JsonReader jsonReader = JsonProviders.createReader(loadResource(HOTELS_TESTS_INDEX_DATA_JSON))) { @@ -282,14 +302,13 @@ private static SearchIndexClient setupIndex() { .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) .buildClient(); - List semanticConfigurations - = Collections.singletonList(new SemanticConfiguration("semantic-config", - new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) - .setContentFields(new SemanticField("Description")) - .setKeywordsFields(new SemanticField("Category")))); + SemanticConfiguration semanticConfigurations = new SemanticConfiguration("semantic-config", + new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) + .setContentFields(new SemanticField("Description")) + .setKeywordsFields(new SemanticField("Category"))); SemanticSearch semanticSearch = new SemanticSearch().setDefaultConfigurationName("semantic-config") .setConfigurations(semanticConfigurations); - searchIndexClient.createOrUpdateIndex( + searchIndexClient.createIndex( TestHelpers.createTestIndex(HOTEL_INDEX_NAME, baseIndex).setSemanticSearch(semanticSearch)); return searchIndexClient; @@ -308,7 +327,9 @@ private static void uploadTestDocuments() { createHotel("7", 4, null, "Missing Category Hotel") // Missing category for default value testing ); - searchClient.uploadDocuments(hotels); + searchClient.index(new IndexDocumentsBatch(hotels.stream() + .map(hotel -> new IndexAction().setActionType(IndexActionType.UPLOAD).setAdditionalProperties(hotel)) + .collect(Collectors.toList()))); // Wait for indexing to complete Thread.sleep(3000); 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 index 5e218d41158b..3211b86c72d3 100644 --- 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 @@ -6,12 +6,18 @@ 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.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.models.SearchField; import com.azure.search.documents.indexes.models.SearchFieldDataType; import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.SearchOptions; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; @@ -23,6 +29,7 @@ import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -31,6 +38,8 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static com.azure.search.documents.TestHelpers.convertFromMapStringObject; + /** * This class tests indexes using OData type GeographyPoint. */ @@ -72,7 +81,11 @@ public static void createSharedIndex() { .buildClient(); searchIndexClient.createIndex(new SearchIndex(INDEX_NAME, SEARCH_FIELDS)); - searchIndexClient.getSearchClient(INDEX_NAME).uploadDocuments(getDocuments()); + searchIndexClient.getSearchClient(INDEX_NAME) + .index(new IndexDocumentsBatch(getDocuments().stream() + .map(document -> new IndexAction().setActionType(IndexActionType.UPLOAD) + .setAdditionalProperties(TestHelpers.convertToMapStringObject(document))) + .collect(Collectors.toList()))); TestHelpers.sleepIfRunningAgainstService(2000); } @@ -98,16 +111,20 @@ 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)); + actualDocuments.put("1", convertFromMapStringObject(searchClient.getDocument("1").getAdditionalProperties(), + SimpleDocument::fromJson)); + actualDocuments.put("2", convertFromMapStringObject(searchClient.getDocument("2").getAdditionalProperties(), + SimpleDocument::fromJson)); + actualDocuments.put("3", convertFromMapStringObject(searchClient.getDocument("3").getAdditionalProperties(), + SimpleDocument::fromJson)); + actualDocuments.put("4", convertFromMapStringObject(searchClient.getDocument("4").getAdditionalProperties(), + SimpleDocument::fromJson)); compareMaps(expectedDocuments, actualDocuments, Assertions::assertEquals); - actualDocuments = searchClient.search("Tourist location", new SearchOptions().setOrderBy("id"), Context.NONE) + actualDocuments = searchClient.search(new SearchOptions().setSearchText("Tourist location").setOrderBy("id")) .stream() - .map(doc -> doc.getDocument(SimpleDocument.class)) + .map(doc -> convertFromMapStringObject(doc.getAdditionalProperties(), SimpleDocument::fromJson)) .collect(Collectors.toMap(SimpleDocument::getId, Function.identity())); compareMaps(expectedDocuments, actualDocuments, Assertions::assertEquals); @@ -118,7 +135,8 @@ public void canRoundTripGeographyPointsAsync() { Map expectedDocuments = getExpectedDocuments(); Mono> getDocumentsByIdMono = Flux.just("1", "2", "3", "4") - .flatMap(id -> searchAsyncClient.getDocument(id, SimpleDocument.class)) + .flatMap(id -> searchAsyncClient.getDocument(id)) + .map(doc -> convertFromMapStringObject(doc.getAdditionalProperties(), SimpleDocument::fromJson)) .collectMap(SimpleDocument::getId); StepVerifier.create(getDocumentsByIdMono) @@ -126,8 +144,8 @@ public void canRoundTripGeographyPointsAsync() { .verifyComplete(); Mono> searchDocumentsMono - = searchAsyncClient.search("Tourist location", new SearchOptions().setOrderBy("id")) - .map(doc -> doc.getDocument(SimpleDocument.class)) + = searchAsyncClient.search(new SearchOptions().setSearchText("Tourist location").setOrderBy("id")) + .map(doc -> convertFromMapStringObject(doc.getAdditionalProperties(), SimpleDocument::fromJson)) .collectMap(SimpleDocument::getId); StepVerifier.create(searchDocumentsMono) @@ -135,7 +153,7 @@ public void canRoundTripGeographyPointsAsync() { .verifyComplete(); } - public static final class SimpleDocument { + public static final class SimpleDocument implements JsonSerializable { @JsonProperty("id") private final String id; @@ -185,5 +203,39 @@ public boolean equals(Object obj) { public int hashCode() { return Objects.hash(id, geoPoint.getCoordinates(), description); } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("id", id) + .writeJsonField("geography_point", geoPoint) + .writeStringField("description", description) + .writeEndObject(); + } + + public static SimpleDocument fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + String id = null; + GeoPoint geoPoint = null; + String description = null; + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("id".equals(fieldName)) { + id = reader.getString(); + } else if ("geography_point".equals(fieldName)) { + geoPoint = GeoPoint.fromJson(reader); + } else if ("description".equals(fieldName)) { + description = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return new SimpleDocument(id, geoPoint, 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 index f5ada36401d4..23168e9c9489 100644 --- 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 @@ -4,22 +4,26 @@ 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.TestProxyTestBase; import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.util.Context; +import com.azure.json.JsonReader; +import com.azure.json.JsonSerializable; +import com.azure.json.ReadValueCallback; import com.azure.search.documents.indexes.SearchIndexClient; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; +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.IndexDocumentsBatch; 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 com.azure.search.documents.testingmodels.Author; +import com.azure.search.documents.testingmodels.Book; +import com.azure.search.documents.testingmodels.Hotel; +import com.azure.search.documents.testingmodels.HotelAddress; +import com.azure.search.documents.testingmodels.HotelRoom; +import com.azure.search.documents.testingmodels.LoudHotel; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; @@ -30,7 +34,6 @@ import reactor.test.StepVerifier; import java.net.HttpURLConnection; -import java.time.Instant; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -38,19 +41,23 @@ 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 java.util.stream.Collectors; 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.convertFromMapStringObject; +import static com.azure.search.documents.TestHelpers.convertToIndexAction; +import static com.azure.search.documents.TestHelpers.convertToMapStringObject; +import static com.azure.search.documents.TestHelpers.createIndexAction; 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.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -130,9 +137,10 @@ public void indexDoesNotThrowWhenAllActionsSucceedSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String expectedHotelId = getRandomDocumentKey(); - List hotels = Collections.singletonList(new Hotel().hotelId(expectedHotelId)); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + convertToIndexAction(new Hotel().hotelId(expectedHotelId), IndexActionType.UPLOAD)); - List result = client.uploadDocuments(hotels).getResults(); + List result = client.indexDocuments(batch).getResults(); assertIndexActionSucceeded(expectedHotelId, result.get(0), 201); } @@ -146,9 +154,10 @@ public void indexDoesNotThrowWhenAllActionsSucceedAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String expectedHotelId = getRandomDocumentKey(); - List hotels = Collections.singletonList(new Hotel().hotelId(expectedHotelId)); + IndexDocumentsBatch batch = new IndexDocumentsBatch( + convertToIndexAction(new Hotel().hotelId(expectedHotelId), IndexActionType.UPLOAD)); - StepVerifier.create(asyncClient.uploadDocuments(hotels)) + StepVerifier.create(asyncClient.indexDocuments(batch)) .assertNext(result -> assertIndexActionSucceeded(expectedHotelId, result.getResults().get(0), 201)) .verifyComplete(); } @@ -163,12 +172,11 @@ public void canIndexWithPascalCaseFieldsSync() { SearchClient client = getClient(BOOKS_INDEX_NAME); String isbn = getRandomDocumentKey(); - List books = new ArrayList<>(); - books.add(new Book().ISBN(isbn) + IndexDocumentsBatch batch = new IndexDocumentsBatch(convertToIndexAction(new Book().ISBN(isbn) .title("Lord of the Rings") - .author(new Author().firstName("J.R.R").lastName("Tolkien"))); + .author(new Author().firstName("J.R.R").lastName("Tolkien")), IndexActionType.UPLOAD)); - List result = client.uploadDocuments(books).getResults(); + List result = client.indexDocuments(batch).getResults(); assertIndexActionSucceeded(isbn, result.get(0), 201); } @@ -182,12 +190,11 @@ public void canIndexWithPascalCaseFieldsAsync() { SearchAsyncClient asyncClient = getAsyncClient(BOOKS_INDEX_NAME); String isbn = getRandomDocumentKey(); - List books = new ArrayList<>(); - books.add(new Book().ISBN(isbn) + IndexDocumentsBatch batch = new IndexDocumentsBatch(convertToIndexAction(new Book().ISBN(isbn) .title("Lord of the Rings") - .author(new Author().firstName("J.R.R").lastName("Tolkien"))); + .author(new Author().firstName("J.R.R").lastName("Tolkien")), IndexActionType.UPLOAD)); - StepVerifier.create(asyncClient.uploadDocuments(books)) + StepVerifier.create(asyncClient.indexDocuments(batch)) .assertNext(result -> assertIndexActionSucceeded(isbn, result.getResults().get(0), 201)) .verifyComplete(); } @@ -204,12 +211,15 @@ public void canDeleteBatchByKeysSync() { String hotel1Key = getRandomDocumentKey(); String hotel2Key = getRandomDocumentKey(); - client.uploadDocuments(Arrays.asList(new Hotel().hotelId(hotel1Key), new Hotel().hotelId(hotel2Key))); + client.indexDocuments( + new IndexDocumentsBatch(convertToIndexAction(new Hotel().hotelId(hotel1Key), IndexActionType.UPLOAD), + convertToIndexAction(new Hotel().hotelId(hotel2Key), IndexActionType.UPLOAD))); waitForIndexing(); - IndexDocumentsBatch deleteBatch - = new IndexDocumentsBatch().addDeleteActions("HotelId", Arrays.asList(hotel1Key, hotel2Key)); + IndexDocumentsBatch deleteBatch = new IndexDocumentsBatch( + createIndexAction(IndexActionType.DELETE, Collections.singletonMap("HotelId", hotel1Key)), + createIndexAction(IndexActionType.DELETE, Collections.singletonMap("HotelId", hotel2Key))); IndexDocumentsResult documentIndexResult = client.indexDocuments(deleteBatch); @@ -230,13 +240,17 @@ public void canDeleteBatchByKeysAsync() { String hotel1Key = getRandomDocumentKey(); String hotel2Key = getRandomDocumentKey(); - asyncClient.uploadDocuments(Arrays.asList(new Hotel().hotelId(hotel1Key), new Hotel().hotelId(hotel2Key))) + asyncClient + .indexDocuments( + new IndexDocumentsBatch(convertToIndexAction(new Hotel().hotelId(hotel1Key), IndexActionType.UPLOAD), + convertToIndexAction(new Hotel().hotelId(hotel2Key), IndexActionType.UPLOAD))) .block(); waitForIndexing(); - IndexDocumentsBatch deleteBatch - = new IndexDocumentsBatch().addDeleteActions("HotelId", Arrays.asList(hotel1Key, hotel2Key)); + IndexDocumentsBatch deleteBatch = new IndexDocumentsBatch( + createIndexAction(IndexActionType.DELETE, Collections.singletonMap("HotelId", hotel1Key)), + createIndexAction(IndexActionType.DELETE, Collections.singletonMap("HotelId", hotel2Key))); StepVerifier.create(asyncClient.indexDocuments(deleteBatch)).assertNext(result -> { assertEquals(2, result.getResults().size()); @@ -256,13 +270,13 @@ public void indexDoesNotThrowWhenDeletingDocumentWithExtraFieldsSync() { String hotelId = getRandomDocumentKey(); Hotel hotel = new Hotel().hotelId(hotelId).category("Luxury"); - List hotels = Collections.singletonList(hotel); - client.uploadDocuments(hotels); + client.indexDocuments(new IndexDocumentsBatch(convertToIndexAction(hotel, IndexActionType.UPLOAD))); waitForIndexing(); hotel.category("ignored"); - IndexDocumentsResult documentIndexResult = client.deleteDocuments(hotels); + IndexDocumentsResult documentIndexResult + = client.indexDocuments(new IndexDocumentsBatch(convertToIndexAction(hotel, IndexActionType.DELETE))); assertEquals(1, documentIndexResult.getResults().size()); assertIndexActionSucceeded(hotelId, documentIndexResult.getResults().get(0), 200); @@ -279,17 +293,21 @@ public void indexDoesNotThrowWhenDeletingDocumentWithExtraFieldsAsync() { String hotelId = getRandomDocumentKey(); Hotel hotel = new Hotel().hotelId(hotelId).category("Luxury"); - List hotels = Collections.singletonList(hotel); - asyncClient.uploadDocuments(hotels).block(); + asyncClient.indexDocuments(new IndexDocumentsBatch(convertToIndexAction(hotel, IndexActionType.UPLOAD))) + .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(); + StepVerifier + .create(asyncClient + .indexDocuments(new IndexDocumentsBatch(convertToIndexAction(hotel, IndexActionType.DELETE)))) + .assertNext(result -> { + assertEquals(1, result.getResults().size()); + assertIndexActionSucceeded(hotelId, result.getResults().get(0), 200); + }) + .verifyComplete(); } @Test @@ -302,17 +320,17 @@ public void indexDoesNotThrowWhenDeletingDynamicDocumentWithExtraFieldsSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument searchDocument = new SearchDocument(); + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("HotelId", hotelId); searchDocument.put("Category", "Luxury"); - List docs = Collections.singletonList(searchDocument); - client.uploadDocuments(docs); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, searchDocument))); waitForIndexing(); searchDocument.put("Category", "ignored"); - IndexDocumentsResult documentIndexResult = client.deleteDocuments(docs); + IndexDocumentsResult documentIndexResult + = client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.DELETE, searchDocument))); assertEquals(1, documentIndexResult.getResults().size()); assertIndexActionSucceeded(hotelId, documentIndexResult.getResults().get(0), 200); @@ -328,20 +346,24 @@ public void indexDoesNotThrowWhenDeletingDynamicDocumentWithExtraFieldsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument searchDocument = new SearchDocument(); + Map searchDocument = new LinkedHashMap<>(); searchDocument.put("HotelId", hotelId); searchDocument.put("Category", "Luxury"); - List docs = Collections.singletonList(searchDocument); - asyncClient.uploadDocuments(docs).block(); + asyncClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, searchDocument))) + .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(); + StepVerifier + .create(asyncClient + .indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.DELETE, searchDocument)))) + .assertNext(result -> { + assertEquals(1, result.getResults().size()); + assertIndexActionSucceeded(hotelId, result.getResults().get(0), 200); + }) + .verifyComplete(); } @Test @@ -362,15 +384,14 @@ public void canIndexStaticallyTypedDocumentsSync() { 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)); + IndexDocumentsBatch batch = new IndexDocumentsBatch(convertToIndexAction(hotel1, IndexActionType.UPLOAD), + convertToIndexAction(randomHotel, IndexActionType.DELETE), + convertToIndexAction(nonExistingHotel, IndexActionType.MERGE), + convertToIndexAction(hotel3, IndexActionType.MERGE_OR_UPLOAD), + convertToIndexAction(hotel2, IndexActionType.UPLOAD)); - IndexBatchException ex = assertThrows(IndexBatchException.class, () -> client.indexDocumentsWithResponse(batch, - new IndexDocumentsOptions().setThrowOnAnyError(true), Context.NONE)); + IndexBatchException ex = assertThrows(IndexBatchException.class, + () -> client.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(true), null)); List results = ex.getIndexingResults(); assertEquals(results.size(), batch.getActions().size()); @@ -382,7 +403,7 @@ public void canIndexStaticallyTypedDocumentsSync() { assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); for (Hotel hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - Hotel actual = client.getDocument(hotel.hotelId(), Hotel.class); + Hotel actual = getAndConvertDocument(client, hotel.hotelId(), Hotel::fromJson); assertObjectEquals(hotel, actual, true); } } @@ -405,15 +426,16 @@ public void canIndexStaticallyTypedDocumentsAsync() { 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)); + IndexDocumentsBatch batch + = new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(hotel1)), + createIndexAction(IndexActionType.DELETE, convertToMapStringObject(randomHotel)), + createIndexAction(IndexActionType.MERGE, convertToMapStringObject(nonExistingHotel)), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, convertToMapStringObject(hotel3)), + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(hotel2))); StepVerifier - .create(asyncClient.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(true))) + .create(asyncClient.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(true), + null)) .verifyErrorSatisfies(throwable -> { IndexBatchException ex = assertInstanceOf(IndexBatchException.class, throwable); @@ -428,7 +450,8 @@ public void canIndexStaticallyTypedDocumentsAsync() { }); for (Hotel hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - getAndValidateDocumentAsync(asyncClient, hotel.hotelId(), Hotel.class, hotel, + getAndValidateDocumentAsync(asyncClient, hotel.hotelId(), hotel, + map -> convertFromMapStringObject(map, Hotel::fromJson), (expected, actual) -> assertObjectEquals(expected, actual, true)); } } @@ -445,21 +468,20 @@ public void canIndexDynamicDocumentsNotThrowSync() { 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); + Map hotel1 = prepareDynamicallyTypedHotel(hotel1Id); + Map hotel2 = prepareDynamicallyTypedHotel(hotel2Id); + Map hotel3 = prepareDynamicallyTypedHotel(hotel3Id); + Map nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document + Map randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document + + IndexDocumentsBatch batch = new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, hotel1), + createIndexAction(IndexActionType.DELETE, randomHotel), + createIndexAction(IndexActionType.MERGE, nonExistingHotel), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, hotel3), + createIndexAction(IndexActionType.UPLOAD, hotel3)); + + Response resultResponse + = client.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(false), null); List results = resultResponse.getValue().getResults(); assertEquals(207, resultResponse.getStatusCode()); assertSuccessfulIndexResult(results.get(0), hotel1Id, 201); @@ -468,8 +490,8 @@ public void canIndexDynamicDocumentsNotThrowSync() { 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); + for (Map hotel : Arrays.asList(hotel1, hotel2, hotel3)) { + Map actual = client.getDocument(hotel.get("HotelId").toString()).getAdditionalProperties(); assertMapEquals(hotel, actual, true); } } @@ -486,22 +508,21 @@ public void canIndexDynamicDocumentsNotThrowAsync() { 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)); + Map hotel1 = prepareDynamicallyTypedHotel(hotel1Id); + Map hotel2 = prepareDynamicallyTypedHotel(hotel2Id); + Map hotel3 = prepareDynamicallyTypedHotel(hotel3Id); + Map nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document + Map randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document + + IndexDocumentsBatch batch = new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, hotel1), + createIndexAction(IndexActionType.DELETE, randomHotel), + createIndexAction(IndexActionType.MERGE, nonExistingHotel), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, hotel3), + createIndexAction(IndexActionType.UPLOAD, hotel2)); StepVerifier - .create( - asyncClient.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(false))) + .create(asyncClient.indexDocumentsWithResponse(batch, new IndexDocumentsOptions().setThrowOnAnyError(false), + null)) .assertNext(resultResponse -> { List results = resultResponse.getValue().getResults(); assertEquals(207, resultResponse.getStatusCode()); @@ -513,8 +534,8 @@ public void canIndexDynamicDocumentsNotThrowAsync() { }) .verifyComplete(); - for (SearchDocument hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - getAndValidateDocumentAsync(asyncClient, hotel.get("HotelId").toString(), SearchDocument.class, hotel, + for (Map hotel : Arrays.asList(hotel1, hotel2, hotel3)) { + getAndValidateDocumentAsync(asyncClient, hotel.get("HotelId").toString(), hotel, map -> map, (expected, actual) -> assertMapEquals(expected, actual, true)); } } @@ -531,18 +552,17 @@ public void canIndexDynamicDocumentsThrowOnErrorSync() { 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)); + Map hotel1 = prepareDynamicallyTypedHotel(hotel1Id); + Map hotel2 = prepareDynamicallyTypedHotel(hotel2Id); + Map hotel3 = prepareDynamicallyTypedHotel(hotel3Id); + Map nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document + Map randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document + + IndexDocumentsBatch batch = new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, hotel1), + createIndexAction(IndexActionType.DELETE, randomHotel), + createIndexAction(IndexActionType.MERGE, nonExistingHotel), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, hotel3), + createIndexAction(IndexActionType.UPLOAD, hotel2)); IndexBatchException ex = assertThrows(IndexBatchException.class, () -> client.indexDocuments(batch)); List results = ex.getIndexingResults(); @@ -554,8 +574,8 @@ public void canIndexDynamicDocumentsThrowOnErrorSync() { 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); + for (Map hotel : Arrays.asList(hotel1, hotel2, hotel3)) { + Map actual = client.getDocument(hotel.get("HotelId").toString()).getAdditionalProperties(); assertMapEquals(hotel, actual, true); } } @@ -572,18 +592,17 @@ public void canIndexDynamicDocumentsThrowOnErrorAsync() { 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)); + Map hotel1 = prepareDynamicallyTypedHotel(hotel1Id); + Map hotel2 = prepareDynamicallyTypedHotel(hotel2Id); + Map hotel3 = prepareDynamicallyTypedHotel(hotel3Id); + Map nonExistingHotel = prepareDynamicallyTypedHotel("nonExistingHotel"); // deleting a non existing document + Map randomHotel = prepareDynamicallyTypedHotel("randomId"); // deleting a non existing document + + IndexDocumentsBatch batch = new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, hotel1), + createIndexAction(IndexActionType.DELETE, randomHotel), + createIndexAction(IndexActionType.MERGE, nonExistingHotel), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, hotel3), + createIndexAction(IndexActionType.UPLOAD, hotel2)); StepVerifier.create(asyncClient.indexDocuments(batch)).verifyErrorSatisfies(throwable -> { IndexBatchException ex = assertInstanceOf(IndexBatchException.class, throwable); @@ -598,8 +617,8 @@ public void canIndexDynamicDocumentsThrowOnErrorAsync() { assertSuccessfulIndexResult(results.get(4), hotel2Id, 201); }); - for (SearchDocument hotel : Arrays.asList(hotel1, hotel2, hotel3)) { - getAndValidateDocumentAsync(asyncClient, hotel.get("HotelId").toString(), SearchDocument.class, hotel, + for (Map hotel : Arrays.asList(hotel1, hotel2, hotel3)) { + getAndValidateDocumentAsync(asyncClient, hotel.get("HotelId").toString(), hotel, map -> map, (expected, actual) -> assertMapEquals(expected, actual, true)); } } @@ -608,49 +627,55 @@ public void canIndexDynamicDocumentsThrowOnErrorAsync() { public void indexWithInvalidDocumentThrowsExceptionSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); - List docs = Collections.singletonList(new SearchDocument()); - - assertHttpResponseException(() -> client.uploadDocuments(docs), HttpURLConnection.HTTP_BAD_REQUEST, null); + assertHttpResponseException( + () -> client.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, new LinkedHashMap<>()))), + 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)) + StepVerifier + .create(asyncClient.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, new LinkedHashMap<>())))) .verifyErrorSatisfies( throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_BAD_REQUEST, null)); } @Test - public void canRoundtripBoundaryValuesSync() { + public void canRoundTripBoundaryValuesSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); List boundaryConditionDocs = getBoundaryValues(); - client.uploadDocuments(boundaryConditionDocs); + client.indexDocuments(new IndexDocumentsBatch(boundaryConditionDocs.stream() + .map(doc -> createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(doc))) + .collect(Collectors.toList()))); waitForIndexing(); for (Hotel expected : boundaryConditionDocs) { - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); + Hotel actual = getAndConvertDocument(client, expected.hotelId(), Hotel::fromJson); assertObjectEquals(expected, actual, true); } } @Test - public void canRoundtripBoundaryValuesAsync() { + public void canRoundTripBoundaryValuesAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); List boundaryConditionDocs = getBoundaryValues(); - asyncClient.uploadDocuments(boundaryConditionDocs).block(); + asyncClient.indexDocuments(new IndexDocumentsBatch(boundaryConditionDocs.stream() + .map(doc -> createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(doc))) + .collect(Collectors.toList()))).block(); waitForIndexing(); for (Hotel expected : boundaryConditionDocs) { - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, + getAndValidateDocumentAsync(asyncClient, expected.hotelId(), expected, + map -> convertFromMapStringObject(map, Hotel::fromJson), (ignored, actual) -> assertObjectEquals(expected, actual, true)); } } @@ -665,23 +690,24 @@ public void dynamicDocumentDateTimesRoundTripAsUtcSync() { = OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)); String isbn1 = getRandomDocumentKey(); - Map book1 = new HashMap<>(); + Map book1 = new LinkedHashMap<>(); book1.put("ISBN", isbn1); book1.put("PublishDate", utcTime); String isbn2 = getRandomDocumentKey(); - Map book2 = new HashMap<>(); + Map book2 = new LinkedHashMap<>(); book2.put("ISBN", isbn2); book2.put("PublishDate", utcTimeMinusEight); - client.uploadDocuments(Arrays.asList(book1, book2)); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, book1), + createIndexAction(IndexActionType.UPLOAD, book2))); waitForIndexing(); - SearchDocument actualBook1 = client.getDocument(isbn1, SearchDocument.class); + Map actualBook1 = client.getDocument(isbn1).getAdditionalProperties(); 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); + Map actualBook2 = client.getDocument(isbn2).getAdditionalProperties(); assertEquals( utcTimeMinusEight.withOffsetSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), actualBook2.get("PublishDate")); @@ -697,24 +723,25 @@ public void dynamicDocumentDateTimesRoundTripAsUtcAsync() { = OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)); String isbn1 = getRandomDocumentKey(); - SearchDocument book1 = new SearchDocument(); + Map book1 = new LinkedHashMap<>(); book1.put("ISBN", isbn1); book1.put("PublishDate", utcTime); String isbn2 = getRandomDocumentKey(); - SearchDocument book2 = new SearchDocument(); + Map book2 = new LinkedHashMap<>(); book2.put("ISBN", isbn2); book2.put("PublishDate", utcTimeMinusEight); - asyncClient.uploadDocuments(Arrays.asList(book1, book2)).block(); + asyncClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, book1), + createIndexAction(IndexActionType.UPLOAD, book2))).block(); waitForIndexing(); - getAndValidateDocumentAsync(asyncClient, isbn1, SearchDocument.class, book1, (expected, + getAndValidateDocumentAsync(asyncClient, isbn1, book1, map -> map, (ignored, 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( + getAndValidateDocumentAsync(asyncClient, isbn2, book2, map -> map, + (ignored, actual) -> assertEquals( utcTimeMinusEight.withOffsetSameInstant(ZoneOffset.UTC).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), actual.get("PublishDate"))); } @@ -731,13 +758,15 @@ public void staticallyTypedDateTimesRoundTripAsUtcSync() { new Book().ISBN(isbn2) .publishDate(OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)))); - client.uploadDocuments(books); + client.indexDocuments(new IndexDocumentsBatch(books.stream() + .map(book -> createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(book))) + .collect(Collectors.toList()))); - Book actualBook1 = client.getDocument(isbn1, Book.class); + Book actualBook1 = getAndConvertDocument(client, isbn1, Book::fromJson); assertEquals(books.get(0).publishDate(), actualBook1.publishDate()); // Azure AI Search normalizes to UTC, so we compare instants - Book actualBook2 = client.getDocument(isbn2, Book.class); + Book actualBook2 = getAndConvertDocument(client, isbn2, Book::fromJson); assertEquals(books.get(1).publishDate().withOffsetSameInstant(ZoneOffset.UTC), actualBook2.publishDate().withOffsetSameInstant(ZoneOffset.UTC)); } @@ -754,14 +783,16 @@ public void staticallyTypedDateTimesRoundTripAsUtcAsync() { new Book().ISBN(isbn2) .publishDate(OffsetDateTime.of(LocalDateTime.of(2010, 1, 1, 0, 0, 0), ZoneOffset.ofHours(-8)))); - asyncClient.uploadDocuments(books).block(); + asyncClient.indexDocuments(new IndexDocumentsBatch(books.stream() + .map(book -> createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(book))) + .collect(Collectors.toList()))).block(); - getAndValidateDocumentAsync(asyncClient, isbn1, Book.class, null, - (expected, actual) -> assertEquals(books.get(0).publishDate(), actual.publishDate())); + getAndValidateDocumentAsync(asyncClient, isbn1, null, map -> convertFromMapStringObject(map, Book::fromJson), + (ignored, 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), + getAndValidateDocumentAsync(asyncClient, isbn2, null, map -> convertFromMapStringObject(map, Book::fromJson), + (ignored, actual) -> assertEquals(books.get(1).publishDate().withOffsetSameInstant(ZoneOffset.UTC), actual.publishDate().withOffsetSameInstant(ZoneOffset.UTC))); } @@ -780,14 +811,16 @@ public void canMergeStaticallyTypedDocumentsSync() { // 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.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(originalDoc)))); - client.mergeDocuments(Collections.singletonList(updatedDoc)); - assertObjectEquals(expectedDoc, client.getDocument(hotelId, Hotel.class), true); + client.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, convertToMapStringObject(updatedDoc)))); + assertObjectEquals(expectedDoc, getAndConvertDocument(client, hotelId, Hotel::fromJson), true); - client.mergeDocuments(originalDocs); - assertObjectEquals(originalDoc, client.getDocument(hotelId, Hotel.class), true); + client.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, convertToMapStringObject(originalDoc)))); + assertObjectEquals(originalDoc, getAndConvertDocument(client, hotelId, Hotel::fromJson), true); } @Test @@ -805,17 +838,27 @@ public void canMergeStaticallyTypedDocumentsAsync() { // 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 + .indexDocuments(new IndexDocumentsBatch( + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(originalDoc)))) + .block(); - asyncClient.mergeDocuments(Collections.singletonList(updatedDoc)).block(); + asyncClient + .indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, convertToMapStringObject(updatedDoc)))) + .block(); - getAndValidateDocumentAsync(asyncClient, hotelId, Hotel.class, expectedDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, expectedDoc, + map -> convertFromMapStringObject(map, Hotel::fromJson), (expected, actual) -> assertObjectEquals(expected, actual, true)); - asyncClient.mergeDocuments(originalDocs).block(); + asyncClient + .indexDocuments(new IndexDocumentsBatch( + createIndexAction(IndexActionType.MERGE, convertToMapStringObject(originalDoc)))) + .block(); - getAndValidateDocumentAsync(asyncClient, hotelId, Hotel.class, originalDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, originalDoc, + map -> convertFromMapStringObject(map, Hotel::fromJson), (expected, actual) -> assertObjectEquals(expected, actual, true)); } @@ -830,7 +873,8 @@ public void mergeDocumentWithoutExistingKeyThrowsIndexingExceptionSync() { String hotelId = getRandomDocumentKey(); IndexBatchException ex = assertThrows(IndexBatchException.class, - () -> client.mergeDocuments(Collections.singletonList(prepareStaticallyTypedHotel(hotelId)))); + () -> client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, + convertToMapStringObject(prepareStaticallyTypedHotel(hotelId)))))); List results = ex.getIndexingResults(); assertFailedIndexResult(results.get(0), hotelId, HttpResponseStatus.NOT_FOUND.code()); @@ -847,7 +891,8 @@ public void mergeDocumentWithoutExistingKeyThrowsIndexingExceptionAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - StepVerifier.create(asyncClient.mergeDocuments(Collections.singletonList(prepareStaticallyTypedHotel(hotelId)))) + StepVerifier.create(asyncClient.indexDocuments(new IndexDocumentsBatch( + createIndexAction(IndexActionType.MERGE, convertToMapStringObject(prepareStaticallyTypedHotel(hotelId)))))) .verifyErrorSatisfies(throwable -> { IndexBatchException ex = assertInstanceOf(IndexBatchException.class, throwable); @@ -866,20 +911,22 @@ public void canSetExplicitNullsInStaticallyTypedDocumentSync() { LoudHotel updatedDoc = canSetExplicitNullsInStaticallyTypedDocumentUpdated(hotelId); LoudHotel expectedDoc = canSetExplicitNullsInStaticallyTypedDocumentExpected(hotelId); - List originalDocs = Collections.singletonList(originalDoc); - client.uploadDocuments(originalDocs); + client.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(originalDoc)))); waitForIndexing(); - client.mergeDocuments(Collections.singletonList(updatedDoc)); + client.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, convertToMapStringObject(updatedDoc)))); waitForIndexing(); - LoudHotel actualDoc1 = client.getDocument(hotelId, LoudHotel.class); + LoudHotel actualDoc1 = getAndConvertDocument(client, hotelId, LoudHotel::fromJson); assertObjectEquals(expectedDoc, actualDoc1, true); - client.uploadDocuments(originalDocs); + client.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(originalDoc)))); waitForIndexing(); - LoudHotel actualDoc2 = client.getDocument(hotelId, LoudHotel.class); + LoudHotel actualDoc2 = getAndConvertDocument(client, hotelId, LoudHotel::fromJson); assertObjectEquals(originalDoc, actualDoc2, true); } @@ -892,20 +939,30 @@ public void canSetExplicitNullsInStaticallyTypedDocumentAsync() { LoudHotel updatedDoc = canSetExplicitNullsInStaticallyTypedDocumentUpdated(hotelId); LoudHotel expectedDoc = canSetExplicitNullsInStaticallyTypedDocumentExpected(hotelId); - List originalDocs = Collections.singletonList(originalDoc); - asyncClient.uploadDocuments(originalDocs).block(); + asyncClient + .indexDocuments(new IndexDocumentsBatch( + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(originalDoc)))) + .block(); waitForIndexing(); - asyncClient.mergeDocuments(Collections.singletonList(updatedDoc)).block(); + asyncClient + .indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, convertToMapStringObject(updatedDoc)))) + .block(); waitForIndexing(); - getAndValidateDocumentAsync(asyncClient, hotelId, LoudHotel.class, expectedDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, expectedDoc, + map -> convertFromMapStringObject(map, LoudHotel::fromJson), (expected, actual) -> assertObjectEquals(expected, actual, true)); - asyncClient.uploadDocuments(originalDocs).block(); + asyncClient + .indexDocuments(new IndexDocumentsBatch( + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(originalDoc)))) + .block(); waitForIndexing(); - getAndValidateDocumentAsync(asyncClient, hotelId, LoudHotel.class, originalDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, originalDoc, + map -> convertFromMapStringObject(map, LoudHotel::fromJson), (expected, actual) -> assertObjectEquals(expected, actual, true)); } @@ -914,24 +971,23 @@ public void canMergeDynamicDocumentsSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = canMergeDynamicDocumentsOriginal(hotelId); - SearchDocument updatedDoc = canMergeDynamicDocumentsUpdated(hotelId); - SearchDocument expectedDoc = canMergeDynamicDocumentsExpected(hotelId); + Map originalDoc = canMergeDynamicDocumentsOriginal(hotelId); + Map updatedDoc = canMergeDynamicDocumentsUpdated(hotelId); + Map expectedDoc = canMergeDynamicDocumentsExpected(hotelId); - List originalDocs = Collections.singletonList(originalDoc); - client.mergeOrUploadDocuments(originalDocs); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE_OR_UPLOAD, originalDoc))); waitForIndexing(); - client.mergeDocuments(Collections.singletonList(updatedDoc)); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, updatedDoc))); waitForIndexing(); - SearchDocument actualDoc = client.getDocument(hotelId, SearchDocument.class); + Map actualDoc = client.getDocument(hotelId).getAdditionalProperties(); assertObjectEquals(expectedDoc, actualDoc, true); - client.mergeOrUploadDocuments(originalDocs); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE_OR_UPLOAD, originalDoc))); waitForIndexing(); - actualDoc = client.getDocument(hotelId, SearchDocument.class); + actualDoc = client.getDocument(hotelId).getAdditionalProperties(); assertMapEquals(originalDoc, actualDoc, false, "properties"); } @@ -940,24 +996,28 @@ public void canMergeDynamicDocumentsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = canMergeDynamicDocumentsOriginal(hotelId); - SearchDocument updatedDoc = canMergeDynamicDocumentsUpdated(hotelId); - SearchDocument expectedDoc = canMergeDynamicDocumentsExpected(hotelId); + Map originalDoc = canMergeDynamicDocumentsOriginal(hotelId); + Map updatedDoc = canMergeDynamicDocumentsUpdated(hotelId); + Map expectedDoc = canMergeDynamicDocumentsExpected(hotelId); - List originalDocs = Collections.singletonList(originalDoc); - asyncClient.mergeOrUploadDocuments(originalDocs).block(); + asyncClient + .indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE_OR_UPLOAD, originalDoc))) + .block(); waitForIndexing(); - asyncClient.mergeDocuments(Collections.singletonList(updatedDoc)).block(); + asyncClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, updatedDoc))) + .block(); waitForIndexing(); - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, expectedDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, expectedDoc, map -> map, (expected, actual) -> assertObjectEquals(expected, actual, true)); - asyncClient.mergeOrUploadDocuments(originalDocs).block(); + asyncClient + .indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE_OR_UPLOAD, originalDoc))) + .block(); waitForIndexing(); - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, originalDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, originalDoc, map -> map, (expected, actual) -> assertObjectEquals(expected, actual, true, "properties")); } @@ -970,33 +1030,45 @@ public void canIndexAndAccessResponseSync() { String hotel3Id = getRandomDocumentKey(); String hotel4Id = getRandomDocumentKey(); - List hotelsToUpload = Arrays.asList(new Hotel().hotelId(hotel1Id), new Hotel().hotelId(hotel2Id)); + List hotelsToUpload = Arrays.asList( + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(new Hotel().hotelId(hotel1Id))), + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(new Hotel().hotelId(hotel2Id)))); - List hotelsToMerge = Collections.singletonList(new Hotel().hotelId(hotel1Id).rating(5)); + IndexAction hotelsToMerge = createIndexAction(IndexActionType.MERGE, + convertToMapStringObject(new Hotel().hotelId(hotel1Id).rating(5))); - List hotelsToMergeOrUpload - = Arrays.asList(new Hotel().hotelId(hotel3Id).rating(4), new Hotel().hotelId(hotel4Id).rating(1)); + List hotelsToMergeOrUpload = Arrays.asList( + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, + convertToMapStringObject(new Hotel().hotelId(hotel3Id).rating(4))), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, + convertToMapStringObject(new Hotel().hotelId(hotel4Id).rating(1)))); - List hotelsToDelete = Collections.singletonList(new Hotel().hotelId(hotel4Id)); + IndexAction hotelsToDelete + = createIndexAction(IndexActionType.DELETE, convertToMapStringObject(new Hotel().hotelId(hotel4Id))); - IndexDocumentsBatch batch = new IndexDocumentsBatch().addUploadActions(hotelsToUpload) - .addMergeOrUploadActions(hotelsToMergeOrUpload); + List batchActions = new ArrayList<>(); + batchActions.addAll(hotelsToUpload); + batchActions.addAll(hotelsToMergeOrUpload); + IndexDocumentsBatch batch = new IndexDocumentsBatch(batchActions); - validateIndexResponseSync(client.uploadDocumentsWithResponse(hotelsToUpload, null, Context.NONE), 2); + validateIndexResponseSync( + client.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToUpload), null, null), 2); waitForIndexing(); - validateIndexResponseSync(client.mergeDocumentsWithResponse(hotelsToMerge, null, Context.NONE), 1); - validateIndexResponseSync(client.mergeOrUploadDocumentsWithResponse(hotelsToMergeOrUpload, null, Context.NONE), - 2); + validateIndexResponseSync(client.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToMerge), null, null), + 1); + validateIndexResponseSync( + client.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToMergeOrUpload), null, null), 2); waitForIndexing(); - validateIndexResponseSync(client.deleteDocumentsWithResponse(hotelsToDelete, null, Context.NONE), 1); + validateIndexResponseSync( + client.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToDelete), null, null), 1); waitForIndexing(); - validateIndexResponseSync(client.indexDocumentsWithResponse(batch, null, Context.NONE), 4); + validateIndexResponseSync(client.indexDocumentsWithResponse(batch, null, null), 4); waitForIndexing(); - assertEquals(4, client.getDocument(hotel3Id, SearchDocument.class).get("Rating")); + assertEquals(4, client.getDocument(hotel3Id).getAdditionalProperties().get("Rating")); } @Test @@ -1008,43 +1080,62 @@ public void canIndexAndAccessResponseAsync() { String hotel3Id = getRandomDocumentKey(); String hotel4Id = getRandomDocumentKey(); - List hotelsToUpload = Arrays.asList(new Hotel().hotelId(hotel1Id), new Hotel().hotelId(hotel2Id)); + List hotelsToUpload = Arrays.asList( + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(new Hotel().hotelId(hotel1Id))), + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(new Hotel().hotelId(hotel2Id)))); - List hotelsToMerge = Collections.singletonList(new Hotel().hotelId(hotel1Id).rating(5)); + IndexAction hotelsToMerge = createIndexAction(IndexActionType.MERGE, + convertToMapStringObject(new Hotel().hotelId(hotel1Id).rating(5))); - List hotelsToMergeOrUpload - = Arrays.asList(new Hotel().hotelId(hotel3Id).rating(4), new Hotel().hotelId(hotel4Id).rating(1)); + List hotelsToMergeOrUpload = Arrays.asList( + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, + convertToMapStringObject(new Hotel().hotelId(hotel3Id).rating(4))), + createIndexAction(IndexActionType.MERGE_OR_UPLOAD, + convertToMapStringObject(new Hotel().hotelId(hotel4Id).rating(1)))); - List hotelsToDelete = Collections.singletonList(new Hotel().hotelId(hotel4Id)); + IndexAction hotelsToDelete + = createIndexAction(IndexActionType.DELETE, convertToMapStringObject(new Hotel().hotelId(hotel4Id))); - IndexDocumentsBatch batch = new IndexDocumentsBatch().addUploadActions(hotelsToUpload) - .addMergeOrUploadActions(hotelsToMergeOrUpload); + List batchActions = new ArrayList<>(); + batchActions.addAll(hotelsToUpload); + batchActions.addAll(hotelsToMergeOrUpload); + IndexDocumentsBatch batch = new IndexDocumentsBatch(batchActions); - validateIndexResponseAsync(asyncClient.uploadDocumentsWithResponse(hotelsToUpload, null), 2); + validateIndexResponseAsync( + asyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToUpload), null, null), 2); waitForIndexing(); - validateIndexResponseAsync(asyncClient.mergeDocumentsWithResponse(hotelsToMerge, null), 1); - validateIndexResponseAsync(asyncClient.mergeOrUploadDocumentsWithResponse(hotelsToMergeOrUpload, null), 2); + validateIndexResponseAsync( + asyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToMerge), null, null), 1); + validateIndexResponseAsync( + asyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToMergeOrUpload), null, null), 2); waitForIndexing(); - validateIndexResponseAsync(asyncClient.deleteDocumentsWithResponse(hotelsToDelete, null), 1); + validateIndexResponseAsync( + asyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch(hotelsToDelete), null, null), 1); waitForIndexing(); - validateIndexResponseAsync(asyncClient.indexDocumentsWithResponse(batch, null), 4); + validateIndexResponseAsync(asyncClient.indexDocumentsWithResponse(batch, null, null), 4); waitForIndexing(); - getAndValidateDocumentAsync(asyncClient, hotel3Id, SearchDocument.class, null, - (expected, actual) -> assertEquals(4, actual.get("Rating"))); + getAndValidateDocumentAsync(asyncClient, hotel3Id, null, map -> map, + (ignored, 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)) + private static > T getAndConvertDocument(SearchClient client, String key, + ReadValueCallback converter) { + return convertFromMapStringObject(client.getDocument(key).getAdditionalProperties(), converter); + } + + private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, T expected, + ReadValueCallback, T> converter, BiConsumer comparator) { + StepVerifier.create(asyncClient.getDocument(key)) + .assertNext(actual -> comparator.accept(expected, + assertDoesNotThrow(() -> converter.read(actual.getAdditionalProperties())))) .verifyComplete(); } @@ -1065,10 +1156,12 @@ private static void validateIndexResponseAsync(Mono prepareDynamicallyTypedHotel(String hotelId) { - SearchDocument room1 = new SearchDocument(); + Map room1 = new LinkedHashMap<>(); room1.put("Description", "Budget Room, 1 Queen Bed"); room1.put("Description_fr", null); room1.put("Type", "Budget Room"); @@ -1095,7 +1188,7 @@ SearchDocument prepareDynamicallyTypedHotel(String hotelId) { room1.put("SmokingAllowed", true); room1.put("Tags", Arrays.asList("vcr/dvd", "great view")); - SearchDocument room2 = new SearchDocument(); + Map room2 = new LinkedHashMap<>(); room2.put("Description", "Budget Room, 1 King Bed"); room2.put("Description_fr", null); room2.put("Type", "Budget Room"); @@ -1105,9 +1198,9 @@ SearchDocument prepareDynamicallyTypedHotel(String hotelId) { room2.put("SmokingAllowed", true); room2.put("Tags", Arrays.asList("vcr/dvd", "seaside view")); - List rooms = Arrays.asList(room1, room2); + List> rooms = Arrays.asList(room1, room2); - SearchDocument address = new SearchDocument(); + Map address = new LinkedHashMap<>(); address.put("StreetAddress", "One Microsoft way"); address.put("City", "Redmond"); address.put("StateProvince", "Washington"); @@ -1115,19 +1208,21 @@ SearchDocument prepareDynamicallyTypedHotel(String hotelId) { address.put("Country", "US"); // TODO (alzimmer): Determine if this should be used to create the hotel document. - SearchDocument location = new SearchDocument(); + Map location = new LinkedHashMap<>(); location.put("type", "Point"); location.put("coordinates", Arrays.asList(-122.131577, 47.678581)); location.put("crs", null); - SearchDocument hotel = new SearchDocument(); + Map hotel = new LinkedHashMap<>(); 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."); + "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("Location", location); hotel.put("Category", "Luxury"); hotel.put("Tags", Arrays.asList("pool", "view", "wifi", "concierge")); hotel.put("LastRenovationDate", OffsetDateTime.parse("2019-01-30T00:00:00Z")); @@ -1159,17 +1254,13 @@ static void assertIndexActionSucceeded(String key, IndexingResult result, int ex 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 + .lastRenovationDate(OffsetDateTime.of(1, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)) + .location(new GeoPoint(-180.0, -90.0)) // South Pole, date line from the west .parkingIncluded(false) .rating(Integer.MIN_VALUE) .tags(Collections.emptyList()) @@ -1178,9 +1269,8 @@ List getBoundaryValues() { // 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 + .lastRenovationDate(OffsetDateTime.of(9999, 12, 31, 23, 59, 59, 0, ZoneOffset.UTC)) + .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. @@ -1217,10 +1307,13 @@ 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.") + .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) @@ -1253,7 +1346,8 @@ private static Hotel canMergeStaticallyTypedDocumentsOriginal(String key) { } private static Hotel canMergeStaticallyTypedDocumentsUpdated(String key) { - // Update category, tags, parking included, rating, and rooms. Erase description, last renovation date, location and address. + // 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) @@ -1277,10 +1371,13 @@ 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.") + .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) @@ -1305,10 +1402,13 @@ private static Hotel canMergeStaticallyTypedDocumentsExpected(String key) { 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.") + .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) @@ -1363,8 +1463,10 @@ private static LoudHotel canSetExplicitNullsInStaticallyTypedDocumentExpected(St 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.") + .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) @@ -1390,14 +1492,17 @@ private static LoudHotel canSetExplicitNullsInStaticallyTypedDocumentExpected(St .tags(new String[] { "vcr/dvd", "balcony" }))); } - private static SearchDocument canMergeDynamicDocumentsOriginal(String key) { - SearchDocument originalDoc = new SearchDocument(); + private static Map canMergeDynamicDocumentsOriginal(String key) { + Map originalDoc = new LinkedHashMap<>(); 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("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); @@ -1406,7 +1511,7 @@ private static SearchDocument canMergeDynamicDocumentsOriginal(String key) { originalDoc.put("Rating", 4); originalDoc.put("Location", new GeoPoint(-73.965403, 40.760586)); - SearchDocument originalAddress = new SearchDocument(); + Map originalAddress = new LinkedHashMap<>(); originalAddress.put("StreetAddress", "677 5th Ave"); originalAddress.put("City", "New York"); originalAddress.put("StateProvince", "NY"); @@ -1414,7 +1519,7 @@ private static SearchDocument canMergeDynamicDocumentsOriginal(String key) { originalAddress.put("Country", "USA"); originalDoc.put("Address", originalAddress); - SearchDocument originalRoom1 = new SearchDocument(); + Map originalRoom1 = new LinkedHashMap<>(); 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"); @@ -1424,7 +1529,7 @@ private static SearchDocument canMergeDynamicDocumentsOriginal(String key) { originalRoom1.put("SmokingAllowed", true); originalRoom1.put("Tags", Collections.singletonList("vcr/dvd")); - SearchDocument originalRoom2 = new SearchDocument(); + Map originalRoom2 = new LinkedHashMap<>(); 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"); @@ -1439,8 +1544,8 @@ private static SearchDocument canMergeDynamicDocumentsOriginal(String key) { return originalDoc; } - private static SearchDocument canMergeDynamicDocumentsUpdated(String key) { - SearchDocument updatedDoc = new SearchDocument(); + private static Map canMergeDynamicDocumentsUpdated(String key) { + Map updatedDoc = new LinkedHashMap<>(); updatedDoc.put("HotelId", key); updatedDoc.put("Description", null); updatedDoc.put("Category", "Economy"); @@ -1449,9 +1554,9 @@ private static SearchDocument canMergeDynamicDocumentsUpdated(String key) { updatedDoc.put("LastRenovationDate", null); updatedDoc.put("Rating", 3); updatedDoc.put("Location", null); - updatedDoc.put("Address", new SearchDocument()); + updatedDoc.put("Address", new LinkedHashMap<>()); - SearchDocument updatedRoom1 = new SearchDocument(); + Map updatedRoom1 = new LinkedHashMap<>(); updatedRoom1.put("Description", null); updatedRoom1.put("Type", "Budget Room"); updatedRoom1.put("BaseRate", 10.5); @@ -1464,13 +1569,15 @@ private static SearchDocument canMergeDynamicDocumentsUpdated(String key) { return updatedDoc; } - private static SearchDocument canMergeDynamicDocumentsExpected(String key) { - SearchDocument expectedDoc = new SearchDocument(); + private static Map canMergeDynamicDocumentsExpected(String key) { + Map expectedDoc = new LinkedHashMap<>(); 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("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); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeBaseTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeBaseTests.java index ff44cd647d02..57daf04397fb 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeBaseTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeBaseTests.java @@ -15,12 +15,6 @@ import com.azure.core.util.BinaryData; import com.azure.json.JsonProviders; import com.azure.json.JsonReader; -import com.azure.search.documents.knowledgebases.SearchKnowledgeBaseAsyncClient; -import com.azure.search.documents.knowledgebases.SearchKnowledgeBaseClient; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessage; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageTextContent; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; -import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; import com.azure.search.documents.indexes.SearchIndexAsyncClient; import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.indexes.SearchIndexClientBuilder; @@ -38,7 +32,12 @@ 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.knowledgebases.KnowledgeBaseRetrievalAsyncClient; +import com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClient; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessage; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseMessageTextContent; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalRequest; +import com.azure.search.documents.knowledgebases.models.KnowledgeBaseRetrievalResponse; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -54,7 +53,6 @@ import java.io.IOException; import java.io.UncheckedIOException; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; @@ -83,10 +81,9 @@ public class KnowledgeBaseTests extends SearchTestBase { .setDeploymentName(KNOWLEDGEBASE_DEPLOYMENT_NAME) .setResourceUrl(OPENAI_ENDPOINT) .setAuthIdentity(new SearchIndexerDataUserAssignedIdentity(USER_ASSIGNED_IDENTITY))); - private static final List KNOWLEDGE_BASE_MODELS - = Collections.singletonList(OPEN_AI_KNOWLEDGEBASE_MODEL); - private static final List KNOWLEDGE_SOURCE_REFERENCES - = Collections.singletonList(new KnowledgeSourceReference(HOTEL_KNOWLEDGE_SOURCE_NAME)); + private static final KnowledgeBaseModel KNOWLEDGE_BASE_MODEL = OPEN_AI_KNOWLEDGEBASE_MODEL; + private static final KnowledgeSourceReference KNOWLEDGE_SOURCE_REFERENCE + = new KnowledgeSourceReference(HOTEL_KNOWLEDGE_SOURCE_NAME); private static SearchIndexClient searchIndexClient; @@ -153,8 +150,8 @@ protected static void cleanupClass() { public void createKnowledgeBaseSync() { // Test creating a knowledge knowledgebase. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); KnowledgeBase created = searchIndexClient.createKnowledgeBase(knowledgeBase); assertEquals(knowledgeBase.getName(), created.getName()); @@ -180,8 +177,8 @@ public void createKnowledgeBaseSync() { public void createKnowledgeBaseAsync() { // Test creating a knowledge knowledgebase. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); StepVerifier.create(searchIndexClient.createKnowledgeBase(knowledgeBase)).assertNext(created -> { assertEquals(knowledgeBase.getName(), created.getName()); @@ -208,8 +205,8 @@ public void createKnowledgeBaseAsync() { public void getKnowledgeBaseSync() { // Test getting a knowledge knowledgebase. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); searchIndexClient.createKnowledgeBase(knowledgeBase); KnowledgeBase retrieved = searchIndexClient.getKnowledgeBase(knowledgeBase.getName()); @@ -236,8 +233,8 @@ public void getKnowledgeBaseSync() { public void getKnowledgeBaseAsync() { // Test getting a knowledge knowledgebase. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); Mono createAndGet = searchIndexClient.createKnowledgeBase(knowledgeBase) .flatMap(created -> searchIndexClient.getKnowledgeBase(created.getName())); @@ -268,10 +265,10 @@ public void listKnowledgeBasesSync() { // Test listing knowledge knowledgebases. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); long currentCount = searchIndexClient.listKnowledgeBases().stream().count(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); - KnowledgeBase knowledgeBase2 = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); + KnowledgeBase knowledgeBase2 + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); searchIndexClient.createKnowledgeBase(knowledgeBase); searchIndexClient.createKnowledgeBase(knowledgeBase2); Map knowledgeBasesByName = searchIndexClient.listKnowledgeBases() @@ -290,10 +287,10 @@ public void listKnowledgeBasesSync() { public void listKnowledgeBasesAsync() { // Test listing knowledge knowledgebases. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); - KnowledgeBase knowledgeBase2 = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); + KnowledgeBase knowledgeBase2 + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); Mono>> tuple2Mono = searchIndexClient.listKnowledgeBases() .count() @@ -318,8 +315,8 @@ public void listKnowledgeBasesAsync() { public void deleteKnowledgeBaseSync() { // Test deleting a knowledge knowledgebase. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); searchIndexClient.createKnowledgeBase(knowledgeBase); assertEquals(knowledgeBase.getName(), searchIndexClient.getKnowledgeBase(knowledgeBase.getName()).getName()); @@ -332,8 +329,8 @@ public void deleteKnowledgeBaseSync() { public void deleteKnowledgeBaseAsync() { // Test deleting a knowledge base. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); Mono createAndGetMono = searchIndexClient.createKnowledgeBase(knowledgeBase) .flatMap(created -> searchIndexClient.getKnowledgeBase(created.getName())); @@ -353,12 +350,12 @@ public void deleteKnowledgeBaseAsync() { public void updateKnowledgeBaseSync() { // Test updating a knowledge base. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); searchIndexClient.createKnowledgeBase(knowledgeBase); String newDescription = "Updated description"; knowledgeBase.setDescription(newDescription); - searchIndexClient.createOrUpdateKnowledgeBase(knowledgeBase); + searchIndexClient.createKnowledgeBase(knowledgeBase); KnowledgeBase retrieved = searchIndexClient.getKnowledgeBase(knowledgeBase.getName()); assertEquals(newDescription, retrieved.getDescription()); } @@ -368,12 +365,12 @@ public void updateKnowledgeBaseSync() { public void updateKnowledgeBaseAsync() { // Test updating a knowledge base. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); String newDescription = "Updated description"; Mono createUpdateAndGetMono = searchIndexClient.createKnowledgeBase(knowledgeBase) - .flatMap(created -> searchIndexClient.createOrUpdateKnowledgeBase(created.setDescription(newDescription))) + .flatMap(created -> searchIndexClient.createKnowledgeBase(created.setDescription(newDescription))) .flatMap(updated -> searchIndexClient.getKnowledgeBase(updated.getName())); StepVerifier.create(createUpdateAndGetMono) @@ -386,21 +383,19 @@ public void updateKnowledgeBaseAsync() { public void basicRetrievalSync() { // Test knowledge base retrieval functionality. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); searchIndexClient.createKnowledgeBase(knowledgeBase); - SearchKnowledgeBaseClient knowledgeBaseClient - = getSearchKnowledgeBaseClientBuilder(true).knowledgeBaseName(knowledgeBase.getName()).buildClient(); + KnowledgeBaseRetrievalClient knowledgeBaseClient = getKnowledgeBaseRetrievalClientBuilder(true).buildClient(); KnowledgeBaseMessageTextContent messageTextContent = new KnowledgeBaseMessageTextContent("What are the pet policies at the hotel?"); - KnowledgeBaseMessage message - = new KnowledgeBaseMessage(Collections.singletonList(messageTextContent)).setRole("user"); - KnowledgeBaseRetrievalRequest retrievalRequest - = new KnowledgeBaseRetrievalRequest().setMessages(Collections.singletonList(message)); + KnowledgeBaseMessage message = new KnowledgeBaseMessage(messageTextContent).setRole("user"); + KnowledgeBaseRetrievalRequest retrievalRequest = new KnowledgeBaseRetrievalRequest().setMessages(message); - KnowledgeBaseRetrievalResponse response = knowledgeBaseClient.retrieve(retrievalRequest, null); + KnowledgeBaseRetrievalResponse response + = knowledgeBaseClient.retrieve(knowledgeBase.getName(), retrievalRequest); assertNotNull(response); assertNotNull(response.getResponse()); } @@ -410,23 +405,21 @@ public void basicRetrievalSync() { public void basicRetrievalAsync() { // Test knowledge base retrieval functionality. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); Mono createAndRetrieveMono = searchIndexClient.createKnowledgeBase(knowledgeBase).flatMap(created -> { - SearchKnowledgeBaseAsyncClient knowledgeBaseClient - = getSearchKnowledgeBaseClientBuilder(false).knowledgeBaseName(created.getName()) - .buildAsyncClient(); + KnowledgeBaseRetrievalAsyncClient knowledgeBaseClient + = getKnowledgeBaseRetrievalClientBuilder(false).buildAsyncClient(); KnowledgeBaseMessageTextContent messageTextContent = new KnowledgeBaseMessageTextContent("What are the pet policies at the hotel?"); - KnowledgeBaseMessage message - = new KnowledgeBaseMessage(Collections.singletonList(messageTextContent)).setRole("user"); + KnowledgeBaseMessage message = new KnowledgeBaseMessage(messageTextContent).setRole("user"); KnowledgeBaseRetrievalRequest retrievalRequest - = new KnowledgeBaseRetrievalRequest().setMessages(Collections.singletonList(message)); + = new KnowledgeBaseRetrievalRequest().setMessages(message); - return knowledgeBaseClient.retrieve(retrievalRequest, null); + return knowledgeBaseClient.retrieve(created.getName(), retrievalRequest); }); StepVerifier.create(createAndRetrieveMono).assertNext(response -> { @@ -440,22 +433,20 @@ public void basicRetrievalAsync() { public void basicRetrievalWithReasoningEffortSync() { // Test knowledge base retrieval functionality. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); searchIndexClient.createKnowledgeBase(knowledgeBase); - SearchKnowledgeBaseClient knowledgeBaseClient - = getSearchKnowledgeBaseClientBuilder(true).knowledgeBaseName(knowledgeBase.getName()).buildClient(); + KnowledgeBaseRetrievalClient knowledgeBaseClient = getKnowledgeBaseRetrievalClientBuilder(true).buildClient(); KnowledgeBaseMessageTextContent messageTextContent = new KnowledgeBaseMessageTextContent("What are the pet policies at the hotel?"); - KnowledgeBaseMessage message - = new KnowledgeBaseMessage(Collections.singletonList(messageTextContent)).setRole("user"); - KnowledgeBaseRetrievalRequest retrievalRequest - = new KnowledgeBaseRetrievalRequest().setMessages(Collections.singletonList(message)); + KnowledgeBaseMessage message = new KnowledgeBaseMessage(messageTextContent).setRole("user"); + KnowledgeBaseRetrievalRequest retrievalRequest = new KnowledgeBaseRetrievalRequest().setMessages(message); // .setRetrievalReasoningEffort(KnowledgeRetrievalReasoningEffortKind.MEDIUM); // TODO: Missing enum - KnowledgeBaseRetrievalResponse response = knowledgeBaseClient.retrieve(retrievalRequest, null); + KnowledgeBaseRetrievalResponse response + = knowledgeBaseClient.retrieve(knowledgeBase.getName(), retrievalRequest); assertNotNull(response); assertNotNull(response.getResponse()); } @@ -465,24 +456,22 @@ public void basicRetrievalWithReasoningEffortSync() { public void basicRetrievalWithReasoningEffortAsync() { // Test knowledge base retrieval functionality. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); Mono createAndRetrieveMono = searchIndexClient.createKnowledgeBase(knowledgeBase).flatMap(created -> { - SearchKnowledgeBaseAsyncClient knowledgeBaseClient - = getSearchKnowledgeBaseClientBuilder(false).knowledgeBaseName(created.getName()) - .buildAsyncClient(); + KnowledgeBaseRetrievalAsyncClient knowledgeBaseClient + = getKnowledgeBaseRetrievalClientBuilder(false).buildAsyncClient(); KnowledgeBaseMessageTextContent messageTextContent = new KnowledgeBaseMessageTextContent("What are the pet policies at the hotel?"); - KnowledgeBaseMessage message - = new KnowledgeBaseMessage(Collections.singletonList(messageTextContent)).setRole("user"); + KnowledgeBaseMessage message = new KnowledgeBaseMessage(messageTextContent).setRole("user"); KnowledgeBaseRetrievalRequest retrievalRequest - = new KnowledgeBaseRetrievalRequest().setMessages(Collections.singletonList(message)); + = new KnowledgeBaseRetrievalRequest().setMessages(message); // .setRetrievalReasoningEffort(KnowledgeRetrievalReasoningEffortKind.MEDIUM); // TODO: Missing enum - return knowledgeBaseClient.retrieve(retrievalRequest, null); + return knowledgeBaseClient.retrieve(created.getName(), retrievalRequest); }); StepVerifier.create(createAndRetrieveMono).assertNext(response -> { @@ -497,21 +486,19 @@ public void answerSynthesisRetrievalSync() { // Test knowledge base retrieval functionality. SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); KnowledgeBase knowledgeBase - = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES).setModels(KNOWLEDGE_BASE_MODELS) + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL) .setRetrievalInstructions("Only include well reviewed hotels."); searchIndexClient.createKnowledgeBase(knowledgeBase); - SearchKnowledgeBaseClient knowledgeBaseClient - = getSearchKnowledgeBaseClientBuilder(true).knowledgeBaseName(knowledgeBase.getName()).buildClient(); + KnowledgeBaseRetrievalClient knowledgeBaseClient = getKnowledgeBaseRetrievalClientBuilder(true).buildClient(); KnowledgeBaseMessageTextContent messageTextContent = new KnowledgeBaseMessageTextContent("What are the pet policies at the hotel?"); - KnowledgeBaseMessage message - = new KnowledgeBaseMessage(Collections.singletonList(messageTextContent)).setRole("user"); - KnowledgeBaseRetrievalRequest retrievalRequest - = new KnowledgeBaseRetrievalRequest().setMessages(Collections.singletonList(message)); + KnowledgeBaseMessage message = new KnowledgeBaseMessage(messageTextContent).setRole("user"); + KnowledgeBaseRetrievalRequest retrievalRequest = new KnowledgeBaseRetrievalRequest().setMessages(message); - KnowledgeBaseRetrievalResponse response = knowledgeBaseClient.retrieve(retrievalRequest, null); + KnowledgeBaseRetrievalResponse response + = knowledgeBaseClient.retrieve(knowledgeBase.getName(), retrievalRequest); assertNotNull(response); assertNotNull(response.getResponse()); assertNotNull(response.getActivity()); @@ -523,22 +510,20 @@ public void answerSynthesisRetrievalAsync() { // Test knowledge base retrieval functionality. SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); KnowledgeBase knowledgeBase - = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES).setModels(KNOWLEDGE_BASE_MODELS) + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL) .setRetrievalInstructions("Only include well reviewed hotels."); Mono createAndRetrieveMono = searchIndexClient.createKnowledgeBase(knowledgeBase).flatMap(created -> { - SearchKnowledgeBaseAsyncClient knowledgeBaseClient - = getSearchKnowledgeBaseClientBuilder(false).knowledgeBaseName(created.getName()) - .buildAsyncClient(); + KnowledgeBaseRetrievalAsyncClient knowledgeBaseClient + = getKnowledgeBaseRetrievalClientBuilder(false).buildAsyncClient(); KnowledgeBaseMessageTextContent messageTextContent = new KnowledgeBaseMessageTextContent("What are the pet policies at the hotel?"); - KnowledgeBaseMessage message - = new KnowledgeBaseMessage(Collections.singletonList(messageTextContent)).setRole("user"); + KnowledgeBaseMessage message = new KnowledgeBaseMessage(messageTextContent).setRole("user"); KnowledgeBaseRetrievalRequest retrievalRequest - = new KnowledgeBaseRetrievalRequest().setMessages(Collections.singletonList(message)); + = new KnowledgeBaseRetrievalRequest().setMessages(message); - return knowledgeBaseClient.retrieve(retrievalRequest, null); + return knowledgeBaseClient.retrieve(created.getName(), retrievalRequest); }); StepVerifier.create(createAndRetrieveMono).assertNext(response -> { @@ -552,8 +537,8 @@ public void answerSynthesisRetrievalAsync() { @Disabled("Requires further resource deployment") public void knowledgeBaseObjectHasNoAgentReferences() { SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); - KnowledgeBase knowledgeBase = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCES) - .setModels(KNOWLEDGE_BASE_MODELS); + KnowledgeBase knowledgeBase + = new KnowledgeBase(randomKnowledgeBaseName(), KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); KnowledgeBase created = searchIndexClient.createKnowledgeBase(knowledgeBase); String kbJson = BinaryData.fromObject(created).toString(); @@ -575,7 +560,7 @@ public void knowledgeBaseEndpointsUseKnowledgeBasesPath() { String kbName = randomKnowledgeBaseName(); KnowledgeBase knowledgeBase - = new KnowledgeBase(kbName, KNOWLEDGE_SOURCE_REFERENCES).setModels(KNOWLEDGE_BASE_MODELS); + = new KnowledgeBase(kbName, KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); client.createKnowledgeBase(knowledgeBase); @@ -615,7 +600,7 @@ public void knowledgeSourcesEndpointUnchanged() { String kbName = randomKnowledgeBaseName(); KnowledgeBase knowledgeBase - = new KnowledgeBase(kbName, KNOWLEDGE_SOURCE_REFERENCES).setModels(KNOWLEDGE_BASE_MODELS); + = new KnowledgeBase(kbName, KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); KnowledgeBase created = client.createKnowledgeBase(knowledgeBase); @@ -634,7 +619,7 @@ public void knowledgeBaseTypeNamesContainNoAgentReferences() { String kbName = randomKnowledgeBaseName(); KnowledgeBase knowledgeBase - = new KnowledgeBase(kbName, KNOWLEDGE_SOURCE_REFERENCES).setModels(KNOWLEDGE_BASE_MODELS); + = new KnowledgeBase(kbName, KNOWLEDGE_SOURCE_REFERENCE).setModels(KNOWLEDGE_BASE_MODEL); KnowledgeBase created = client.createKnowledgeBase(knowledgeBase); @@ -671,14 +656,13 @@ public void knowledgeBaseTypeNamesContainNoAgentReferences() { public void errorHandlingUsesKnowledgeBaseTerminology() { SearchIndexClient client = getSearchIndexClientBuilder(true).buildClient(); - HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { - client.getKnowledgeBase("nonexistent-kb-name"); - }); + HttpResponseException exception + = assertThrows(HttpResponseException.class, () -> client.getKnowledgeBase("nonexistent-kb-name")); assertEquals(404, exception.getResponse().getStatusCode(), "Status code should be 404 Not Found"); String errorMessage = exception.getMessage().toLowerCase(); - if (errorMessage != null && errorMessage.toLowerCase().contains("knowledge")) { + if (errorMessage.toLowerCase().contains("knowledge")) { assertFalse(errorMessage.toLowerCase().contains("agent"), "Error message should not contain 'agent' terminology"); } @@ -699,13 +683,12 @@ private static SearchIndexClient setupIndex() { .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) .buildClient(); - List semanticConfigurations - = Collections.singletonList(new SemanticConfiguration("semantic-config", - new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) - .setContentFields(new SemanticField("Description")) - .setKeywordsFields(new SemanticField("Category")))); + SemanticConfiguration semanticConfiguration = new SemanticConfiguration("semantic-config", + new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) + .setContentFields(new SemanticField("Description")) + .setKeywordsFields(new SemanticField("Category"))); SemanticSearch semanticSearch = new SemanticSearch().setDefaultConfigurationName("semantic-config") - .setConfigurations(semanticConfigurations); + .setConfigurations(semanticConfiguration); searchIndexClient.createOrUpdateIndex( TestHelpers.createTestIndex(HOTEL_INDEX_NAME, baseIndex).setSemanticSearch(semanticSearch)); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeSourceTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeSourceTests.java index f4d5acaf85e3..9dd8d9371dae 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeSourceTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/KnowledgeSourceTests.java @@ -16,21 +16,20 @@ import com.azure.search.documents.indexes.models.KnowledgeSource; import com.azure.search.documents.indexes.models.KnowledgeSourceIngestionPermissionOption; import com.azure.search.documents.indexes.models.KnowledgeSourceKind; -import com.azure.search.documents.indexes.models.KnowledgeSourceStatus; import com.azure.search.documents.indexes.models.KnowledgeSourceSynchronizationStatus; import com.azure.search.documents.indexes.models.RemoteSharePointKnowledgeSource; import com.azure.search.documents.indexes.models.RemoteSharePointKnowledgeSourceParameters; import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.indexes.models.SearchIndexFieldReference; import com.azure.search.documents.indexes.models.SearchIndexKnowledgeSource; import com.azure.search.documents.indexes.models.SearchIndexKnowledgeSourceParameters; -import com.azure.search.documents.indexes.models.SearchIndexFieldReference; 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.WebKnowledgeSource; import com.azure.search.documents.indexes.models.WebKnowledgeSourceParameters; - +import com.azure.search.documents.knowledgebases.models.KnowledgeSourceStatus; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -45,13 +44,9 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; -import java.time.Duration; import static com.azure.search.documents.TestHelpers.loadResource; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -146,8 +141,7 @@ public void createKnowledgeSourceRemoteSharePointSync() { assertEquals(knowledgeSource.getName(), created.getName()); - RemoteSharePointKnowledgeSource createdSource - = assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); + assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); } @Test @@ -160,8 +154,7 @@ public void createKnowledgeSourceRemoteSharePointAsync() { StepVerifier.create(searchIndexClient.createKnowledgeSource(knowledgeSource)).assertNext(created -> { assertEquals(knowledgeSource.getName(), created.getName()); - RemoteSharePointKnowledgeSource createdSource - = assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); + assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); }).verifyComplete(); } @@ -171,7 +164,7 @@ public void createKnowledgeSourceRemoteSharePointCustomParametersSync() { SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); RemoteSharePointKnowledgeSourceParameters params = new RemoteSharePointKnowledgeSourceParameters().setFilterExpression("FileExtension:\"docx\"") - .setResourceMetadata(Arrays.asList("Author", "CreatedDate")); + .setResourceMetadata("Author", "CreatedDate"); KnowledgeSource knowledgeSource = new RemoteSharePointKnowledgeSource(randomKnowledgeSourceName()).setRemoteSharePointParameters(params); @@ -179,8 +172,7 @@ public void createKnowledgeSourceRemoteSharePointCustomParametersSync() { assertEquals(knowledgeSource.getName(), created.getName()); - RemoteSharePointKnowledgeSource createdSource - = assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); + assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); } @Test @@ -189,15 +181,14 @@ public void createKnowledgeSourceRemoteSharePointCustomParametersAsync() { SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); RemoteSharePointKnowledgeSourceParameters params = new RemoteSharePointKnowledgeSourceParameters().setFilterExpression("FileExtension:\"docx\"") - .setResourceMetadata(Arrays.asList("Author", "CreatedDate")); + .setResourceMetadata("Author", "CreatedDate"); KnowledgeSource knowledgeSource = new RemoteSharePointKnowledgeSource(randomKnowledgeSourceName()).setRemoteSharePointParameters(params); StepVerifier.create(searchIndexClient.createKnowledgeSource(knowledgeSource)).assertNext(created -> { assertEquals(knowledgeSource.getName(), created.getName()); - RemoteSharePointKnowledgeSource createdSource - = assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); + assertInstanceOf(RemoteSharePointKnowledgeSource.class, created); }).verifyComplete(); } @@ -245,8 +236,7 @@ public void getKnowledgeSourceRemoteSharePointSync() { KnowledgeSource retrieved = searchIndexClient.getKnowledgeSource(knowledgeSource.getName()); assertEquals(knowledgeSource.getName(), retrieved.getName()); - RemoteSharePointKnowledgeSource retrievedSource - = assertInstanceOf(RemoteSharePointKnowledgeSource.class, retrieved); + assertInstanceOf(RemoteSharePointKnowledgeSource.class, retrieved); } @Test @@ -262,8 +252,7 @@ public void getKnowledgeSourceRemoteSharePointAsync() { StepVerifier.create(createAndGetMono).assertNext(retrieved -> { assertEquals(knowledgeSource.getName(), retrieved.getName()); - RemoteSharePointKnowledgeSource retrievedSource - = assertInstanceOf(RemoteSharePointKnowledgeSource.class, retrieved); + assertInstanceOf(RemoteSharePointKnowledgeSource.class, retrieved); }).verifyComplete(); } @@ -416,11 +405,10 @@ public void updateKnowledgeSourceRemoteSharePointAsync() { @Test public void statusPayloadMapsToModelsWithNullables() throws IOException { // Sample status payload with nullables for first sync - String statusJson = "{\n" + " \"synchronizationStatus\": \"creating\",\n" - + " \"synchronizationInterval\": \"PT24H\",\n" + " \"currentSynchronizationState\": null,\n" - + " \"lastSynchronizationState\": null,\n" + " \"statistics\": {\n" - + " \"totalSynchronization\": 0,\n" + " \"averageSynchronizationDuration\": \"00:00:00\",\n" - + " \"averageItemsProcessedPerSynchronization\": 0\n" + " }\n" + "}"; + String statusJson = "{\"synchronizationStatus\": \"creating\",\"synchronizationInterval\": \"PT24H\"," + + "\"currentSynchronizationState\": null,\"lastSynchronizationState\": null,\"statistics\": {" + + "\"totalSynchronization\": 0,\"averageSynchronizationDuration\": \"00:00:00\"," + + "\"averageItemsProcessedPerSynchronization\": 0}}"; try (JsonReader reader = JsonProviders.createReader(statusJson)) { KnowledgeSourceStatus status = KnowledgeSourceStatus.fromJson(reader); @@ -428,14 +416,8 @@ public void statusPayloadMapsToModelsWithNullables() throws IOException { assertNotNull(status); assertEquals(KnowledgeSourceSynchronizationStatus.CREATING, status.getSynchronizationStatus()); - Object syncInterval = status.getSynchronizationInterval(); - if (syncInterval instanceof String) { - assertEquals("PT24H", syncInterval); // ← Compare as String - } else if (syncInterval instanceof Duration) { - assertEquals(Duration.ofHours(24), syncInterval); // ← Compare as Duration - } else { - // Handle other types if needed - assertNotNull(syncInterval, "Synchronization interval should not be null"); + if (status.getSynchronizationInterval() != null) { + assertEquals("PT24H", status.getSynchronizationInterval()); } assertNull(status.getCurrentSynchronizationState()); @@ -460,10 +442,7 @@ public void putNewKnowledgeSourceReturns201() { assertNotNull(created); assertEquals(knowledgeSource.getName(), created.getName()); } finally { - try { - client.deleteKnowledgeSource(knowledgeSource.getName()); - } catch (Exception e) { - } + client.deleteKnowledgeSource(knowledgeSource.getName()); } } @@ -485,10 +464,7 @@ public void putExistingKnowledgeSourceReturns200() { KnowledgeSource retrieved = client.getKnowledgeSource(knowledgeSource.getName()); assertEquals(newDescription, retrieved.getDescription()); } finally { - try { - client.deleteKnowledgeSource(knowledgeSource.getName()); - } catch (Exception e) { - } + client.deleteKnowledgeSource(knowledgeSource.getName()); } } @@ -501,9 +477,8 @@ public void deleteKnowledgeSourceRemovesSource() { client.createKnowledgeSource(knowledgeSource); client.deleteKnowledgeSource(knowledgeSource.getName()); - HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { - client.getKnowledgeSource(knowledgeSource.getName()); - }); + HttpResponseException exception + = assertThrows(HttpResponseException.class, () -> client.getKnowledgeSource(knowledgeSource.getName())); assertEquals(404, exception.getResponse().getStatusCode()); } @@ -527,13 +502,9 @@ public void listKnowledgeSourcesReturnsAllResources() { assertEquals(initialCount + 2, knowledgeSourcesByName.size()); assertTrue(knowledgeSourcesByName.containsKey(ks1.getName())); assertTrue(knowledgeSourcesByName.containsKey(ks2.getName())); - } finally { - try { - client.deleteKnowledgeSource(ks1.getName()); - client.deleteKnowledgeSource(ks2.getName()); - } catch (Exception e) { - } + client.deleteKnowledgeSource(ks1.getName()); + client.deleteKnowledgeSource(ks2.getName()); } } @@ -546,15 +517,12 @@ public void knowledgeSourceParametersSetsFieldsCorrectly() { params.setSemanticConfigurationName("semantic-config"); assertEquals("semantic-config", params.getSemanticConfigurationName()); - List sourceFields - = Arrays.asList(new SearchIndexFieldReference("field1"), new SearchIndexFieldReference("field2")); - params.setSourceDataFields(sourceFields); + params.setSourceDataFields(new SearchIndexFieldReference("field1"), new SearchIndexFieldReference("field2")); assertEquals(2, params.getSourceDataFields().size()); assertEquals("field1", params.getSourceDataFields().get(0).getName()); assertEquals("field2", params.getSourceDataFields().get(1).getName()); - List searchFields = Arrays.asList(new SearchIndexFieldReference("searchField1")); - params.setSearchFields(searchFields); + params.setSearchFields(new SearchIndexFieldReference("searchField1")); assertEquals(1, params.getSearchFields().size()); assertEquals("searchField1", params.getSearchFields().get(0).getName()); @@ -683,9 +651,8 @@ public void deleteWebKnowledgeSourceRemovesResource() { searchIndexClient.deleteKnowledgeSource(created.getName()); - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> { - searchIndexClient.getKnowledgeSource(created.getName()); - }); + HttpResponseException ex + = assertThrows(HttpResponseException.class, () -> searchIndexClient.getKnowledgeSource(created.getName())); assertEquals(404, ex.getResponse().getStatusCode()); } @@ -709,9 +676,8 @@ public void createKnowledgeSourceWithInvalidName() { try { WebKnowledgeSource webKS = new WebKnowledgeSource(""); - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> { - searchIndexClient.createKnowledgeSource(webKS); - }); + HttpResponseException ex + = assertThrows(HttpResponseException.class, () -> searchIndexClient.createKnowledgeSource(webKS)); assertTrue(ex.getResponse().getStatusCode() >= 400 && ex.getResponse().getStatusCode() < 500); } catch (NullPointerException | IllegalArgumentException e) { @@ -721,9 +687,8 @@ public void createKnowledgeSourceWithInvalidName() { try { WebKnowledgeSource webKS = new WebKnowledgeSource(null); - HttpResponseException ex2 = assertThrows(HttpResponseException.class, () -> { - searchIndexClient.createKnowledgeSource(webKS); - }); + HttpResponseException ex2 + = assertThrows(HttpResponseException.class, () -> searchIndexClient.createKnowledgeSource(webKS)); assertTrue(ex2.getResponse().getStatusCode() >= 400 && ex2.getResponse().getStatusCode() < 500); } catch (NullPointerException | IllegalArgumentException e) { @@ -794,8 +759,7 @@ public void webKnowledgeSourceInheritsKnowledgeSourceBehavior() { assertNotNull(created.getName()); assertNotNull(created.getDescription()); - assertTrue(created instanceof KnowledgeSource); - assertTrue(created instanceof WebKnowledgeSource); + assertInstanceOf(WebKnowledgeSource.class, created); String newDescription = "Updated via base class"; created.setDescription(newDescription); @@ -818,13 +782,12 @@ private static SearchIndexClient setupIndex() { .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) .buildClient(); - List semanticConfigurations - = Collections.singletonList(new SemanticConfiguration("semantic-config", - new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) - .setContentFields(new SemanticField("Description")) - .setKeywordsFields(new SemanticField("Category")))); + SemanticConfiguration semanticConfiguration = new SemanticConfiguration("semantic-config", + new SemanticPrioritizedFields().setTitleField(new SemanticField("HotelName")) + .setContentFields(new SemanticField("Description")) + .setKeywordsFields(new SemanticField("Category"))); SemanticSearch semanticSearch = new SemanticSearch().setDefaultConfigurationName("semantic-config") - .setConfigurations(semanticConfigurations); + .setConfigurations(semanticConfiguration); searchIndexClient.createOrUpdateIndex( TestHelpers.createTestIndex(HOTEL_INDEX_NAME, baseIndex).setSemanticSearch(semanticSearch)); 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 index d6261c3a1317..6fa5d3f63525 100644 --- 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 @@ -2,20 +2,23 @@ // Licensed under the MIT License. package com.azure.search.documents; -import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RequestOptions; 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.core.test.TestProxyTestBase; +import com.azure.json.JsonReader; +import com.azure.json.ReadValueCallback; 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 com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; +import com.azure.search.documents.models.LookupDocument; +import com.azure.search.documents.testingmodels.Hotel; +import com.azure.search.documents.testingmodels.HotelAddress; +import com.azure.search.documents.testingmodels.HotelRoom; +import com.azure.search.documents.testingmodels.ModelWithPrimitiveCollections; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -31,20 +34,24 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; +import java.util.Collection; import java.util.Collections; -import java.util.Date; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; 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.convertFromMapStringObject; +import static com.azure.search.documents.TestHelpers.createIndexAction; 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 com.azure.search.documents.TestHelpers.uploadDocumentRaw; 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 { @@ -92,8 +99,8 @@ public void canGetStaticallyTypedDocumentSync() { Hotel expected = prepareExpectedHotel(getRandomDocumentKey()); uploadDocument(client, expected); - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - assertObjectEquals(expected, actual, true, "boundingBox"); + getAndValidateDocument(client, expected.hotelId(), Hotel::fromJson, expected, + (ignored, actual) -> assertObjectEquals(expected, actual, true, "boundingBox")); } @Test @@ -103,7 +110,7 @@ public void canGetStaticallyTypedDocumentAsync() { Hotel expected = prepareExpectedHotel(getRandomDocumentKey()); uploadDocument(asyncClient, expected); - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, + getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel::fromJson, expected, (ignored, actual) -> assertObjectEquals(expected, actual, true, "boundingBox")); } @@ -114,8 +121,8 @@ public void canGetStaticallyTypedDocumentWithNullOrEmptyValuesSync() { Hotel expected = prepareEmptyHotel(getRandomDocumentKey()); uploadDocument(client, expected); - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - assertObjectEquals(expected, actual, true); + getAndValidateDocument(client, expected.hotelId(), Hotel::fromJson, expected, + (ignored, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -125,7 +132,7 @@ public void canGetStaticallyTypedDocumentWithNullOrEmptyValuesAsync() { Hotel expected = prepareEmptyHotel(getRandomDocumentKey()); uploadDocument(asyncClient, expected); - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, + getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel::fromJson, expected, (ignored, actual) -> assertObjectEquals(expected, actual, true)); } @@ -136,8 +143,8 @@ public void canGetStaticallyTypedDocumentWithPascalCaseFieldsSync() { Hotel expected = preparePascalCaseFieldsHotel(getRandomDocumentKey()); uploadDocument(client, expected); - Hotel actual = client.getDocument(expected.hotelId(), Hotel.class); - assertObjectEquals(expected, actual, true); + getAndValidateDocument(client, expected.hotelId(), Hotel::fromJson, expected, + (ignored, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -147,7 +154,7 @@ public void canGetStaticallyTypedDocumentWithPascalCaseFieldsAsync() { Hotel expected = preparePascalCaseFieldsHotel(getRandomDocumentKey()); uploadDocument(asyncClient, expected); - getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel.class, expected, + getAndValidateDocumentAsync(asyncClient, expected.hotelId(), Hotel::fromJson, expected, (ignored, actual) -> assertObjectEquals(expected, actual, true)); } @@ -158,8 +165,8 @@ public void canRoundTripStaticallyTypedPrimitiveCollectionsSync() { ModelWithPrimitiveCollections expected = preparePrimitivesModel(getRandomDocumentKey()); uploadDocument(client, expected); - ModelWithPrimitiveCollections actual = client.getDocument(expected.key(), ModelWithPrimitiveCollections.class); - assertObjectEquals(expected, actual, true, "boundingBox"); + getAndValidateDocument(client, expected.key(), ModelWithPrimitiveCollections::fromJson, expected, + (ignored, actual) -> assertObjectEquals(expected, actual, true, "boundingBox")); } @Test @@ -169,7 +176,7 @@ public void canRoundTripStaticallyTypedPrimitiveCollectionsAsync() { ModelWithPrimitiveCollections expected = preparePrimitivesModel(getRandomDocumentKey()); uploadDocument(asyncClient, expected); - getAndValidateDocumentAsync(asyncClient, expected.key(), ModelWithPrimitiveCollections.class, expected, + getAndValidateDocumentAsync(asyncClient, expected.key(), ModelWithPrimitiveCollections::fromJson, expected, (ignored, actual) -> assertObjectEquals(expected, actual, true, "boundingBox")); } @@ -187,9 +194,8 @@ public void getStaticallyTypedDocumentSetsUnselectedFieldsToNullSync() { 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); + getAndValidateDocument(client, indexedDoc.hotelId(), Hotel::fromJson, selectedFields, expected, + (ignored, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -206,7 +212,7 @@ public void getStaticallyTypedDocumentSetsUnselectedFieldsToNullAsync() { uploadDocument(asyncClient, indexedDoc); List selectedFields = Arrays.asList("Description", "HotelName", "Address/City", "Rooms/BaseRate"); - getAndValidateDocumentAsync(asyncClient, indexedDoc.hotelId(), Hotel.class, selectedFields, expected, + getAndValidateDocumentAsync(asyncClient, indexedDoc.hotelId(), Hotel::fromJson, selectedFields, expected, (ignored, actual) -> assertObjectEquals(expected, actual, true)); } @@ -215,7 +221,7 @@ public void canGetDynamicDocumentWithNullOrEmptyValuesSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); expectedDoc.put("HotelName", null); expectedDoc.put("Tags", Collections.emptyList()); @@ -225,7 +231,7 @@ public void canGetDynamicDocumentWithNullOrEmptyValuesSync() { expectedDoc.put("Location", null); expectedDoc.put("Address", null); - SearchDocument room = new SearchDocument(); + Map room = new LinkedHashMap<>(); room.put("BaseRate", null); room.put("BedOptions", null); room.put("SleepsCount", null); @@ -234,15 +240,14 @@ public void canGetDynamicDocumentWithNullOrEmptyValuesSync() { expectedDoc.put("Rooms", Collections.singletonList(room)); - uploadDocument(client, expectedDoc); + uploadDocumentRaw(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); + getAndValidateDocument(client, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -250,7 +255,7 @@ public void canGetDynamicDocumentWithNullOrEmptyValuesAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); expectedDoc.put("HotelName", null); expectedDoc.put("Tags", Collections.emptyList()); @@ -260,7 +265,7 @@ public void canGetDynamicDocumentWithNullOrEmptyValuesAsync() { expectedDoc.put("Location", null); expectedDoc.put("Address", null); - SearchDocument room = new SearchDocument(); + Map room = new LinkedHashMap<>(); room.put("BaseRate", null); room.put("BedOptions", null); room.put("SleepsCount", null); @@ -269,14 +274,14 @@ public void canGetDynamicDocumentWithNullOrEmptyValuesAsync() { expectedDoc.put("Rooms", Collections.singletonList(room)); - uploadDocument(asyncClient, expectedDoc); + uploadDocumentRaw(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)); + getAndValidateDocumentAsync(asyncClient, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -284,14 +289,14 @@ public void getDynamicDocumentWithEmptyObjectsReturnsObjectsFullOfNullsSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); originalDoc.put("HotelId", hotelId); - originalDoc.put("Address", new SearchDocument()); + originalDoc.put("Address", new LinkedHashMap()); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); - SearchDocument address = new SearchDocument(); + Map address = new LinkedHashMap<>(); address.put("StreetAddress", null); address.put("City", null); address.put("StateProvince", null); @@ -299,13 +304,12 @@ public void getDynamicDocumentWithEmptyObjectsReturnsObjectsFullOfNullsSync() { address.put("PostalCode", null); expectedDoc.put("Address", address); - uploadDocument(client, originalDoc); + uploadDocumentRaw(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); + getAndValidateDocument(client, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -313,14 +317,14 @@ public void getDynamicDocumentWithEmptyObjectsReturnsObjectsFullOfNullsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); originalDoc.put("HotelId", hotelId); - originalDoc.put("Address", new SearchDocument()); + originalDoc.put("Address", new LinkedHashMap()); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); - SearchDocument address = new SearchDocument(); + Map address = new LinkedHashMap<>(); address.put("StreetAddress", null); address.put("City", null); address.put("StateProvince", null); @@ -328,12 +332,12 @@ public void getDynamicDocumentWithEmptyObjectsReturnsObjectsFullOfNullsAsync() { address.put("PostalCode", null); expectedDoc.put("Address", address); - uploadDocument(asyncClient, originalDoc); + uploadDocumentRaw(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)); + getAndValidateDocumentAsync(asyncClient, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -342,17 +346,17 @@ public void emptyDynamicallyTypedPrimitiveCollectionsRoundTripAsObjectArraysSync String docKey = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); 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(); + originalDoc.put("Dates", new Object[0]); + originalDoc.put("Doubles", new Double[0]); + originalDoc.put("Bools", new Boolean[0]); + originalDoc.put("Longs", new Long[0]); + originalDoc.put("Strings", new String[0]); + originalDoc.put("Ints", new Integer[0]); + originalDoc.put("Points", new Object[0]); + + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("Key", docKey); expectedDoc.put("Doubles", Collections.emptyList()); expectedDoc.put("Bools", Collections.emptyList()); @@ -362,10 +366,9 @@ public void emptyDynamicallyTypedPrimitiveCollectionsRoundTripAsObjectArraysSync expectedDoc.put("Points", Collections.emptyList()); expectedDoc.put("Dates", Collections.emptyList()); - uploadDocument(client, originalDoc); + uploadDocumentRaw(client, originalDoc); - SearchDocument actualDoc = client.getDocument(docKey, SearchDocument.class); - assertEquals(expectedDoc, actualDoc); + getAndValidateDocument(client, docKey, expectedDoc, Assertions::assertEquals); } @Test @@ -374,17 +377,17 @@ public void emptyDynamicallyTypedPrimitiveCollectionsRoundTripAsObjectArraysAsyn String docKey = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); 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(); + originalDoc.put("Dates", new Object[0]); + originalDoc.put("Doubles", new Double[0]); + originalDoc.put("Bools", new Boolean[0]); + originalDoc.put("Longs", new Long[0]); + originalDoc.put("Strings", new String[0]); + originalDoc.put("Ints", new Integer[0]); + originalDoc.put("Points", new Object[0]); + + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("Key", docKey); expectedDoc.put("Doubles", Collections.emptyList()); expectedDoc.put("Bools", Collections.emptyList()); @@ -394,9 +397,9 @@ public void emptyDynamicallyTypedPrimitiveCollectionsRoundTripAsObjectArraysAsyn expectedDoc.put("Points", Collections.emptyList()); expectedDoc.put("Dates", Collections.emptyList()); - uploadDocument(asyncClient, originalDoc); + uploadDocumentRaw(asyncClient, originalDoc); - getAndValidateDocumentAsync(asyncClient, docKey, SearchDocument.class, expectedDoc, Assertions::assertEquals); + getAndValidateDocumentAsync(asyncClient, docKey, expectedDoc, Assertions::assertEquals); } @Test @@ -404,21 +407,21 @@ public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelec SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); originalDoc.put("HotelId", hotelId); - SearchDocument originalRoom = new SearchDocument(); + Map originalRoom = new LinkedHashMap<>(); 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)); + originalDoc.put("Rooms", Arrays.asList(new LinkedHashMap(), originalRoom)); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); - SearchDocument expectedRoom1 = new SearchDocument(); + Map expectedRoom1 = new LinkedHashMap<>(); expectedRoom1.put("Description", null); expectedRoom1.put("Description_fr", null); expectedRoom1.put("Type", null); @@ -428,7 +431,7 @@ public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelec expectedRoom1.put("SmokingAllowed", null); expectedRoom1.put("Tags", Collections.emptyList()); - SearchDocument expectedRoom2 = new SearchDocument(); + Map expectedRoom2 = new LinkedHashMap<>(); expectedRoom2.put("Description", null); expectedRoom2.put("Description_fr", null); expectedRoom2.put("Type", null); @@ -440,12 +443,11 @@ public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelec expectedDoc.put("Rooms", Arrays.asList(expectedRoom1, expectedRoom2)); - uploadDocument(client, originalDoc); + uploadDocumentRaw(client, originalDoc); List selectedFields = Arrays.asList("HotelId", "Rooms"); - Response response - = client.getDocumentWithResponse(hotelId, SearchDocument.class, selectedFields, Context.NONE); - assertObjectEquals(expectedDoc, response.getValue(), true); + getAndValidateDocument(client, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -453,21 +455,21 @@ public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelec SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); originalDoc.put("HotelId", hotelId); - SearchDocument originalRoom = new SearchDocument(); + Map originalRoom = new LinkedHashMap<>(); 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)); + originalDoc.put("Rooms", Arrays.asList(new LinkedHashMap(), originalRoom)); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); - SearchDocument expectedRoom1 = new SearchDocument(); + Map expectedRoom1 = new LinkedHashMap<>(); expectedRoom1.put("Description", null); expectedRoom1.put("Description_fr", null); expectedRoom1.put("Type", null); @@ -477,7 +479,7 @@ public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelec expectedRoom1.put("SmokingAllowed", null); expectedRoom1.put("Tags", Collections.emptyList()); - SearchDocument expectedRoom2 = new SearchDocument(); + Map expectedRoom2 = new LinkedHashMap<>(); expectedRoom2.put("Description", null); expectedRoom2.put("Description_fr", null); expectedRoom2.put("Type", null); @@ -489,10 +491,10 @@ public void emptyDynamicObjectsInCollectionExpandedOnGetWhenCollectionFieldSelec expectedDoc.put("Rooms", Arrays.asList(expectedRoom1, expectedRoom2)); - uploadDocument(asyncClient, originalDoc); + uploadDocumentRaw(asyncClient, originalDoc); List selectedFields = Arrays.asList("HotelId", "Rooms"); - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, selectedFields, expectedDoc, (expected, actual) -> assertObjectEquals(expected, actual, true)); } @@ -501,28 +503,25 @@ public void getDynamicDocumentCannotAlwaysDetermineCorrectTypeSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); + Map indexedDoc = new LinkedHashMap<>(); 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)))); + indexedDoc.put("Rooms", Collections.singletonList(Collections.singletonMap("BaseRate", NaN))); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); 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")))); + expectedDoc.put("Rooms", Collections.singletonList(Collections.singletonMap("BaseRate", "NaN"))); - client.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, 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"); + getAndValidateDocument(client, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertMapEquals(expected, actual, true, "boundingBox", "properties")); } @Test @@ -530,27 +529,25 @@ public void getDynamicDocumentCannotAlwaysDetermineCorrectTypeAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); + Map indexedDoc = new LinkedHashMap<>(); 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)))); + indexedDoc.put("Rooms", Collections.singletonList(Collections.singletonMap("BaseRate", NaN))); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); 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")))); + expectedDoc.put("Rooms", Collections.singletonList(Collections.singletonMap("BaseRate", "NaN"))); - asyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))) + asyncClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, 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, + getAndValidateDocumentAsync(asyncClient, hotelId, selectedFields, expectedDoc, (expected, actual) -> assertMapEquals(expected, actual, true, "boundingBox", "properties")); } @@ -560,16 +557,11 @@ public void canGetDocumentWithBase64EncodedKeySync() { String complexKey = Base64.getEncoder().encodeToString(new byte[] { 1, 2, 3, 4, 5 }); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); 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); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, expectedDoc))); + getAndValidateDocument(client, complexKey, expectedDoc.keySet(), expectedDoc, Assertions::assertEquals); } @Test @@ -578,14 +570,14 @@ public void canGetDocumentWithBase64EncodedKeyAsync() { String complexKey = Base64.getEncoder().encodeToString(new byte[] { 1, 2, 3, 4, 5 }); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", complexKey); - asyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(expectedDoc))) + asyncClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, expectedDoc))) .block(); - getAndValidateDocumentAsync(asyncClient, complexKey, SearchDocument.class, - new ArrayList<>(expectedDoc.keySet()), expectedDoc, Assertions::assertEquals); + getAndValidateDocumentAsync(asyncClient, complexKey, expectedDoc.keySet(), expectedDoc, + Assertions::assertEquals); } @Test @@ -593,20 +585,18 @@ public void roundTrippingDateTimeOffsetNormalizesToUtcSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); + Map indexedDoc = new LinkedHashMap<>(); indexedDoc.put("HotelId", hotelId); indexedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T00:00:00-08:00")); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); 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); + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, indexedDoc))); + getAndValidateDocument(client, hotelId, expectedDoc.keySet(), expectedDoc, + (expected, actual) -> assertMapEquals(expected, actual, false)); } @Test @@ -614,20 +604,20 @@ public void roundTrippingDateTimeOffsetNormalizesToUtcAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument indexedDoc = new SearchDocument(); + Map indexedDoc = new LinkedHashMap<>(); indexedDoc.put("HotelId", hotelId); indexedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T00:00:00-08:00")); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); expectedDoc.put("LastRenovationDate", OffsetDateTime.parse("2010-06-27T08:00Z")); - asyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions(Collections.singletonList(indexedDoc))) + asyncClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, indexedDoc))) .block(); - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, new ArrayList<>(expectedDoc.keySet()), - expectedDoc, (expected, actual) -> assertMapEquals(expected, actual, false)); + getAndValidateDocumentAsync(asyncClient, hotelId, expectedDoc.keySet(), expectedDoc, + (expected, actual) -> assertMapEquals(expected, actual, false)); } @Test @@ -635,21 +625,21 @@ public void emptyDynamicObjectsOmittedFromCollectionOnGetWhenSubFieldsSelectedSy SearchClient client = getClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); originalDoc.put("HotelId", hotelId); - SearchDocument originalRoom = new SearchDocument(); + Map originalRoom = new LinkedHashMap<>(); 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)); + originalDoc.put("Rooms", Arrays.asList(new LinkedHashMap(), originalRoom)); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); - SearchDocument expectedRoom = new SearchDocument(); + Map expectedRoom = new LinkedHashMap<>(); expectedRoom.put("BaseRate", null); expectedRoom.put("BedOptions", null); expectedRoom.put("SleepsCount", null); @@ -657,13 +647,12 @@ public void emptyDynamicObjectsOmittedFromCollectionOnGetWhenSubFieldsSelectedSy expectedRoom.put("Tags", Collections.emptyList()); expectedDoc.put("Rooms", Collections.singletonList(expectedRoom)); - uploadDocument(client, originalDoc); + uploadDocumentRaw(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); + getAndValidateDocument(client, hotelId, selectedFields, expectedDoc, + (expected, actual) -> assertObjectEquals(expected, actual, true)); } @Test @@ -671,21 +660,21 @@ public void emptyDynamicObjectsOmittedFromCollectionOnGetWhenSubFieldsSelectedAs SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); String hotelId = getRandomDocumentKey(); - SearchDocument originalDoc = new SearchDocument(); + Map originalDoc = new LinkedHashMap<>(); originalDoc.put("HotelId", hotelId); - SearchDocument originalRoom = new SearchDocument(); + Map originalRoom = new LinkedHashMap<>(); 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)); + originalDoc.put("Rooms", Arrays.asList(new LinkedHashMap(), originalRoom)); - SearchDocument expectedDoc = new SearchDocument(); + Map expectedDoc = new LinkedHashMap<>(); expectedDoc.put("HotelId", hotelId); - SearchDocument expectedRoom = new SearchDocument(); + Map expectedRoom = new LinkedHashMap<>(); expectedRoom.put("BaseRate", null); expectedRoom.put("BedOptions", null); expectedRoom.put("SleepsCount", null); @@ -693,11 +682,11 @@ public void emptyDynamicObjectsOmittedFromCollectionOnGetWhenSubFieldsSelectedAs expectedRoom.put("Tags", Collections.emptyList()); expectedDoc.put("Rooms", Collections.singletonList(expectedRoom)); - uploadDocument(asyncClient, originalDoc); + uploadDocumentRaw(asyncClient, originalDoc); List selectedFields = Arrays.asList("HotelId", "Rooms/BaseRate", "Rooms/BedOptions", "Rooms/SleepsCount", "Rooms/SmokingAllowed", "Rooms/Tags"); - getAndValidateDocumentAsync(asyncClient, hotelId, SearchDocument.class, selectedFields, expectedDoc, + getAndValidateDocumentAsync(asyncClient, hotelId, selectedFields, expectedDoc, (expected, actual) -> assertObjectEquals(expected, actual, true)); } @@ -709,32 +698,31 @@ public void dynamicallyTypedPrimitiveCollectionsDoNotAllRoundTripCorrectlySync() OffsetDateTime dateTime = OffsetDateTime.parse("2019-08-13T14:30:00Z"); GeoPoint geoPoint = new GeoPoint(100.0, 1.0); - SearchDocument indexedDoc = new SearchDocument(); + Map indexedDoc = new LinkedHashMap<>(); 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("Ints", new Integer[] { 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(); + Map expectedDoc = new LinkedHashMap<>(); 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("Points", Collections.singletonList(geoPoint)); expectedDoc.put("Dates", Collections.singletonList(dateTime)); - uploadDocument(client, indexedDoc); - - SearchDocument actualDoc = client.getDocument(docKey, SearchDocument.class); + uploadDocumentRaw(client, indexedDoc); - assertMapEquals(expectedDoc, actualDoc, true, "properties"); + getAndValidateDocument(client, docKey, expectedDoc, + (expected, actual) -> assertMapEquals(expected, actual, true, "properties")); } @Test @@ -745,67 +733,127 @@ public void dynamicallyTypedPrimitiveCollectionsDoNotAllRoundTripCorrectlyAsync( OffsetDateTime dateTime = OffsetDateTime.parse("2019-08-13T14:30:00Z"); GeoPoint geoPoint = new GeoPoint(100.0, 1.0); - SearchDocument indexedDoc = new SearchDocument(); + Map indexedDoc = new LinkedHashMap<>(); 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("Ints", new Integer[] { 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(); + Map expectedDoc = new LinkedHashMap<>(); 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("Points", Collections.singletonList(geoPoint)); expectedDoc.put("Dates", Collections.singletonList(dateTime)); - uploadDocument(asyncClient, indexedDoc); + uploadDocumentRaw(asyncClient, indexedDoc); - getAndValidateDocumentAsync(asyncClient, docKey, SearchDocument.class, expectedDoc, + getAndValidateDocumentAsync(asyncClient, docKey, 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.") + .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())) + .lastRenovationDate(OffsetDateTime.ofInstant(Instant.ofEpochMilli(1277582400000L), ZoneOffset.UTC)) .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)) + private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, + Map expected, BiConsumer, Map> comparator) { + StepVerifier.create(asyncClient.getDocument(key)) + .assertNext(actual -> comparator.accept(expected, actual.getAdditionalProperties())) + .verifyComplete(); + } + + private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, + ReadValueCallback converter, T expected, BiConsumer comparator) { + StepVerifier + .create(asyncClient.getDocument(key) + .map(doc -> convertFromMapStringObject(doc.getAdditionalProperties(), converter))) .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())) + private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, + Collection selectedFields, Map expected, + BiConsumer, Map> comparator) { + StepVerifier + .create(asyncClient + .getDocumentWithResponse(key, + new RequestOptions().addQueryParam("$select", String.join(",", selectedFields))) + .map(response -> response.getValue().toObject(LookupDocument.class).getAdditionalProperties())) + .assertNext(actual -> comparator.accept(expected, actual)) + .verifyComplete(); + } + + private static void getAndValidateDocumentAsync(SearchAsyncClient asyncClient, String key, + ReadValueCallback converter, Collection selectedFields, T expected, + BiConsumer comparator) { + StepVerifier + .create(asyncClient + .getDocumentWithResponse(key, + new RequestOptions().addQueryParam("$select", String.join(",", selectedFields))) + .map(response -> convertFromMapStringObject( + response.getValue().toObject(LookupDocument.class).getAdditionalProperties(), converter))) + .assertNext(actual -> comparator.accept(expected, actual)) .verifyComplete(); } + private static void getAndValidateDocument(SearchClient client, String key, Map expected, + BiConsumer, Map> comparator) { + comparator.accept(expected, client.getDocument(key).getAdditionalProperties()); + } + + private static void getAndValidateDocument(SearchClient client, String key, + ReadValueCallback converter, T expected, BiConsumer comparator) { + comparator.accept(expected, + convertFromMapStringObject(client.getDocument(key).getAdditionalProperties(), converter)); + } + + private static void getAndValidateDocument(SearchClient client, String key, Collection selectedFields, + Map expected, BiConsumer, Map> comparator) { + Map actual = client + .getDocumentWithResponse(key, + new RequestOptions().addQueryParam("$select", String.join(",", selectedFields))) + .getValue() + .toObject(LookupDocument.class) + .getAdditionalProperties(); + comparator.accept(expected, actual); + } + + private static void getAndValidateDocument(SearchClient client, String key, + ReadValueCallback converter, Collection selectedFields, T expected, + BiConsumer comparator) { + Map actual = client + .getDocumentWithResponse(key, + new RequestOptions().addQueryParam("$select", String.join(",", selectedFields))) + .getValue() + .toObject(LookupDocument.class) + .getAdditionalProperties(); + comparator.accept(expected, convertFromMapStringObject(actual, converter)); + } + static Hotel prepareEmptyHotel(String key) { return new Hotel().hotelId(key) .tags(new ArrayList<>()) @@ -816,7 +864,6 @@ 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. @@ -826,16 +873,16 @@ static Hotel prepareSelectedFieldsHotel(String key) { 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.") + .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())) + .lastRenovationDate(dateTime) .rating(3) .location(new GeoPoint(-78.940483, 35.904160)) .address(new HotelAddress().streetAddress("6910 Fayetteville Rd") @@ -876,17 +923,18 @@ static ModelWithPrimitiveCollections preparePrimitivesModel(String key) { } 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), + SearchIndex index = new SearchIndex(TYPE_INDEX_NAME, + new SearchField("Key", SearchFieldDataType.STRING).setKey(true).setRetrievable(true), + new SearchField("Bools", SearchFieldDataType.collection(SearchFieldDataType.BOOLEAN)).setRetrievable(true), new SearchField("Dates", SearchFieldDataType.collection(SearchFieldDataType.DATE_TIME_OFFSET)) - .setHidden(false), - new SearchField("Doubles", SearchFieldDataType.collection(SearchFieldDataType.DOUBLE)).setHidden(false), + .setRetrievable(true), + new SearchField("Doubles", SearchFieldDataType.collection(SearchFieldDataType.DOUBLE)).setRetrievable(true), 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))); + .setRetrievable(true), + new SearchField("Ints", SearchFieldDataType.collection(SearchFieldDataType.INT32)).setRetrievable(true), + new SearchField("Longs", SearchFieldDataType.collection(SearchFieldDataType.INT64)).setRetrievable(true), + new SearchField("Strings", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + .setRetrievable(true)); createSharedSearchIndexClient().createOrUpdateIndex(index); } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAliasTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAliasTests.java index e54759d8f849..509b9b0039b8 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAliasTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAliasTests.java @@ -14,8 +14,6 @@ import reactor.test.StepVerifier; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -42,7 +40,7 @@ public class SearchAliasTests extends SearchTestBase { public static void beforeAll() { // When running against the live service ensure all aliases are deleted before running these tests. if (TEST_MODE == TestMode.PLAYBACK) { - return; // Running in PLAYBACK, no need to clean-up. + return; // Running in PLAYBACK, no need to clean up. } searchIndexClient = setupSharedIndex(HOTEL_INDEX_NAME1, HOTELS_TESTS_INDEX_DATA_JSON, null); @@ -70,7 +68,7 @@ protected void afterTest() { // When running against the live service ensure all aliases are deleted before running these tests. if (TEST_MODE == TestMode.PLAYBACK) { - return; // Running in PLAYBACK, no need to clean-up. + return; // Running in PLAYBACK, no need to clean up. } SearchIndexClient cleanupClient = new SearchIndexClientBuilder().endpoint(SEARCH_ENDPOINT) @@ -91,8 +89,7 @@ protected void afterTest() { @Test public void canCreateAndGetAliasSync() { - SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); SearchAlias searchAlias = indexClient.createAlias(expectedAlias); aliasesToDelete.add(searchAlias.getName()); @@ -107,8 +104,7 @@ public void canCreateAndGetAliasSync() { @Test public void canCreateAliasAsync() { - SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); StepVerifier.create(indexAsyncClient.createAlias(expectedAlias)).assertNext(searchAlias -> { aliasesToDelete.add(searchAlias.getName()); @@ -124,50 +120,44 @@ public void canCreateAliasAsync() { @Test public void cannotCreateAliasOnNonExistentIndexSync() { - assertThrows(HttpResponseException.class, () -> indexClient - .createAlias(new SearchAlias("my-alias", Collections.singletonList("index-that-does-not-exist")))); + assertThrows(HttpResponseException.class, + () -> indexClient.createAlias(new SearchAlias("my-alias", "index-that-does-not-exist"))); } @Test public void cannotCreateAliasOnNonExistentIndexAsync() { - StepVerifier - .create(indexAsyncClient - .createAlias(new SearchAlias("my-alias", Collections.singletonList("index-that-does-not-exist")))) + StepVerifier.create(indexAsyncClient.createAlias(new SearchAlias("my-alias", "index-that-does-not-exist"))) .verifyError(HttpResponseException.class); } @Test public void cannotCreateAliasWithInvalidNameSync() { - assertThrows(HttpResponseException.class, () -> indexClient - .createAlias(new SearchAlias("--invalid--alias-name", Collections.singletonList(HOTEL_INDEX_NAME1)))); + assertThrows(HttpResponseException.class, + () -> indexClient.createAlias(new SearchAlias("--invalid--alias-name", HOTEL_INDEX_NAME1))); } @Test public void cannotCreateAliasWithInvalidNameAsync() { - StepVerifier - .create(indexAsyncClient - .createAlias(new SearchAlias("--invalid--alias-name", Collections.singletonList(HOTEL_INDEX_NAME1)))) + StepVerifier.create(indexAsyncClient.createAlias(new SearchAlias("--invalid--alias-name", HOTEL_INDEX_NAME1))) .verifyError(HttpResponseException.class); } @Test public void cannotCreateMultipleAliasesWithTheSameNameSync() { - SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); SearchAlias searchAlias = indexClient.createAlias(expectedAlias); aliasesToDelete.add(searchAlias.getName()); assertEquals(expectedAlias.getName(), searchAlias.getName()); assertEquals(expectedAlias.getIndexes(), searchAlias.getIndexes()); - assertThrows(HttpResponseException.class, () -> indexClient - .createAlias(new SearchAlias(expectedAlias.getName(), Collections.singletonList(HOTEL_INDEX_NAME1)))); + assertThrows(HttpResponseException.class, + () -> indexClient.createAlias(new SearchAlias(expectedAlias.getName(), HOTEL_INDEX_NAME1))); } @Test public void cannotCreateMultipleAliasesWithTheSameNameAsync() { - SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias expectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); StepVerifier.create(indexAsyncClient.createAlias(expectedAlias)).assertNext(searchAlias -> { aliasesToDelete.add(searchAlias.getName()); @@ -175,38 +165,35 @@ public void cannotCreateMultipleAliasesWithTheSameNameAsync() { assertEquals(expectedAlias.getIndexes(), searchAlias.getIndexes()); }).verifyComplete(); - StepVerifier - .create(indexAsyncClient - .createAlias(new SearchAlias(expectedAlias.getName(), Collections.singletonList(HOTEL_INDEX_NAME1)))) + StepVerifier.create(indexAsyncClient.createAlias(new SearchAlias(expectedAlias.getName(), HOTEL_INDEX_NAME1))) .verifyError(HttpResponseException.class); } @Test public void cannotCreateAliasWithMultipleIndexesSync() { - assertThrows(HttpResponseException.class, () -> indexClient - .createAlias(new SearchAlias("my-alias", Arrays.asList(HOTEL_INDEX_NAME1, HOTEL_INDEX_NAME2)))); + assertThrows(HttpResponseException.class, + () -> indexClient.createAlias(new SearchAlias("my-alias", HOTEL_INDEX_NAME1, HOTEL_INDEX_NAME2))); } @Test public void cannotCreateAliasWithMultipleIndexesAsync() { StepVerifier - .create(indexAsyncClient - .createAlias(new SearchAlias("my-alias", Arrays.asList(HOTEL_INDEX_NAME1, HOTEL_INDEX_NAME2)))) + .create(indexAsyncClient.createAlias(new SearchAlias("my-alias", HOTEL_INDEX_NAME1, HOTEL_INDEX_NAME2))) .verifyError(HttpResponseException.class); } @Test public void canCreateMultipleAliasesReferencingTheSameIndexSync() { - SearchAlias firstExpectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias firstExpectedAlias + = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); SearchAlias searchAlias = indexClient.createAlias(firstExpectedAlias); aliasesToDelete.add(searchAlias.getName()); assertEquals(firstExpectedAlias.getName(), searchAlias.getName()); assertEquals(firstExpectedAlias.getIndexes(), searchAlias.getIndexes()); - SearchAlias secondExpectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias secondExpectedAlias + = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); searchAlias = indexClient.createAlias(secondExpectedAlias); aliasesToDelete.add(searchAlias.getName()); @@ -216,8 +203,8 @@ public void canCreateMultipleAliasesReferencingTheSameIndexSync() { @Test public void canCreateMultipleAliasesReferencingTheSameIndexAsync() { - SearchAlias firstExpectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias firstExpectedAlias + = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); StepVerifier.create(indexAsyncClient.createAlias(firstExpectedAlias)).assertNext(searchAlias -> { aliasesToDelete.add(searchAlias.getName()); @@ -225,8 +212,8 @@ public void canCreateMultipleAliasesReferencingTheSameIndexAsync() { assertEquals(firstExpectedAlias.getIndexes(), searchAlias.getIndexes()); }).verifyComplete(); - SearchAlias secondExpectedAlias = new SearchAlias(testResourceNamer.randomName("my-alias", 32), - Collections.singletonList(HOTEL_INDEX_NAME1)); + SearchAlias secondExpectedAlias + = new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1); StepVerifier.create(indexAsyncClient.createAlias(secondExpectedAlias)).assertNext(searchAlias -> { aliasesToDelete.add(searchAlias.getName()); @@ -238,10 +225,10 @@ public void canCreateMultipleAliasesReferencingTheSameIndexAsync() { @Test public void canUpdateAliasAfterCreationSync() { String aliasName = testResourceNamer.randomName("my-alias", 32); - indexClient.createAlias(new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME1))); + indexClient.createAlias(new SearchAlias(aliasName, HOTEL_INDEX_NAME1)); aliasesToDelete.add(aliasName); - SearchAlias expectedUpdatedAlias = new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME2)); + SearchAlias expectedUpdatedAlias = new SearchAlias(aliasName, HOTEL_INDEX_NAME2); SearchAlias updatedAlias = indexClient.createOrUpdateAlias(expectedUpdatedAlias); assertEquals(expectedUpdatedAlias.getName(), updatedAlias.getName()); @@ -251,10 +238,10 @@ public void canUpdateAliasAfterCreationSync() { @Test public void canUpdateAliasAfterCreationAsync() { String aliasName = testResourceNamer.randomName("my-alias", 32); - indexAsyncClient.createAlias(new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME1))).block(); + indexAsyncClient.createAlias(new SearchAlias(aliasName, HOTEL_INDEX_NAME1)).block(); aliasesToDelete.add(aliasName); - SearchAlias expectedUpdatedAlias = new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME2)); + SearchAlias expectedUpdatedAlias = new SearchAlias(aliasName, HOTEL_INDEX_NAME2); StepVerifier.create(indexAsyncClient.createOrUpdateAlias(expectedUpdatedAlias)).assertNext(updatedAlias -> { assertEquals(expectedUpdatedAlias.getName(), updatedAlias.getName()); @@ -265,7 +252,7 @@ public void canUpdateAliasAfterCreationAsync() { @Test public void canDeleteAliasSync() { String aliasName = testResourceNamer.randomName("my-alias", 32); - indexClient.createAlias(new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME1))); + indexClient.createAlias(new SearchAlias(aliasName, HOTEL_INDEX_NAME1)); assertDoesNotThrow(() -> indexClient.deleteAlias(aliasName)); @@ -278,7 +265,7 @@ public void canDeleteAliasSync() { @Test public void canDeleteAliasAsync() { String aliasName = testResourceNamer.randomName("my-alias", 32); - indexAsyncClient.createAlias(new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME1))).block(); + indexAsyncClient.createAlias(new SearchAlias(aliasName, HOTEL_INDEX_NAME1)).block(); StepVerifier.create(indexAsyncClient.deleteAlias(aliasName)).verifyComplete(); @@ -291,7 +278,7 @@ public void canDeleteAliasAsync() { @Test public void cannotDeleteIndexWithAliasSyncAndAsync() { String aliasName = testResourceNamer.randomName("my-alias", 32); - indexClient.createAlias(new SearchAlias(aliasName, Collections.singletonList(HOTEL_INDEX_NAME1))); + indexClient.createAlias(new SearchAlias(aliasName, HOTEL_INDEX_NAME1)); aliasesToDelete.add(aliasName); // Give 3 seconds for alias deletion to propagate. @@ -308,15 +295,15 @@ public void cannotDeleteIndexWithAliasSyncAndAsync() { @Test public void canListAliasesSyncAndAsync() { String firstAliasName = testResourceNamer.randomName("my-alias", 32); - indexClient.createAlias(new SearchAlias(firstAliasName, Collections.singletonList(HOTEL_INDEX_NAME1))); + indexClient.createAlias(new SearchAlias(firstAliasName, HOTEL_INDEX_NAME1)); aliasesToDelete.add(firstAliasName); String secondAliasName = testResourceNamer.randomName("my-alias", 32); - indexClient.createAlias(new SearchAlias(secondAliasName, Collections.singletonList(HOTEL_INDEX_NAME1))); + indexClient.createAlias(new SearchAlias(secondAliasName, HOTEL_INDEX_NAME1)); aliasesToDelete.add(secondAliasName); String thirdAliasName = testResourceNamer.randomName("my-alias", 32); - indexClient.createAlias(new SearchAlias(thirdAliasName, Collections.singletonList(HOTEL_INDEX_NAME1))); + indexClient.createAlias(new SearchAlias(thirdAliasName, HOTEL_INDEX_NAME1)); aliasesToDelete.add(thirdAliasName); List syncAliases = indexClient.listAliases().stream().collect(Collectors.toList()); @@ -335,15 +322,15 @@ public void canListAliasesSyncAndAsync() { @Test public void canInspectAliasUsageInServiceStatisticsSyncAndAsync() { - aliasesToDelete.add(indexClient.createAlias( - new SearchAlias(testResourceNamer.randomName("my-alias", 32), Collections.singletonList(HOTEL_INDEX_NAME1))) - .getName()); - aliasesToDelete.add(indexClient.createAlias( - new SearchAlias(testResourceNamer.randomName("my-alias", 32), Collections.singletonList(HOTEL_INDEX_NAME1))) - .getName()); - aliasesToDelete.add(indexClient.createAlias( - new SearchAlias(testResourceNamer.randomName("my-alias", 32), Collections.singletonList(HOTEL_INDEX_NAME1))) - .getName()); + aliasesToDelete.add( + indexClient.createAlias(new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1)) + .getName()); + aliasesToDelete.add( + indexClient.createAlias(new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1)) + .getName()); + aliasesToDelete.add( + indexClient.createAlias(new SearchAlias(testResourceNamer.randomName("my-alias", 32), HOTEL_INDEX_NAME1)) + .getName()); // Give 3 seconds for alias creation to propagate. sleepIfRunningAgainstService(3000); 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 index a75e198554b8..30b9acd918d5 100644 --- 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 @@ -39,7 +39,7 @@ 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; + private static final SearchServiceVersion API_VERSION = SearchServiceVersion.getLatest(); @Test public void buildSyncClientTest() { @@ -112,19 +112,9 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { 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("")); + assertThrows(NullPointerException.class, () -> new SearchClientBuilder().indexName(null).buildClient()); } @Test 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/SearchIndexingBufferedSenderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexingBufferedSenderTests.java index ae56ae11e3c8..71719a9f01a1 100644 --- 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 @@ -304,7 +304,7 @@ public void indexManyDocumentsSmallDocumentSets() { AtomicInteger successCount = new AtomicInteger(); AtomicInteger failedCount = new AtomicInteger(); - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { + SearchClientBuilder builder = clientBuilder.addPolicy((ignored, next) -> { requestCount.incrementAndGet(); return next.process(); }); @@ -314,8 +314,8 @@ public void indexManyDocumentsSmallDocumentSets() { .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) .autoFlushInterval(Duration.ofSeconds(5)) .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> failedCount.incrementAndGet()) .buildSender(); List> documents = readJsonFileToList(HOTELS_DATA_JSON); @@ -348,7 +348,7 @@ public void indexManyDocumentsSmallDocumentSetsAsync() { AtomicInteger successCount = new AtomicInteger(); AtomicInteger failedCount = new AtomicInteger(); - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { + SearchClientBuilder builder = clientBuilder.addPolicy((ignored, next) -> { requestCount.incrementAndGet(); return next.process(); }); @@ -359,8 +359,8 @@ public void indexManyDocumentsSmallDocumentSetsAsync() { .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) .autoFlushInterval(Duration.ofSeconds(5)) .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> failedCount.incrementAndGet()) .buildAsyncSender(); List> documents = readJsonFileToList(HOTELS_DATA_JSON); @@ -394,7 +394,7 @@ public void indexManyDocumentsOneLargeDocumentSet() { AtomicInteger successCount = new AtomicInteger(); AtomicInteger failedCount = new AtomicInteger(); - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { + SearchClientBuilder builder = clientBuilder.addPolicy((ignored, next) -> { requestCount.incrementAndGet(); return next.process(); }); @@ -404,8 +404,8 @@ public void indexManyDocumentsOneLargeDocumentSet() { .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) .autoFlushInterval(Duration.ofSeconds(5)) .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> failedCount.incrementAndGet()) .buildSender(); List> documents = readJsonFileToList(HOTELS_DATA_JSON); @@ -442,7 +442,7 @@ public void indexManyDocumentsOneLargeDocumentSetAsync() { AtomicInteger successCount = new AtomicInteger(); AtomicInteger failedCount = new AtomicInteger(); - SearchClientBuilder builder = clientBuilder.addPolicy((context, next) -> { + SearchClientBuilder builder = clientBuilder.addPolicy((ignored, next) -> { requestCount.incrementAndGet(); return next.process(); }); @@ -453,8 +453,8 @@ public void indexManyDocumentsOneLargeDocumentSetAsync() { .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) .autoFlushInterval(Duration.ofSeconds(5)) .initialBatchActionCount(10) - .onActionSucceeded(options -> successCount.incrementAndGet()) - .onActionError(options -> failedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> failedCount.incrementAndGet()) .buildAsyncSender(); List> documents = readJsonFileToList(HOTELS_DATA_JSON); 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 index 515a0168ef78..008dc7b2753a 100644 --- 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 @@ -10,16 +10,15 @@ 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.SharedExecutorService; 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 com.azure.search.documents.models.IndexDocumentsBatch; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; @@ -49,8 +48,9 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static com.azure.search.documents.SearchTestBase.SEARCH_ENDPOINT; import static com.azure.search.documents.SearchTestBase.HOTELS_DATA_JSON; +import static com.azure.search.documents.SearchTestBase.SEARCH_ENDPOINT; +import static com.azure.search.documents.TestHelpers.createIndexAction; import static com.azure.search.documents.TestHelpers.getTestTokenCredential; import static com.azure.search.documents.TestHelpers.readJsonFileToList; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -90,7 +90,7 @@ private static HttpClient wrapWithAsserting(HttpClient wrappedHttpClient, boolea } /** - * Tests that a batch can timeout while indexing. + * Tests that a batch can time out while indexing. */ @Test public void flushTimesOut() { @@ -106,11 +106,11 @@ public void flushTimesOut() { batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1)); - assertThrows(RuntimeException.class, () -> batchingClient.flush(Duration.ofSeconds(1), Context.NONE)); + assertThrows(RuntimeException.class, () -> batchingClient.flush(Duration.ofSeconds(1), null)); } /** - * Tests that a batch can timeout while indexing. + * Tests that a batch can time out while indexing. */ @Test public void flushTimesOutAsync() { @@ -131,7 +131,7 @@ public void flushTimesOutAsync() { } /** - * Tests that a batch will retain in-flight documents if the request is cancelled before the response is handled. + * Tests that a batch will retain in-flight documents if the request is canceled before the response is handled. */ @Test @Disabled("Temporarily disabled") @@ -163,11 +163,11 @@ public void inFlightDocumentsAreRetried() { batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); - // First request is setup to timeout. - assertThrows(RuntimeException.class, () -> batchingClient.flush(Duration.ofSeconds(3), Context.NONE)); + // First request is set up to timeout. + assertThrows(RuntimeException.class, () -> batchingClient.flush(Duration.ofSeconds(3), null)); // Second request shouldn't timeout. - assertDoesNotThrow(() -> batchingClient.flush(Duration.ofSeconds(3), Context.NONE)); + assertDoesNotThrow(() -> batchingClient.flush(Duration.ofSeconds(3), null)); // Then validate that we have the expected number of requests sent and responded. assertEquals(10, addedCount.get()); @@ -177,7 +177,7 @@ public void inFlightDocumentsAreRetried() { } /** - * Tests that a batch will retain in-flight documents if the request is cancelled before the response is handled. + * Tests that a batch will retain in-flight documents if the request is canceled before the response is handled. */ @Test @Disabled("Temporarily disabled") @@ -209,7 +209,7 @@ public void inFlightDocumentsAreRetriedAsync() { StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); - // First request is setup to timeout. + // First request is set up to timeout. StepVerifier.create(batchingClient.flush().timeout(Duration.ofSeconds(3))).verifyError(TimeoutException.class); // Second request shouldn't timeout. @@ -238,10 +238,10 @@ public void batchHasSomeFailures() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); @@ -276,10 +276,10 @@ public void batchHasSomeFailuresAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); @@ -314,10 +314,10 @@ public void retryableDocumentsAreAddedBackToTheBatch() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); @@ -352,10 +352,10 @@ public void retryableDocumentsAreAddedBackToTheBatchAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); @@ -402,10 +402,10 @@ public void batchSplits() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); @@ -452,10 +452,10 @@ public void batchSplitsAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); @@ -612,7 +612,6 @@ public void batchWithDuplicateKeysBeingRetriedTakesAllNonDuplicateKeysAsync() { } }, false)) .bufferedSender(HOTEL_DOCUMENT_TYPE) - .autoFlush(false) .documentKeyRetriever(HOTEL_ID_KEY_RETRIEVER) .buildAsyncSender(); @@ -636,7 +635,8 @@ public void batchWithDuplicateKeysBeingRetriedTakesAllNonDuplicateKeysAsync() { */ assertEquals(1, batchingClient.getActions().size()); - StepVerifier.create(batchingClient.flush().then(batchingClient.close())).verifyComplete(); + StepVerifier.create(batchingClient.flush()).verifyComplete(); + StepVerifier.create(batchingClient.close()).verifyComplete(); /* * No documents should remain as no duplicate keys exists. @@ -664,10 +664,10 @@ public void batchRetriesUntilLimit() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1)); @@ -714,10 +714,10 @@ public void batchRetriesUntilLimitAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 1))) @@ -763,10 +763,10 @@ public void batchSplitsUntilOneAndFails() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2)); @@ -802,10 +802,10 @@ public void batchSplitsUntilOneAndFailsAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2))) @@ -845,10 +845,10 @@ public void batchSplitsUntilOneAndPartiallyFails() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2)); @@ -887,10 +887,10 @@ public void batchSplitsUntilOneAndPartiallyFailsAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON).subList(0, 2))) @@ -930,27 +930,26 @@ public void batchSplitsUntilOneAndPartiallyFailsAsync() { static Stream>>> operationsThrowAfterClientIsClosedSupplier() { List> simpleDocuments = Collections.singletonList(Collections.singletonMap("key", "value")); - List>> actions = simpleDocuments.stream() - .map(document -> new IndexAction>().setDocument(document) - .setActionType(IndexActionType.UPLOAD)) + List actions = simpleDocuments.stream() + .map(document -> createIndexAction(IndexActionType.UPLOAD, document)) .collect(Collectors.toList()); return Stream.of(client -> client.addActions(actions), - client -> client.addActions(actions, Duration.ofSeconds(60), Context.NONE), + client -> client.addActions(actions, Duration.ofSeconds(60), null), client -> client.addUploadActions(simpleDocuments), - client -> client.addUploadActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), + client -> client.addUploadActions(simpleDocuments, Duration.ofSeconds(60), null), client -> client.addMergeOrUploadActions(simpleDocuments), - client -> client.addMergeOrUploadActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), + client -> client.addMergeOrUploadActions(simpleDocuments, Duration.ofSeconds(60), null), client -> client.addMergeActions(simpleDocuments), - client -> client.addMergeActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), + client -> client.addMergeActions(simpleDocuments, Duration.ofSeconds(60), null), client -> client.addDeleteActions(simpleDocuments), - client -> client.addDeleteActions(simpleDocuments, Duration.ofSeconds(60), Context.NONE), + client -> client.addDeleteActions(simpleDocuments, Duration.ofSeconds(60), null), - SearchIndexingBufferedSender::flush, client -> client.flush(Duration.ofSeconds(60), Context.NONE)); + SearchIndexingBufferedSender::flush, client -> client.flush(Duration.ofSeconds(60), null)); } @ParameterizedTest @@ -972,9 +971,8 @@ public void operationsThrowAfterClientIsClosedAsync( 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)) + List actions = simpleDocuments.stream() + .map(document -> createIndexAction(IndexActionType.UPLOAD, document)) .collect(Collectors.toList()); return Stream.of(client -> client.addActions(actions), client -> client.addUploadActions(simpleDocuments), @@ -1281,10 +1279,10 @@ public void serverBusyResponseRetries() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildSender(); batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON)); @@ -1326,10 +1324,10 @@ public void serverBusyResponseRetriesAsync() { .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()) + .onActionAdded(ignored -> addedCount.incrementAndGet()) + .onActionSucceeded(ignored -> successCount.incrementAndGet()) + .onActionError(ignored -> errorCount.incrementAndGet()) + .onActionSent(ignored -> sentCount.incrementAndGet()) .buildAsyncSender(); StepVerifier.create(batchingClient.addUploadActions(readJsonFileToList(HOTELS_DATA_JSON))).verifyComplete(); @@ -1503,7 +1501,7 @@ public void emptyBatchIsNeverSent() { AtomicInteger requestCount = new AtomicInteger(); SearchIndexingBufferedSender> batchingClient = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .addPolicy((context, next) -> { + .addPolicy((ignored, next) -> { requestCount.incrementAndGet(); return next.process(); }) @@ -1526,7 +1524,7 @@ public void emptyBatchIsNeverSentAsync() { AtomicInteger requestCount = new AtomicInteger(); SearchIndexingBufferedAsyncSender> batchingClient = getSearchClientBuilder().httpClient(request -> Mono.just(new MockHttpResponse(request, 200))) - .addPolicy((context, next) -> { + .addPolicy((ignored, next) -> { requestCount.incrementAndGet(); return next.process(); }) @@ -1575,9 +1573,9 @@ private static Mono createMockBatchSplittingResponse(HttpRequest r 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); + IndexDocumentsBatch indexBatch = IndexDocumentsBatch.fromJson(reader); - // Given the initial size was 10 and it was split we should expect 5 elements. + // Given the initial size was 10, and it was split we should expect 5 elements. assertNotNull(indexBatch); assertEquals(expectedBatchSize, indexBatch.getActions().size()); 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 index 6363cdfeea33..ede4fcf11805 100644 --- 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 @@ -33,7 +33,7 @@ public void canGetIndexClientFromSearchClient() { assertNotNull(searchClient); // Validate the client points to the same instance - assertEquals(serviceClient.getEndpoint(), searchClient.getEndpoint()); + assertEquals(IndexesTestHelpers.getEndpoint(serviceClient), searchClient.getEndpoint()); // Validate that the client uses the same HTTP pipeline for authentication, retries, etc HttpPipeline servicePipeline = IndexesTestHelpers.getHttpPipeline(serviceClient); @@ -55,7 +55,7 @@ public void canGetIndexAsyncClientFromSearchClient() { assertNotNull(searchAsyncClient); // Validate the client points to the same instance - assertEquals(indexAsyncClient.getEndpoint(), searchAsyncClient.getEndpoint()); + assertEquals(IndexesTestHelpers.getEndpoint(indexAsyncClient), searchAsyncClient.getEndpoint()); // Validate that the client uses the same HTTP pipeline for authentication, retries, etc HttpPipeline servicePipeline = IndexesTestHelpers.getHttpPipeline(indexAsyncClient); 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 index 3eafbd51c842..4b4752281dc2 100644 --- 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 @@ -19,13 +19,12 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.json.JsonProviders; import com.azure.json.JsonReader; -import com.azure.search.documents.knowledgebases.SearchKnowledgeBaseClientBuilder; 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.DataSourceCredentials; import com.azure.search.documents.indexes.models.DistanceScoringFunction; import com.azure.search.documents.indexes.models.DistanceScoringParameters; import com.azure.search.documents.indexes.models.FreshnessScoringFunction; @@ -39,29 +38,25 @@ 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.SearchIndexerDataContainer; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; +import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; 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 com.azure.search.documents.knowledgebases.KnowledgeBaseRetrievalClientBuilder; 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.time.OffsetDateTime; +import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; -import java.util.TimeZone; import java.util.function.BiConsumer; 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; @@ -191,11 +186,12 @@ protected SearchIndexerClientBuilder getSearchIndexerClientBuilder(boolean isSyn return builder; } - protected SearchKnowledgeBaseClientBuilder getSearchKnowledgeBaseClientBuilder(boolean isSync) { - SearchKnowledgeBaseClientBuilder builder = new SearchKnowledgeBaseClientBuilder().endpoint(SEARCH_ENDPOINT) - .credential(getTestTokenCredential()) - .httpClient(getHttpClient(interceptorManager, isSync)) - .retryOptions(SERVICE_THROTTLE_SAFE_RETRY_OPTIONS); + protected KnowledgeBaseRetrievalClientBuilder getKnowledgeBaseRetrievalClientBuilder(boolean isSync) { + KnowledgeBaseRetrievalClientBuilder builder + = new KnowledgeBaseRetrievalClientBuilder().endpoint(SEARCH_ENDPOINT) + .credential(getTestTokenCredential()) + .httpClient(getHttpClient(interceptorManager, isSync)) + .retryOptions(SERVICE_THROTTLE_SAFE_RETRY_OPTIONS); // Disable `("$..token")` and `name` sanitizer if (!interceptorManager.isLiveMode() && !sanitizersRemoved) { @@ -279,143 +275,141 @@ private static HttpClient getHttpClient(InterceptorManager interceptorManager, b } protected SearchIndex createTestIndex(String indexName) { - Map weights = new HashMap<>(); + Map weights = new LinkedHashMap<>(); 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) + new SearchField("HotelId", SearchFieldDataType.STRING).setKey(Boolean.TRUE) + .setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setSearchable(Boolean.TRUE), + new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setSearchable(Boolean.TRUE), + new SearchField("Description", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE) + .setSearchable(Boolean.TRUE), + new SearchField("DescriptionFr", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setAnalyzerName(LexicalAnalyzerName.FR_LUCENE) + .setSearchable(Boolean.TRUE), + new SearchField("Description_Custom", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setSearchAnalyzerName(LexicalAnalyzerName.STOP) + .setIndexAnalyzerName(LexicalAnalyzerName.STOP) + .setSearchable(Boolean.TRUE), + new SearchField("Category", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setSearchable(Boolean.TRUE), + new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + .setSearchable(Boolean.TRUE) + .setFilterable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("ParkingIncluded", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("LastRenovationDate", SearchFieldDataType.DATE_TIME_OFFSET).setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("Rating", SearchFieldDataType.INT32).setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("Address", SearchFieldDataType.COMPLEX).setFields( + new SearchField("StreetAddress", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setSearchable(Boolean.TRUE), + new SearchField("City", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("StateProvince", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("Country", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) .setFilterable(Boolean.TRUE) .setSortable(Boolean.TRUE) .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("PostalCode", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) .setFilterable(Boolean.TRUE) .setSortable(Boolean.TRUE) - .setHidden(Boolean.FALSE), + .setFacetable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE)), + new SearchField("Location", SearchFieldDataType.GEOGRAPHY_POINT).setFilterable(Boolean.TRUE) + .setSortable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("Rooms", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)).setFields( new SearchField("Description", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) - .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE) - .setHidden(Boolean.FALSE), + .setAnalyzerName(LexicalAnalyzerName.EN_LUCENE), 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) + .setRetrievable(Boolean.TRUE), + new SearchField("Type", 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) + .setRetrievable(Boolean.TRUE), + new SearchField("BaseRate", SearchFieldDataType.DOUBLE).setKey(Boolean.FALSE) .setFilterable(Boolean.TRUE) .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("ParkingIncluded", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("BedOptions", SearchFieldDataType.STRING).setSearchable(Boolean.TRUE) + .setFilterable(Boolean.TRUE) .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("SleepsCount", SearchFieldDataType.INT32).setFilterable(Boolean.TRUE) .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("LastRenovationDate", SearchFieldDataType.DATE_TIME_OFFSET).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("SmokingAllowed", SearchFieldDataType.BOOLEAN).setFilterable(Boolean.TRUE) .setFacetable(Boolean.TRUE) - .setHidden(Boolean.FALSE), - new SearchField("Rating", SearchFieldDataType.INT32).setFilterable(Boolean.TRUE) - .setSortable(Boolean.TRUE) + .setRetrievable(Boolean.TRUE), + new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)) + .setSearchable(Boolean.TRUE) + .setFilterable(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, + .setRetrievable(Boolean.TRUE)), + 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"))); + 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("http://tempuri.org", "http://localhost:80").setMaxAgeInSeconds(60L)) + .setSuggesters(new SearchSuggester("FancySuggester", "HotelName")); } protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject() { @@ -430,12 +424,22 @@ protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject( protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject(String name, DataDeletionDetectionPolicy dataDeletionDetectionPolicy, DataChangeDetectionPolicy dataChangeDetectionPolicy) { + return createTestSqlDataSourceObject(name, null, dataDeletionDetectionPolicy, dataChangeDetectionPolicy); + } + + protected SearchIndexerDataSourceConnection createTestSqlDataSourceObject(String name, + SearchIndexerDataContainer container, 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); + return new SearchIndexerDataSourceConnection(name, SearchIndexerDataSourceType.AZURE_SQL, + new DataSourceCredentials().setConnectionString(FAKE_AZURE_SQL_CONNECTION_STRING), + (container == null) ? new SearchIndexerDataContainer("GeoNamesRI") : container) + .setDescription(FAKE_DESCRIPTION) + .setDataChangeDetectionPolicy(dataChangeDetectionPolicy) + .setDataDeletionDetectionPolicy(dataDeletionDetectionPolicy); } protected String randomIndexName(String indexNameBase) { @@ -484,14 +488,7 @@ protected void compareMaps(Map expectedMap, Map 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); - } + protected static OffsetDateTime parseDate(String dateString) { + return OffsetDateTime.parse(dateString); } } 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 index 05e1d80f0a82..c5dd8e8a8d2b 100644 --- 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 @@ -4,11 +4,13 @@ package com.azure.search.documents; import com.azure.core.exception.HttpResponseException; -import com.azure.core.models.GeoPoint; import com.azure.core.test.TestMode; import com.azure.core.test.TestProxyTestBase; import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.util.Context; +import com.azure.core.util.IterableStream; +import com.azure.json.JsonProviders; +import com.azure.json.JsonReader; +import com.azure.json.JsonWriter; import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SearchFieldDataType; @@ -16,37 +18,38 @@ 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.SearchPagedFlux; +import com.azure.search.documents.models.SearchPagedIterable; +import com.azure.search.documents.models.SearchPagedResponse; 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 com.azure.search.documents.testingmodels.Bucket; +import com.azure.search.documents.testingmodels.Hotel; +import com.azure.search.documents.testingmodels.NonNullableModel; 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.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.time.Instant; 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.Iterator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; @@ -55,10 +58,11 @@ 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.convertFromMapStringObject; 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 com.azure.search.documents.TestHelpers.uploadDocumentsRaw; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -90,9 +94,9 @@ public static void setupClass() { 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()); + uploadDocumentsRaw(searchIndexClient.getSearchClient(LARGE_INDEX_NAME), createHotelsList()); - searchIndexClient.createSynonymMap(new SynonymMap(SYNONYM_NAME).setSynonyms("luxury,fancy")); + searchIndexClient.createSynonymMap(new SynonymMap(SYNONYM_NAME, "luxury,fancy")); // Attach index field to SynonymMap SearchIndex hotelsIndex = searchIndexClient.getIndex(SYNONYM_INDEX_NAME); @@ -142,28 +146,28 @@ private SearchAsyncClient getAsyncClient(String indexName) { @Test public void searchThrowsWhenRequestIsMalformedSync() { - badSearchSync("*", new SearchOptions().setFilter("This is not a valid filter.")); + badSearchSync(new SearchOptions().setFilter("This is not a valid filter.")); } @Test public void searchThrowsWhenRequestIsMalformedAsync() { - badSearchAsync("*", new SearchOptions().setFilter("This is not a valid filter.")); + badSearchAsync(new SearchOptions().setFilter("This is not a valid filter.")); } @Test public void searchThrowsWhenSpecialCharInRegexIsUnescapedSync() { - badSearchSync("/.*/.*/", new SearchOptions().setQueryType(QueryType.FULL)); + badSearchSync(new SearchOptions().setSearchText("/.*/.*/").setQueryType(QueryType.FULL)); } @Test public void searchThrowsWhenSpecialCharInRegexIsUnescapedAsync() { - badSearchAsync("/.*/.*/", new SearchOptions().setQueryType(QueryType.FULL)); + badSearchAsync(new SearchOptions().setSearchText("/.*/.*/").setQueryType(QueryType.FULL)); } - private void badSearchSync(String searchText, SearchOptions searchOptions) { + private void badSearchSync(SearchOptions searchOptions) { HttpResponseException ex = assertThrows(HttpResponseException.class, () -> getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient() - .search(searchText, searchOptions, Context.NONE) + .search(searchOptions) .iterableByPage() .iterator() .next()); @@ -171,10 +175,11 @@ private void badSearchSync(String searchText, SearchOptions searchOptions) { 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 -> { + private void badSearchAsync(SearchOptions searchOptions) { + StepVerifier + .create(getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient().search(searchOptions).byPage()) + .thenRequest(1) + .verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); }); @@ -188,7 +193,7 @@ public void canSearchDynamicDocumentsSync() { Map> expectedHotels = hotels.stream().collect(Collectors.toMap(h -> h.get("HotelId").toString(), Function.identity())); - for (SearchPagedResponse response : client.search("*").iterableByPage()) { + for (SearchPagedResponse response : client.search(new SearchOptions()).iterableByPage()) { assertNull(response.getCount()); assertNull(response.getCoverage()); assertNull(response.getFacets()); @@ -197,7 +202,7 @@ public void canSearchDynamicDocumentsSync() { assertEquals(1, item.getScore(), 0); assertNull(item.getHighlights()); - SearchDocument actual = item.getDocument(SearchDocument.class); + Map actual = item.getAdditionalProperties(); Map expected = expectedHotels.remove(actual.get("HotelId").toString()); assertNotNull(expected); @@ -216,7 +221,7 @@ public void canSearchDynamicDocumentsAsync() { Map> expectedHotels = hotels.stream().collect(Collectors.toMap(h -> h.get("HotelId").toString(), Function.identity())); - StepVerifier.create(asyncClient.search("*").byPage()).thenConsumeWhile(response -> { + StepVerifier.create(asyncClient.search(new SearchOptions()).byPage()).thenConsumeWhile(response -> { assertNull(response.getCount()); assertNull(response.getCoverage()); assertNull(response.getFacets()); @@ -225,7 +230,7 @@ public void canSearchDynamicDocumentsAsync() { assertEquals(1, item.getScore(), 0); assertNull(item.getHighlights()); - SearchDocument actual = item.getDocument(SearchDocument.class); + Map actual = item.getAdditionalProperties(); Map expected = expectedHotels.remove(actual.get("HotelId").toString()); assertNotNull(expected); @@ -250,13 +255,11 @@ public void canContinueSearchSync() { 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()); + client.search(searchOptions).iterableByPage().forEach(page -> { + assertEquals(50, page.getElements().stream().count()); + assertListEqualHotelIds(expectedHotelIds.subList(total.get(), total.addAndGet(50)), page.getElements()); if (total.get() != 3000) { assertNotNull(page.getContinuationToken()); } else { @@ -278,11 +281,11 @@ public void canContinueSearchAsync() { = 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 -> { + 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()); + assertEquals(50, page.getElements().stream().count()); + assertListEqualHotelIds(expectedHotelIds.subList(total.get(), total.addAndGet(50)), page.getElements()); if (total.get() != 3000) { assertNotNull(page.getContinuationToken()); } else { @@ -304,23 +307,17 @@ public void canContinueSearchWithTopSync() { 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 = client.search(searchOptions).iterableByPage().iterator(); - Iterator iterator = results.iterableByPage().iterator(); + SearchPagedResponse firstPage = iterator.next(); + assertEquals(1000, firstPage.getElements().stream().count()); + assertListEqualHotelIds(expectedHotelIds.subList(0, 1000), firstPage.getElements()); + assertNotNull(firstPage.getContinuationToken()); - 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()); - } + SearchPagedResponse secondPage = iterator.next(); + assertEquals(1000, secondPage.getElements().stream().count()); + assertListEqualHotelIds(expectedHotelIds.subList(1000, 2000), secondPage.getElements()); + assertNull(secondPage.getContinuationToken()); } @Test @@ -335,13 +332,13 @@ public void canContinueSearchWithTopAsync() { 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()); + StepVerifier.create(asyncClient.search(searchOptions).byPage()).assertNext(response -> { + assertEquals(1000, response.getElements().stream().count()); + assertListEqualHotelIds(expectedHotelIds.subList(0, 1000), response.getElements()); assertNotNull(response.getContinuationToken()); }).assertNext(response -> { - assertEquals(1000, response.getValue().size()); - assertListEqualHotelIds(expectedHotelIds.subList(1000, 2000), response.getValue()); + assertEquals(1000, response.getElements().stream().count()); + assertListEqualHotelIds(expectedHotelIds.subList(1000, 2000), response.getElements()); assertNull(response.getContinuationToken()); }).verifyComplete(); } @@ -352,10 +349,10 @@ public void canSearchStaticallyTypedDocumentsSync() { List> hotels = readJsonFileToList(HOTELS_DATA_JSON); Map expectedHotels = hotels.stream() - .map(hotel -> convertMapToValue(hotel, Hotel.class)) + .map(hotel -> convertFromMapStringObject(hotel, Hotel::fromJson)) .collect(Collectors.toMap(Hotel::hotelId, Function.identity())); - for (SearchPagedResponse response : client.search("*", new SearchOptions(), Context.NONE).iterableByPage()) { + for (SearchPagedResponse response : client.search(new SearchOptions()).iterableByPage()) { assertNull(response.getCount()); assertNull(response.getCoverage()); assertNull(response.getFacets()); @@ -363,7 +360,7 @@ public void canSearchStaticallyTypedDocumentsSync() { response.getElements().forEach(sr -> { assertEquals(1, sr.getScore(), 0); assertNull(sr.getHighlights()); - Hotel actual = sr.getDocument(Hotel.class); + Hotel actual = convertFromMapStringObject(sr.getAdditionalProperties(), Hotel::fromJson); Hotel expected = expectedHotels.remove(actual.hotelId()); assertNotNull(expected); @@ -380,10 +377,10 @@ public void canSearchStaticallyTypedDocumentsAsync() { List> hotels = readJsonFileToList(HOTELS_DATA_JSON); Map expectedHotels = hotels.stream() - .map(hotel -> convertMapToValue(hotel, Hotel.class)) + .map(hotel -> convertFromMapStringObject(hotel, Hotel::fromJson)) .collect(Collectors.toMap(Hotel::hotelId, Function.identity())); - StepVerifier.create(asyncClient.search("*", new SearchOptions()).byPage()).thenConsumeWhile(response -> { + StepVerifier.create(asyncClient.search(new SearchOptions()).byPage()).thenConsumeWhile(response -> { assertNull(response.getCount()); assertNull(response.getCoverage()); assertNull(response.getFacets()); @@ -391,7 +388,7 @@ public void canSearchStaticallyTypedDocumentsAsync() { response.getElements().forEach(sr -> { assertEquals(1, sr.getScore(), 0); assertNull(sr.getHighlights()); - Hotel actual = sr.getDocument(Hotel.class); + Hotel actual = convertFromMapStringObject(sr.getAdditionalProperties(), Hotel::fromJson); Hotel expected = expectedHotels.remove(actual.hotelId()); assertNotNull(expected); @@ -404,39 +401,36 @@ public void canSearchStaticallyTypedDocumentsAsync() { 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())) + .startDate(OffsetDateTime.ofInstant(Instant.ofEpochMilli(1275346800000L), ZoneOffset.UTC)) + .endDate(OffsetDateTime.ofInstant(Instant.ofEpochMilli(1275346800000L), ZoneOffset.UTC)) .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<>(); + Map expectedDocs = new LinkedHashMap<>(); 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(); + Iterator iterator = client.search(new SearchOptions()).iterableByPage().iterator(); SearchPagedResponse result = iterator.next(); - Map actualDocs = result.getValue() + Map actualDocs = result.getElements() .stream() - .map(sr -> sr.getDocument(NonNullableModel.class)) + .map(sr -> convertFromMapStringObject(sr.getAdditionalProperties(), NonNullableModel::fromJson)) .collect(Collectors.toMap(NonNullableModel::key, Function.identity())); compareMaps(expectedDocs, actualDocs, (expected, actual) -> assertObjectEquals(expected, actual, true)); @@ -447,23 +441,23 @@ public void canRoundTripNonNullableValueTypesSyncAndAsync() { .isEnabled(true) .rating(5) .ratio(3.25) - .startDate(new Date(startEpoch.getTime())) - .endDate(new Date(startEpoch.getTime())) + .startDate(OffsetDateTime.ofInstant(Instant.ofEpochMilli(1275346800000L), ZoneOffset.UTC)) + .endDate(OffsetDateTime.ofInstant(Instant.ofEpochMilli(1275346800000L), ZoneOffset.UTC)) .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<>(); + Map expectedDocsAsync = new LinkedHashMap<>(); 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() + StepVerifier.create(asyncClient.search(new SearchOptions()).byPage()).assertNext(response -> { + Map actualDocsAsync = response.getElements() .stream() - .map(sr -> sr.getDocument(NonNullableModel.class)) + .map(sr -> convertFromMapStringObject(sr.getAdditionalProperties(), NonNullableModel::fromJson)) .filter(model -> model.key().endsWith("async")) .collect(Collectors.toMap(NonNullableModel::key, Function.identity())); @@ -472,37 +466,43 @@ public void canRoundTripNonNullableValueTypesSyncAndAsync() { }).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(); + Iterator iterator + = client.search(new SearchOptions().setSearchText("Fancy")).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); - } + SearchPagedResponse result = iterator.next(); + assertEquals(1, result.getElements().stream().count()); + OffsetDateTime actual = result.getElements() + .stream() + .findFirst() + .map(sr -> convertFromMapStringObject(sr.getAdditionalProperties(), Hotel::fromJson).lastRenovationDate()) + .get(); + assertEquals(expected, 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(); + StepVerifier.create(asyncClient.search(new SearchOptions().setSearchText("Fancy")).byPage()) + .assertNext(response -> { + assertEquals(1, response.getElements().stream().count()); + OffsetDateTime actual = response.getElements() + .stream() + .findFirst() + .map(sr -> convertFromMapStringObject(sr.getAdditionalProperties(), Hotel::fromJson) + .lastRenovationDate()) + .get(); + assertEquals(expected, actual); + }) + .verifyComplete(); } @Test @@ -514,39 +514,35 @@ public void canSearchWithSelectedFieldsSync() { 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<>(); + Map expectedHotel1 = new LinkedHashMap<>(); 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<>(); + Map expectedHotel2 = new LinkedHashMap<>(); expectedHotel2.put("HotelName", "Secret Point Motel"); expectedHotel2.put("Rating", 4); - HashMap address = new HashMap<>(); + Map address = new LinkedHashMap<>(); address.put("City", "New York"); expectedHotel2.put("Address", address); - HashMap rooms = new HashMap<>(); + Map rooms = new LinkedHashMap<>(); rooms.put("Type", "Budget Room"); - HashMap rooms2 = new HashMap<>(); + Map rooms2 = new LinkedHashMap<>(); 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)); + Iterator iterator + = client.search(sp.setSearchText("fancy luxury secret")).iterableByPage().iterator(); + SearchPagedResponse result = iterator.next(); + Iterator searchResults = result.getElements().iterator(); + SearchResult result1 = searchResults.next(); + SearchResult result2 = searchResults.next(); + assertFalse(searchResults.hasNext()); - assertMapEquals(expectedHotel1, hotel1, true); - assertMapEquals(expectedHotel2, hotel2, true); - } + assertMapEquals(expectedHotel1, result1.getAdditionalProperties(), true); + assertMapEquals(expectedHotel2, result2.getAdditionalProperties(), true); } @Test @@ -558,36 +554,36 @@ public void canSearchWithSelectedFieldsAsync() { sp.setSearchFields("HotelName", "Category"); sp.setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - HashMap expectedHotel1 = new HashMap<>(); + Map expectedHotel1 = new LinkedHashMap<>(); 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<>(); + Map expectedHotel2 = new LinkedHashMap<>(); expectedHotel2.put("HotelName", "Secret Point Motel"); expectedHotel2.put("Rating", 4); - HashMap address = new HashMap<>(); + Map address = new LinkedHashMap<>(); address.put("City", "New York"); expectedHotel2.put("Address", address); - HashMap rooms = new HashMap<>(); + Map rooms = new LinkedHashMap<>(); rooms.put("Type", "Budget Room"); - HashMap rooms2 = new HashMap<>(); + Map rooms2 = new LinkedHashMap<>(); 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)); + StepVerifier.create(asyncClient.search(sp.setSearchText("fancy luxury secret")).byPage()) + .assertNext(response -> { + Iterator searchResults = response.getElements().iterator(); + SearchResult result1 = searchResults.next(); + SearchResult result2 = searchResults.next(); + assertFalse(searchResults.hasNext()); - assertMapEquals(expectedHotel1, hotel1, true); - assertMapEquals(expectedHotel2, hotel2, true); - }).verifyComplete(); + assertMapEquals(expectedHotel1, result1.getAdditionalProperties(), true); + assertMapEquals(expectedHotel2, result2.getAdditionalProperties(), true); + }) + .verifyComplete(); } @Test @@ -596,11 +592,10 @@ public void canUseTopAndSkipForClientSidePagingSync() { SearchOptions parameters = new SearchOptions().setTop(3).setSkip(0).setOrderBy("HotelId"); - SearchPagedIterable results = client.search("*", parameters, Context.NONE); + SearchPagedIterable results = client.search(parameters); assertKeySequenceEqual(results, Arrays.asList("1", "10", "2")); - parameters.setSkip(3); - results = client.search("*", parameters, Context.NONE); + results = client.search(parameters.setSkip(3)); assertKeySequenceEqual(results, Arrays.asList("3", "4", "5")); } @@ -611,15 +606,13 @@ public void canUseTopAndSkipForClientSidePagingAsync() { SearchOptions parameters = new SearchOptions().setTop(3).setSkip(0).setOrderBy("HotelId"); StepVerifier - .create(getSearchResultsAsync(asyncClient.search("*", parameters, null, Context.NONE)) + .create(getSearchResultsAsync(asyncClient.search(parameters)) .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, null, Context.NONE)) + .create(getSearchResultsAsync(asyncClient.search(parameters.setSkip(3))) .map(docs -> docs.stream().map(sd -> sd.get("HotelId").toString()).collect(Collectors.toList()))) .assertNext(actualKeys -> assertEquals(Arrays.asList("3", "4", "5"), actualKeys)) .verifyComplete(); @@ -629,8 +622,7 @@ public void canUseTopAndSkipForClientSidePagingAsync() { public void searchWithoutOrderBySortsByScoreSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); - Iterator results - = client.search("*", new SearchOptions().setFilter("Rating lt 4"), Context.NONE).iterator(); + Iterator results = client.search(new SearchOptions().setFilter("Rating lt 4")).iterator(); SearchResult firstResult = results.next(); SearchResult secondResult = results.next(); assertTrue(firstResult.getScore() <= secondResult.getScore()); @@ -640,7 +632,7 @@ public void searchWithoutOrderBySortsByScoreSync() { public void searchWithoutOrderBySortsByScoreAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - StepVerifier.create(asyncClient.search("*", new SearchOptions().setFilter("Rating lt 4")).take(2).collectList()) + 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(); } @@ -652,9 +644,7 @@ public void orderByProgressivelyBreaksTiesSync() { 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) + = client.search(new SearchOptions().setOrderBy("Rating desc", "LastRenovationDate asc", "HotelId")) .stream() .map(SearchTests::getSearchResultId); @@ -668,10 +658,10 @@ public void orderByProgressivelyBreaksTiesAsync() { 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()) + .create( + asyncClient.search(new SearchOptions().setOrderBy("Rating desc", "LastRenovationDate asc", "HotelId")) + .map(SearchTests::getSearchResultId) + .collectList()) .assertNext(results -> assertArrayEquals(results.toArray(), expectedResults)) .verifyComplete(); } @@ -684,10 +674,7 @@ public void canFilterSync() { = 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); + List> searchResultsList = getSearchResultsSync(client.search(searchOptions)); assertEquals(2, searchResultsList.size()); assertEquals("1", searchResultsList.get(0).get("HotelId").toString()); assertEquals("5", searchResultsList.get(1).get("HotelId").toString()); @@ -701,13 +688,11 @@ public void canFilterAsync() { = 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(); + 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 @@ -719,17 +704,15 @@ public void canSearchWithRangeFacetsSync() { List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - for (SearchPagedResponse response : client.search("*", getSearchOptionsForRangeFacets(), Context.NONE) - .iterableByPage()) { + for (SearchPagedResponse response : client.search(getSearchOptionsForRangeFacets()).iterableByPage()) { Map> facets = response.getFacets(); assertNotNull(facets); - List> baseRateFacets = getRangeFacetsForField(facets, "Rooms/BaseRate", 4); - List> lastRenovationDateFacets - = getRangeFacetsForField(facets, "LastRenovationDate", 2); + List baseRateFacets = getRangeFacetsForField(facets, "Rooms/BaseRate", 4); + List lastRenovationDateFacets = getRangeFacetsForField(facets, "LastRenovationDate", 2); assertRangeFacets(baseRateFacets, lastRenovationDateFacets); - assertContainHotelIds(hotels, response.getValue()); + assertContainHotelIds(hotels, response.getElements()); } } @@ -742,17 +725,16 @@ public void canSearchWithRangeFacetsAsync() { List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - StepVerifier.create(asyncClient.search("*", getSearchOptionsForRangeFacets()).byPage()) + StepVerifier.create(asyncClient.search(getSearchOptionsForRangeFacets()).byPage()) .thenConsumeWhile(response -> { Map> facets = response.getFacets(); assertNotNull(facets); - List> baseRateFacets = getRangeFacetsForField(facets, "Rooms/BaseRate", 4); - List> lastRenovationDateFacets - = getRangeFacetsForField(facets, "LastRenovationDate", 2); + List baseRateFacets = getRangeFacetsForField(facets, "Rooms/BaseRate", 4); + List lastRenovationDateFacets = getRangeFacetsForField(facets, "LastRenovationDate", 2); assertRangeFacets(baseRateFacets, lastRenovationDateFacets); - assertContainHotelIds(hotels, response.getValue()); + assertContainHotelIds(hotels, response.getElements()); return true; }) @@ -765,8 +747,7 @@ public void canSearchWithValueFacetsSync() { List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - for (SearchPagedResponse response : client.search("*", getSearchOptionsForValueFacets(), Context.NONE) - .iterableByPage()) { + for (SearchPagedResponse response : client.search(getSearchOptionsForValueFacets()).iterableByPage()) { Map> facets = response.getFacets(); assertNotNull(facets); @@ -780,7 +761,7 @@ public void canSearchWithValueFacetsAsync() { List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - StepVerifier.create(asyncClient.search("*", getSearchOptionsForValueFacets()).byPage()) + StepVerifier.create(asyncClient.search(getSearchOptionsForValueFacets()).byPage()) .thenConsumeWhile(response -> { Map> facets = response.getFacets(); assertNotNull(facets); @@ -796,14 +777,14 @@ public void canSearchWithValueFacetsAsync() { public void canSearchWithLuceneSyntaxSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); - Map expectedResult = new HashMap<>(); + Map expectedResult = new LinkedHashMap<>(); 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)); + List> searchResultsList + = getSearchResultsSync(client.search(searchOptions.setSearchText("HotelName:roch~"))); assertEquals(1, searchResultsList.size()); assertEquals(expectedResult, searchResultsList.get(0)); } @@ -812,13 +793,13 @@ public void canSearchWithLuceneSyntaxSync() { public void canSearchWithLuceneSyntaxAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - Map expectedResult = new HashMap<>(); + Map expectedResult = new LinkedHashMap<>(); 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))) + StepVerifier.create(getSearchResultsAsync(asyncClient.search(searchOptions.setSearchText("HotelName:roch~")))) .assertNext(searchResultsList -> { assertEquals(1, searchResultsList.size()); assertEquals(expectedResult, searchResultsList.get(0)); @@ -835,33 +816,33 @@ public void canFilterNonNullableTypeSyncAndAsync() { indexesToDelete.add(indexName); SearchClient client = getSearchClientBuilder(indexName, true).buildClient(); - List docsList = createDocsListWithValueTypes(""); - uploadDocuments(client, docsList); + List> docsList = createDocsListWithValueTypes(""); + uploadDocumentsRaw(client, docsList); - Map expectedDocs = docsList.stream() + 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); + SearchPagedIterable results = client.search(searchOptions); assertNotNull(results); - Map actualDocs = results.stream() - .map(sr -> sr.getDocument(SearchDocument.class)) + Map> actualDocs = results.stream() + .map(SearchResult::getAdditionalProperties) .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); + List> docsListAsync = createDocsListWithValueTypes("async"); + uploadDocumentsRaw(asyncClient, docsListAsync); - Map expectedDocsAsync = docsListAsync.stream() + 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)) + .create(asyncClient.search(searchOptions) + .map(SearchResult::getAdditionalProperties) .filter(doc -> doc.get("Key").toString().endsWith("async")) .collectMap(sd -> sd.get("Key").toString())) .assertNext(resultsAsync -> compareMaps(expectedDocsAsync, resultsAsync, @@ -873,8 +854,10 @@ public void canFilterNonNullableTypeSyncAndAsync() { 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)); + List> response + = getSearchResultsSync(client.search(new SearchOptions().setSearchText("Cheapest hotel") + .setQueryType(QueryType.SIMPLE) + .setSearchMode(SearchMode.ALL))); assertEquals(1, response.size()); assertEquals("2", response.get(0).get("HotelId")); @@ -884,22 +867,20 @@ public void canSearchWithSearchModeAllSync() { 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 -> { + StepVerifier.create(getSearchResultsAsync(asyncClient.search(new SearchOptions().setSearchText("Cheapest hotel") + .setQueryType(QueryType.SIMPLE) + .setSearchMode(SearchMode.ALL)))).assertNext(response -> { assertEquals(1, response.size()); assertEquals("2", response.get(0).get("HotelId")); - }) - .verifyComplete(); + }).verifyComplete(); } @Test public void defaultSearchModeIsAnySync() { SearchClient client = getClient(HOTEL_INDEX_NAME); - List response = getSearchResultsSync( - client.search("Cheapest hotel", new SearchOptions().setOrderBy("HotelId"), Context.NONE)); + List> response = getSearchResultsSync( + client.search(new SearchOptions().setSearchText("Cheapest hotel").setOrderBy("HotelId"))); 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())); @@ -910,8 +891,8 @@ public void defaultSearchModeIsAnyAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); StepVerifier - .create( - getSearchResultsAsync(asyncClient.search("Cheapest hotel", new SearchOptions().setOrderBy("HotelId")))) + .create(getSearchResultsAsync( + asyncClient.search(new SearchOptions().setSearchText("Cheapest hotel").setOrderBy("HotelId")))) .assertNext(response -> { assertEquals(7, response.size()); assertEquals(Arrays.asList("1", "10", "2", "3", "4", "5", "9"), @@ -925,10 +906,8 @@ 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); - - Iterator iterator = results.iterableByPage().iterator(); + Iterator iterator + = client.search(new SearchOptions().setIncludeTotalCount(true)).iterableByPage().iterator(); SearchPagedResponse page = iterator.next(); assertEquals(hotels.size(), page.getCount().intValue()); @@ -940,7 +919,7 @@ public void canGetResultCountInSearchAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - StepVerifier.create(asyncClient.search("*", new SearchOptions().setIncludeTotalCount(true)).byPage()) + StepVerifier.create(asyncClient.search(new SearchOptions().setIncludeTotalCount(true)).byPage()) .assertNext(response -> assertEquals(hotels.size(), response.getCount())) .verifyComplete(); } @@ -951,12 +930,12 @@ public void canSearchWithRegexSync() { SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL).setSelect("HotelName", "Rating"); - SearchPagedIterable results = client.search("HotelName:/.*oach.*\\/?/", searchOptions, Context.NONE); + SearchPagedIterable results = client.search(searchOptions.setSearchText("HotelName:/.*oach.*\\/?/")); assertNotNull(results); - List resultsList = getSearchResultsSync(results); + List> resultsList = getSearchResultsSync(results); - SearchDocument expectedHotel = new SearchDocument(); + Map expectedHotel = new LinkedHashMap<>(); expectedHotel.put("HotelName", "Roach Motel"); expectedHotel.put("Rating", 1); @@ -970,9 +949,10 @@ public void canSearchWithRegexAsync() { SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL).setSelect("HotelName", "Rating"); - StepVerifier.create(getSearchResultsAsync(asyncClient.search("HotelName:/.*oach.*\\/?/", searchOptions))) + StepVerifier + .create(getSearchResultsAsync(asyncClient.search(searchOptions.setSearchText("HotelName:/.*oach.*\\/?/")))) .assertNext(resultsList -> { - Map expectedHotel = new HashMap<>(); + Map expectedHotel = new LinkedHashMap<>(); expectedHotel.put("HotelName", "Roach Motel"); expectedHotel.put("Rating", 1); @@ -989,10 +969,10 @@ public void canSearchWithEscapedSpecialCharsInRegexSync() { SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.FULL); SearchPagedIterable results - = client.search("\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:", searchOptions, Context.NONE); + = client.search(searchOptions.setSearchText("\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:")); assertNotNull(results); - List resultsList = getSearchResultsSync(results); + List> resultsList = getSearchResultsSync(results); assertEquals(0, resultsList.size()); } @@ -1004,7 +984,7 @@ public void canSearchWithEscapedSpecialCharsInRegexAsync() { StepVerifier .create(getSearchResultsAsync( - asyncClient.search("\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:", searchOptions))) + asyncClient.search(searchOptions.setSearchText("\\+\\-\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:")))) .assertNext(response -> assertEquals(0, response.size())) .verifyComplete(); } @@ -1014,11 +994,11 @@ 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))) + .setScoringParameters("myloc--122.0,49.0") .setFilter("Rating eq 5 or Rating eq 1") .setOrderBy("HotelId desc"); - List response = getSearchResultsSync(client.search("hotel", searchOptions, Context.NONE)); + List> response = getSearchResultsSync(client.search(searchOptions.setSearchText("hotel"))); assertEquals(2, response.size()); assertEquals("2", response.get(0).get("HotelId").toString()); assertEquals("1", response.get(1).get("HotelId").toString()); @@ -1029,15 +1009,17 @@ 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))) + .setScoringParameters("myloc--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(); + StepVerifier.create(getSearchResultsAsync(asyncClient.search(searchOptions.setSearchText("hotel")))) + .assertNext(response -> { + assertEquals(2, response.size()); + assertEquals("2", response.get(0).get("HotelId").toString()); + assertEquals("1", response.get(1).get("HotelId").toString()); + }) + .verifyComplete(); } @Test @@ -1045,10 +1027,10 @@ 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"))) + .setScoringParameters("mytag-concierge,'Hello, O''Brien'") .setFilter("Rating eq 5 or Rating eq 1"); - List response = getSearchResultsSync(client.search("hotel", searchOptions, Context.NONE)); + List> response = getSearchResultsSync(client.search(searchOptions.setSearchText("hotel"))); assertEquals(2, response.size()); assertEquals(Arrays.asList("1", "2"), response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); @@ -1059,14 +1041,16 @@ 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"))) + .setScoringParameters("mytag-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(); + StepVerifier.create(getSearchResultsAsync(asyncClient.search(searchOptions.setSearchText("hotel")))) + .assertNext(response -> { + assertEquals(2, response.size()); + assertEquals(Arrays.asList("1", "2"), + response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); + }) + .verifyComplete(); } @Test @@ -1074,10 +1058,10 @@ public void searchWithScoringParametersEmptySync() { SearchClient client = getClient(HOTEL_INDEX_NAME); SearchOptions searchOptions = new SearchOptions().setScoringProfile("text") - .setScoringParameters(new ScoringParameter("mytag", Arrays.asList("", "concierge"))) + .setScoringParameters("mytag-concierge") .setFilter("Rating eq 5 or Rating eq 1"); - List response = getSearchResultsSync(client.search("hotel", searchOptions, Context.NONE)); + List> response = getSearchResultsSync(client.search(searchOptions.setSearchText("hotel"))); assertEquals(2, response.size()); assertEquals(Arrays.asList("1", "2"), response.stream().map(res -> res.get("HotelId").toString()).collect(Collectors.toList())); @@ -1088,24 +1072,24 @@ public void searchWithScoringParametersEmptyAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); SearchOptions searchOptions = new SearchOptions().setScoringProfile("text") - .setScoringParameters(new ScoringParameter("mytag", Arrays.asList("", "concierge"))) + .setScoringParameters("mytag-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(); + StepVerifier.create(getSearchResultsAsync(asyncClient.search(searchOptions.setSearchText("hotel")))) + .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(); + SearchPagedResponse response + = client.search(new SearchOptions().setMinimumCoverage(50.0)).iterableByPage().iterator().next(); assertEquals(100.0, response.getCoverage(), 0); } @@ -1114,7 +1098,7 @@ public void canSearchWithMinimumCoverageSync() { public void canSearchWithMinimumCoverageAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - StepVerifier.create(asyncClient.search("*", new SearchOptions().setMinimumCoverage(50.0)).byPage()) + StepVerifier.create(asyncClient.search(new SearchOptions().setMinimumCoverage(50.0)).byPage()) .assertNext(response -> assertEquals(100.0, response.getCoverage())) .verifyComplete(); } @@ -1134,26 +1118,25 @@ public void canUseHitHighlightingSync() { sp.setHighlightFields(category, description); //act - try (SearchPagedResponse result - = client.search("luxury hotel", sp, Context.NONE).iterableByPage().iterator().next()) { + SearchPagedResponse result = client.search(sp.setSearchText("luxury hotel")).iterableByPage().iterator().next(); - List documents = result.getValue(); - assertEquals(1, documents.size()); + Iterator documents = result.getElements().iterator(); - Map> highlights = documents.get(0).getHighlights(); - assertEquals(2, highlights.size()); - assertTrue(highlights.containsKey(description)); - assertTrue(highlights.containsKey(category)); + Map> highlights = documents.next().getHighlights(); + assertEquals(2, highlights.size()); + assertTrue(highlights.containsKey(description)); + assertTrue(highlights.containsKey(category)); - //asserts - assertEquals("Luxury", highlights.get(category).get(0)); + assertFalse(documents.hasNext()); - List expectedDescriptionHighlights - = Arrays.asList("Best hotel in town if you like luxury hotels.", - "We highly recommend this hotel."); + //asserts + assertEquals("Luxury", highlights.get(category).get(0)); - assertEquals(expectedDescriptionHighlights, highlights.get(description)); - } + List expectedDescriptionHighlights + = Arrays.asList("Best hotel in town if you like luxury hotels.", + "We highly recommend this hotel."); + + assertEquals(expectedDescriptionHighlights, highlights.get(description)); } @Test @@ -1170,15 +1153,16 @@ public void canUseHitHighlightingAsync() { sp.setHighlightPostTag(""); sp.setHighlightFields(category, description); - StepVerifier.create(asyncClient.search("luxury hotel", sp).byPage()).assertNext(result -> { - List documents = result.getValue(); + StepVerifier.create(asyncClient.search(sp.setSearchText("luxury hotel")).byPage()).assertNext(result -> { + Iterator documents = result.getElements().iterator(); - assertEquals(1, documents.size()); - Map> highlights = documents.get(0).getHighlights(); + Map> highlights = documents.next().getHighlights(); assertEquals(2, highlights.size()); assertTrue(highlights.containsKey(description)); assertTrue(highlights.containsKey(category)); + assertFalse(documents.hasNext()); + assertEquals("Luxury", highlights.get(category).get(0)); List expectedDescriptionHighlights @@ -1197,10 +1181,7 @@ public void canSearchWithSynonymsSync() { .setSearchFields("HotelName") .setSelect("HotelName", "Rating"); - SearchPagedIterable results = client.search("luxury", searchOptions, Context.NONE); - assertNotNull(results); - - List response = getSearchResultsSync(results); + List> response = getSearchResultsSync(client.search(searchOptions.setSearchText("luxury"))); assertEquals(1, response.size()); assertEquals("Fancy Stay", response.get(0).get("HotelName")); assertEquals(5, response.get(0).get("Rating")); @@ -1214,22 +1195,24 @@ public void canSearchWithSynonymsAsync() { .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(); + StepVerifier.create(getSearchResultsAsync(asyncClient.search(searchOptions.setSearchText("luxury")))) + .assertNext(results -> { + assertEquals(1, results.size()); + assertEquals("Fancy Stay", results.get(0).get("HotelName")); + assertEquals(5, results.get(0).get("Rating")); + }) + .verifyComplete(); } //==Elevated Read Tests== @Test public void searchWithElevatedReadIncludesHeader() { - SearchOptions searchOptions = new SearchOptions().setElevatedReadEnabled(true); + SearchOptions searchOptions = new SearchOptions().setEnableElevatedRead(true); - assertTrue(searchOptions.isElevatedReadEnabled(), "Elevated read should be enabled"); + assertTrue(searchOptions.isEnableElevatedRead(), "Elevated read should be enabled"); - SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search("*", searchOptions, Context.NONE); + SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search(searchOptions); assertNotNull(results, "Search with elevated read should work"); } @@ -1237,9 +1220,9 @@ public void searchWithElevatedReadIncludesHeader() { public void searchDefaultOmitsHeader() { SearchOptions searchOptions = new SearchOptions(); - assertNull(searchOptions.isElevatedReadEnabled(), "Elevated read should be null by default"); + assertNull(searchOptions.isEnableElevatedRead(), "Elevated read should be null by default"); - SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search("*", searchOptions, Context.NONE); + SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search(searchOptions); assertNotNull(results, "Default search should work"); } @@ -1247,21 +1230,19 @@ public void searchDefaultOmitsHeader() { public void listDocsWithElevatedReadIncludesHeader() { SearchIndexClient indexClient = getSearchIndexClientBuilder(true).buildClient(); - SearchOptions searchOptions - = new SearchOptions().setElevatedReadEnabled(true).setSelect("HotelId", "HotelName"); + SearchOptions searchOptions = new SearchOptions().setEnableElevatedRead(true).setSelect("HotelId", "HotelName"); - SearchPagedIterable results - = indexClient.getSearchClient(HOTEL_INDEX_NAME).search("*", searchOptions, Context.NONE); + SearchPagedIterable results = indexClient.getSearchClient(HOTEL_INDEX_NAME).search(searchOptions); assertNotNull(results, "Document listing with elevated read should work"); - assertTrue(searchOptions.isElevatedReadEnabled(), "Elevated read should be enabled"); + assertTrue(searchOptions.isEnableElevatedRead(), "Elevated read should be enabled"); } @Test public void withHeader200CodeparseResponse() { - SearchOptions searchOptions = new SearchOptions().setElevatedReadEnabled(true); + SearchOptions searchOptions = new SearchOptions().setEnableElevatedRead(true); - SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search("*", searchOptions, Context.NONE); + SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search(searchOptions); assertNotNull(results, "Should parse elevated read response"); assertNotNull(results.iterator(), "Should have results"); @@ -1269,10 +1250,10 @@ public void withHeader200CodeparseResponse() { @Test public void withHeaderPlusUserTokenService400() { - SearchOptions searchOptions = new SearchOptions().setElevatedReadEnabled(true); + SearchOptions searchOptions = new SearchOptions().setEnableElevatedRead(true); try { - SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search("*", searchOptions, Context.NONE); + SearchPagedIterable results = getClient(HOTEL_INDEX_NAME).search(searchOptions); assertNotNull(results, "Search completed (may not throw 400 in test environment)"); } catch (HttpResponseException ex) { assertEquals(400, ex.getResponse().getStatusCode()); @@ -1281,18 +1262,18 @@ public void withHeaderPlusUserTokenService400() { } } - @Test - public void oldApiVersionSupportsElevatedRead() { - SearchClient oldVersionClient - = getSearchClientBuilder(HOTEL_INDEX_NAME, true).serviceVersion(SearchServiceVersion.V2023_11_01) - .buildClient(); - - SearchOptions searchOptions = new SearchOptions().setElevatedReadEnabled(true); - - SearchPagedIterable results = oldVersionClient.search("*", searchOptions, null); - assertNotNull(results, "Older API version should support elevated read for backward compatibility"); - assertTrue(results.iterator().hasNext(), "Should have search results"); - } + // @Test + // public void oldApiVersionSupportsElevatedRead() { + // SearchClient oldVersionClient + // = getSearchClientBuilder(HOTEL_INDEX_NAME, true).serviceVersion(SearchServiceVersion.V2023_11_01) + // .buildClient(); + // + // SearchOptions searchOptions = new SearchOptions().setElevatedReadEnabled(true); + // + // SearchPagedIterable results = oldVersionClient.search("*", searchOptions, null); + // assertNotNull(results, "Older API version should support elevated read for backward compatibility"); + // assertTrue(results.iterator().hasNext(), "Should have search results"); + // } @Test public void currentApiVersionSendsHeaderWhenRequested() { @@ -1302,10 +1283,10 @@ public void currentApiVersionSendsHeaderWhenRequested() { .serviceVersion(SearchServiceVersion.V2025_11_01_PREVIEW) .buildClient(); - SearchOptions searchOptions = new SearchOptions().setElevatedReadEnabled(true); + SearchOptions searchOptions = new SearchOptions().setEnableElevatedRead(true); try { - SearchPagedIterable results = currentClient.search("*", searchOptions, Context.NONE); + SearchPagedIterable results = currentClient.search(searchOptions); assertNotNull(results, "Search with elevated read should work with current API version"); } catch (Exception exception) { assertFalse( @@ -1314,78 +1295,20 @@ public void currentApiVersionSendsHeaderWhenRequested() { } } - private static List getSearchResultsSync(SearchPagedIterable results) { - return results.stream().map(sr -> sr.getDocument(SearchDocument.class)).collect(Collectors.toList()); + private static List> getSearchResultsSync(SearchPagedIterable results) { + return results.stream().map(SearchResult::getAdditionalProperties).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 Mono>> getSearchResultsAsync(SearchPagedFlux results) { + return results.map(SearchResult::getAdditionalProperties).collectList(); } 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()) + .map(doc -> (String) doc.getAdditionalProperties().get("HotelId")) + .filter(Objects::nonNull) .collect(Collectors.toList()); assertEquals(expectedKeys, actualKeys); @@ -1394,7 +1317,7 @@ private static void assertKeySequenceEqual(SearchPagedIterable results, List> createHotelsList() { List> documents = new ArrayList<>(); for (int i = 1; i <= 3000; i++) { - Map doc = new HashMap<>(); + Map doc = new LinkedHashMap<>(); doc.put("HotelId", Integer.toString(i)); doc.put("HotelName", "Hotel" + i); @@ -1412,41 +1335,38 @@ static List> createHotelsList() { 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()); + static void assertRangeFacets(List baseRateFacets, List lastRenovationDateFacets) { + assertNull(getFrom(baseRateFacets.get(0))); + assertEquals(5.0, getTo(baseRateFacets.get(0))); + assertEquals(5.0, getFrom(baseRateFacets.get(1))); + assertEquals(8.0, getTo(baseRateFacets.get(1))); + assertEquals(8.0, getFrom(baseRateFacets.get(2))); + assertEquals(10.0, getTo(baseRateFacets.get(2))); + assertEquals(10.0, getFrom(baseRateFacets.get(3))); + assertNull(getTo(baseRateFacets.get(3))); 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()); + assertNull(getFrom(lastRenovationDateFacets.get(0))); + assertEquals("2000-01-01T00:00:00.000+0000", getTo(lastRenovationDateFacets.get(0))); + assertEquals("2000-01-01T00:00:00.000+0000", getFrom(lastRenovationDateFacets.get(1))); + assertNull(getTo(lastRenovationDateFacets.get(1))); 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 getRangeFacetsForField(Map> facets, String expectedField, + int expectedCount) { + return getFacetsForField(facets, expectedField, expectedCount); } - static List> getValueFacetsForField(Map> facets, - String expectedField, int expectedCount) { - List facetCollection = getFacetsForField(facets, expectedField, expectedCount); - return facetCollection.stream().map(ValueFacetResult::new).collect(Collectors.toList()); + static List getValueFacetsForField(Map> facets, String expectedField, + int expectedCount) { + return getFacetsForField(facets, expectedField, expectedCount); } private static List getFacetsForField(Map> facets, String expectedField, @@ -1457,30 +1377,29 @@ private static List getFacetsForField(Map return results; } - static void assertContainHotelIds(List> expected, List actual) { + static void assertContainHotelIds(List> expected, IterableStream actual) { assertNotNull(actual); Set actualKeys = actual.stream() - .filter(item -> item.getDocument(SearchDocument.class).containsKey("HotelId")) - .map(item -> (String) item.getDocument(SearchDocument.class).get("HotelId")) + .map(item -> (String) item.getAdditionalProperties().get("HotelId")) + .filter(Objects::nonNull) .collect(Collectors.toSet()); Set expectedKeys = expected.stream() - .filter(item -> item.containsKey("HotelId")) .map(item -> (String) item.get("HotelId")) + .filter(Objects::nonNull) .collect(Collectors.toSet()); assertEquals(expectedKeys, actualKeys); } - static void assertValueFacetsEqual(List> actualFacets, - ArrayList> expectedFacets) { + static void assertValueFacetsEqual(List actualFacets, List 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()); + assertEquals(getValue(expectedFacets.get(i)), getValue(actualFacets.get(i))); } } static String getSearchResultId(SearchResult searchResult) { - return searchResult.getDocument(SearchDocument.class).get("HotelId").toString(); + return searchResult.getAdditionalProperties().get("HotelId").toString(); } static SearchOptions getSearchOptionsForRangeFacets() { @@ -1493,30 +1412,30 @@ static SearchOptions getSearchOptionsForValueFacets() { "LastRenovationDate,interval:year", "Rooms/BaseRate,sort:value", "Tags,sort:value"); } - static void assertListEqualHotelIds(List expected, List actual) { + static void assertListEqualHotelIds(List expected, IterableStream actual) { assertNotNull(actual); List actualKeys = actual.stream() - .filter(item -> item.getDocument(SearchDocument.class).containsKey("HotelId")) - .map(item -> (String) item.getDocument(SearchDocument.class).get("HotelId")) + .map(item -> (String) item.getAdditionalProperties().get("HotelId")) + .filter(Objects::nonNull) .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))))); + SearchIndex index = new SearchIndex(testResourceNamer.randomName("non-nullable-index", 64), + new SearchField("Key", SearchFieldDataType.STRING).setRetrievable(true).setKey(true), + new SearchField("Rating", SearchFieldDataType.INT32).setRetrievable(true), + new SearchField("Count", SearchFieldDataType.INT64).setRetrievable(true), + new SearchField("IsEnabled", SearchFieldDataType.BOOLEAN).setRetrievable(true), + new SearchField("Ratio", SearchFieldDataType.DOUBLE).setRetrievable(true), + new SearchField("StartDate", SearchFieldDataType.DATE_TIME_OFFSET).setRetrievable(true), + new SearchField("EndDate", SearchFieldDataType.DATE_TIME_OFFSET).setRetrievable(true), + new SearchField("TopLevelBucket", SearchFieldDataType.COMPLEX).setFields( + new SearchField("BucketName", SearchFieldDataType.STRING).setFilterable(true), + new SearchField("Count", SearchFieldDataType.INT32).setFilterable(true)), + new SearchField("Buckets", SearchFieldDataType.collection(SearchFieldDataType.COMPLEX)).setFields( + new SearchField("BucketName", SearchFieldDataType.STRING).setFilterable(true), + new SearchField("Count", SearchFieldDataType.INT32).setFilterable(true))); setupIndex(index); @@ -1524,42 +1443,42 @@ String createIndexWithNonNullableTypes() { } 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))))); + SearchIndex index = new SearchIndex(testResourceNamer.randomName("testindex", 64), + new SearchField("Key", SearchFieldDataType.STRING).setKey(true).setSearchable(true), + new SearchField("IntValue", SearchFieldDataType.INT32).setFilterable(true), + new SearchField("Bucket", SearchFieldDataType.COMPLEX).setFields( + 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(); + static List> createDocsListWithValueTypes(String keySuffix) { + Map element1 = new LinkedHashMap<>(); element1.put("Key", "123" + keySuffix); element1.put("IntValue", 0); - Map subElement1 = new HashMap<>(); + Map subElement1 = new LinkedHashMap<>(); subElement1.put("BucketName", "A"); subElement1.put("Count", 3); element1.put("Bucket", subElement1); - SearchDocument element2 = new SearchDocument(); + Map element2 = new LinkedHashMap<>(); element2.put("Key", "456" + keySuffix); element2.put("IntValue", 7); - Map subElement2 = new HashMap<>(); + Map subElement2 = new LinkedHashMap<>(); subElement2.put("BucketName", "B"); subElement2.put("Count", 5); element2.put("Bucket", subElement2); - SearchDocument element3 = new SearchDocument(); + Map element3 = new LinkedHashMap<>(); element3.put("Key", "789" + keySuffix); element3.put("IntValue", 1); - Map subElement3 = new HashMap<>(); + Map subElement3 = new LinkedHashMap<>(); subElement3.put("BucketName", "B"); subElement3.put("Count", 99); element3.put("Bucket", subElement3); @@ -1569,43 +1488,70 @@ static List createDocsListWithValueTypes(String keySuffix) { private static void canSearchWithValueFacetsValidateResponse(SearchPagedResponse result, List> expectedHotels, Map> facets) { - assertContainHotelIds(expectedHotels, result.getValue()); + assertContainHotelIds(expectedHotels, result.getElements()); assertValueFacetsEqual(getValueFacetsForField(facets, "Rating", 2), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(1L, 5), new ValueFacetResult<>(4L, 4)))); + Arrays.asList(createValueFacet(1L, 5), createValueFacet(4L, 4))); assertValueFacetsEqual(getValueFacetsForField(facets, "SmokingAllowed", 2), - new ArrayList<>(Arrays.asList(new ValueFacetResult<>(4L, false), new ValueFacetResult<>(2L, true)))); + Arrays.asList(createValueFacet(4L, false), createValueFacet(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, "Category", 3), Arrays + .asList(createValueFacet(5L, "Budget"), createValueFacet(1L, "Boutique"), createValueFacet(1L, "Luxury"))); assertValueFacetsEqual(getValueFacetsForField(facets, "LastRenovationDate", 6), - new ArrayList<>(Arrays.asList( - new ValueFacetResult<>(1L, + Arrays.asList( + createValueFacet(1L, OffsetDateTime.parse("1970-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, + createValueFacet(1L, OffsetDateTime.parse("1982-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(2L, + createValueFacet(2L, OffsetDateTime.parse("1995-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, + createValueFacet(1L, OffsetDateTime.parse("1999-01-01T00:00:00Z").format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)), - new ValueFacetResult<>(1L, + createValueFacet(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))))); + createValueFacet(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)))); + Arrays.asList(createValueFacet(1L, 2.44), createValueFacet(1L, 7.69), createValueFacet(1L, 8.09), + createValueFacet(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")))); + Arrays.asList(createValueFacet(1L, "24-hour front desk service"), createValueFacet(1L, "air conditioning"), + createValueFacet(4L, "budget"), createValueFacet(1L, "coffee in lobby"), + createValueFacet(2L, "concierge"), createValueFacet(1L, "motel"), createValueFacet(2L, "pool"), + createValueFacet(1L, "restaurant"), createValueFacet(1L, "view"), createValueFacet(4L, "wifi"))); + } + + private static FacetResult createValueFacet(long count, Object value) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeStartObject() + .writeLongField("count", count) + .writeNullableField("value", value, JsonWriter::writeUntyped) + .writeEndObject(); + } + + try (JsonReader jsonReader = JsonProviders.createReader(outputStream.toByteArray())) { + return FacetResult.fromJson(jsonReader); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + private static Object getFrom(FacetResult facetResult) { + return facetResult.getAdditionalProperties().get("from"); + } + + private static Object getTo(FacetResult facetResult) { + return facetResult.getAdditionalProperties().get("to"); + } + + private static Object getValue(FacetResult facetResult) { + return facetResult.getAdditionalProperties().get("value"); } } 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 ef6ae0d4317a..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(SELECT_STAR, ensuredSuggestOptions.getSelect()); - } - - @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 index 3f132fc6d413..44d53ac3acd6 100644 --- 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 @@ -3,19 +3,13 @@ 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.core.test.TestProxyTestBase; 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 com.azure.search.documents.models.*; +import com.azure.search.documents.testingmodels.Author; +import com.azure.search.documents.testingmodels.Book; +import com.azure.search.documents.testingmodels.Hotel; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -25,23 +19,11 @@ 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.*; 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; +import static com.azure.search.documents.TestHelpers.*; +import static org.junit.jupiter.api.Assertions.*; @Execution(ExecutionMode.CONCURRENT) public class SuggestTests extends SearchTestBase { @@ -75,7 +57,10 @@ public static void setupClass() { doc2.title("War and Peace"); doc2.publishDate(OffsetDateTime.parse("2015-08-18T00:00:00Z")); - searchIndexClient.getSearchClient(BOOKS_INDEX_NAME).uploadDocuments(Arrays.asList(doc1, doc2)); + searchIndexClient.getSearchClient(BOOKS_INDEX_NAME) + .indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(doc1)), + createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(doc2)))); waitForIndexing(); } @@ -98,23 +83,17 @@ private SearchAsyncClient getAsyncClient(String indexName) { @Test public void canSuggestDynamicDocumentsSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("more", "sg").setOrderBy("HotelId"); - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); - - Iterator suggestResultIterator - = client.suggest("more", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifyDynamicDocumentSuggest(suggestResultIterator.next()); - assertFalse(suggestResultIterator.hasNext()); + verifyDynamicDocumentSuggest(client.suggest(suggestOptions)); } @Test public void canSuggestDynamicDocumentsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("more", "sg").setOrderBy("HotelId"); - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); - - StepVerifier.create(asyncClient.suggest("more", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(SuggestTests::verifyDynamicDocumentSuggest) .verifyComplete(); } @@ -122,23 +101,17 @@ public void canSuggestDynamicDocumentsAsync() { @Test public void searchFieldsExcludesFieldsFromSuggestSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("luxury", "sg").setSearchFields("HotelName"); - SuggestOptions suggestOptions = new SuggestOptions().setSearchFields("HotelName"); - - Iterator suggestResultIterator - = client.suggest("luxury", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifySuggestionCount(suggestResultIterator.next(), 0); - assertFalse(suggestResultIterator.hasNext()); + verifySuggestionCount(client.suggest(suggestOptions), 0); } @Test public void searchFieldsExcludesFieldsFromSuggestAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("luxury", "sg").setSearchFields("HotelName"); - SuggestOptions suggestOptions = new SuggestOptions().setSearchFields("HotelName"); - - StepVerifier.create(asyncClient.suggest("luxury", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(response -> verifySuggestionCount(response, 0)) .verifyComplete(); } @@ -146,29 +119,23 @@ public void searchFieldsExcludesFieldsFromSuggestAsync() { @Test public void canUseSuggestHitHighlightingSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setHighlightPreTag("") + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").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()); + verifyHitHighlightingSuggest(client.suggest(suggestOptions)); } @Test public void canUseSuggestHitHighlightingAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - - SuggestOptions suggestOptions = new SuggestOptions().setHighlightPreTag("") + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setHighlightPreTag("") .setHighlightPostTag("") .setFilter("Category eq 'Luxury'") .setTop(1); - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(SuggestTests::verifyHitHighlightingSuggest) .verifyComplete(); } @@ -176,23 +143,17 @@ public void canUseSuggestHitHighlightingAsync() { @Test public void canGetFuzzySuggestionsSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hitel", "sg").setUseFuzzyMatching(true); - SuggestOptions suggestOptions = new SuggestOptions().setUseFuzzyMatching(true); - - Iterator suggestResultIterator - = client.suggest("hitel", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - verifySuggestionCount(suggestResultIterator.next(), 5); - assertFalse(suggestResultIterator.hasNext()); + verifySuggestionCount(client.suggest(suggestOptions), 5); } @Test public void canGetFuzzySuggestionsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hitel", "sg").setUseFuzzyMatching(true); - SuggestOptions suggestOptions = new SuggestOptions().setUseFuzzyMatching(true); - - StepVerifier.create(asyncClient.suggest("hitel", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(response -> verifySuggestionCount(response, 5)) .verifyComplete(); } @@ -200,29 +161,19 @@ public void canGetFuzzySuggestionsAsync() { @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(); + SuggestOptions suggestOptions = new SuggestOptions("more", "sg").setOrderBy("HotelId"); - //assert - verifyCanSuggestStaticallyTypedDocuments(suggestResultIterator.next(), hotels); + verifyCanSuggestStaticallyTypedDocuments(client.suggest(suggestOptions), hotels); } @Test public void canSuggestStaticallyTypedDocumentsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - List> hotels = readJsonFileToList(HOTELS_DATA_JSON); - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId"); + SuggestOptions suggestOptions = new SuggestOptions("more", "sg").setOrderBy("HotelId"); - //act - StepVerifier.create(asyncClient.suggest("more", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(response -> verifyCanSuggestStaticallyTypedDocuments(response, hotels)) .verifyComplete(); } @@ -230,24 +181,17 @@ public void canSuggestStaticallyTypedDocumentsAsync() { @Test public void canSuggestWithDateTimeInStaticModelSync() { SearchClient client = getClient(BOOKS_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("War", "sg").setSelect("ISBN", "Title", "PublishDate"); - SuggestOptions suggestOptions = new SuggestOptions(); - suggestOptions.setSelect("ISBN", "Title", "PublishDate"); - Iterator suggestResultIterator - = client.suggest("War", "sg", suggestOptions, Context.NONE).iterableByPage().iterator(); - - //assert - verifyCanSuggestWithDateTimeInStaticModel(suggestResultIterator.next()); + verifyCanSuggestWithDateTimeInStaticModel(client.suggest(suggestOptions)); } @Test public void canSuggestWithDateTimeInStaticModelAsync() { SearchAsyncClient asyncClient = getAsyncClient(BOOKS_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("War", "sg").setSelect("ISBN", "Title", "PublishDate"); - SuggestOptions suggestOptions = new SuggestOptions(); - suggestOptions.setSelect("ISBN", "Title", "PublishDate"); - - StepVerifier.create(asyncClient.suggest("War", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(SuggestTests::verifyCanSuggestWithDateTimeInStaticModel) .verifyComplete(); } @@ -256,26 +200,14 @@ public void canSuggestWithDateTimeInStaticModelAsync() { 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); + verifySuggestionCount(client.suggest(new SuggestOptions("hitel", "sg")), 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()) + StepVerifier.create(asyncClient.suggest(new SuggestOptions("hitel", "sg"))) .assertNext(response -> verifySuggestionCount(response, 0)) .verifyComplete(); } @@ -284,11 +216,8 @@ public void fuzzyIsOffByDefaultAsync() { 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()); + HttpResponseException ex = assertThrows(HttpResponseException.class, + () -> client.suggest(new SuggestOptions("Hotel", "Suggester does not exist"))); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); } @@ -296,8 +225,7 @@ public void suggestThrowsWhenGivenBadSuggesterNameSync() { public void suggestThrowsWhenGivenBadSuggesterNameAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); - StepVerifier.create(asyncClient.suggest("Hotel", "Suggester does not exist", new SuggestOptions()).byPage()) - .thenRequest(1) + StepVerifier.create(asyncClient.suggest(new SuggestOptions("Hotel", "Suggester does not exist"))) .verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); @@ -307,53 +235,39 @@ public void suggestThrowsWhenGivenBadSuggesterNameAsync() { @Test public void suggestThrowsWhenRequestIsMalformedSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setOrderBy("This is not a valid orderby."); - 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()); + HttpResponseException ex = assertThrows(HttpResponseException.class, () -> client.suggest(suggestOptions)); assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); } @Test public void suggestThrowsWhenRequestIsMalformedAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setOrderBy("This is not a valid orderby."); - 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()); - }); + StepVerifier.create(asyncClient.suggest(suggestOptions)).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); + SuggestOptions suggestOptions + = new SuggestOptions("luxury", "sg").setOrderBy("HotelId").setMinimumCoverage(50.0); - //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); + verifyMinimumCoverage(client.suggest(suggestOptions)); } @Test public void testCanSuggestWithMinimumCoverageAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions + = new SuggestOptions("luxury", "sg").setOrderBy("HotelId").setMinimumCoverage(50.0); - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId").setMinimumCoverage(50.0); - - //act - StepVerifier.create(asyncClient.suggest("luxury", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(SuggestTests::verifyMinimumCoverage) .verifyComplete(); } @@ -361,27 +275,17 @@ public void testCanSuggestWithMinimumCoverageAsync() { @Test public void testTopTrimsResultsSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setOrderBy("HotelId").setTop(3); - //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); + verifyTopDocumentSuggest(client.suggest(suggestOptions)); } @Test public void testTopTrimsResultsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setOrderBy("HotelId").setTop(3); - //arrange - SuggestOptions suggestOptions = new SuggestOptions().setOrderBy("HotelId").setTop(3); - - //act - StepVerifier.create(asyncClient.suggest("hotel", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(SuggestTests::verifyTopDocumentSuggest) .verifyComplete(); } @@ -389,89 +293,70 @@ public void testTopTrimsResultsAsync() { @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") + = new SuggestOptions("hotel", "sg").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() + List actualIds = client.suggest(suggestOptions) + .getResults() .stream() - .map(s -> (String) s.getDocument(SearchDocument.class).get("HotelId")) + .map(s -> (String) s.getAdditionalProperties().get("HotelId")) .collect(Collectors.toList()); - List expectedIds = Arrays.asList("1", "5"); - assertEquals(expectedIds, actualIds); + assertEquals(Arrays.asList("1", "5"), 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") + = new SuggestOptions("hotel", "sg").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() + StepVerifier.create(asyncClient.suggest(suggestOptions)).assertNext(response -> { + List actualIds = response.getResults() .stream() - .map(sr -> sr.getDocument(SearchDocument.class).get("HotelId").toString()) + .map(sr -> sr.getAdditionalProperties().get("HotelId").toString()) .collect(Collectors.toList()); - - assertEquals(expectedIds, actualIds); + assertEquals(Arrays.asList("1", "5"), actualIds); }).verifyComplete(); } @Test public void testOrderByProgressivelyBreaksTiesSync() { SearchClient client = getClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setOrderBy("Rating desc", + "LastRenovationDate asc", "geo.distance(Location, geography'POINT(-122.0 49.0)')"); - 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() + List actualIds = client.suggest(suggestOptions) + .getResults() .stream() - .map(s -> (String) s.getDocument(SearchDocument.class).get("HotelId")) + .map(s -> (String) s.getAdditionalProperties().get("HotelId")) .collect(Collectors.toList()); - List expectedIds = Arrays.asList("1", "9", "4", "3", "5"); - assertEquals(expectedIds, actualIds); + assertEquals(Arrays.asList("1", "9", "4", "3", "5"), actualIds); } @Test public void testOrderByProgressivelyBreaksTiesAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); + SuggestOptions suggestOptions = new SuggestOptions("hotel", "sg").setOrderBy("Rating desc", + "LastRenovationDate asc", "geo.distance(Location, geography'POINT(-122.0 49.0)')"); - 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() + StepVerifier.create(asyncClient.suggest(suggestOptions)).assertNext(response -> { + List actualIds = response.getResults() .stream() - .map(sr -> sr.getDocument(SearchDocument.class).get("HotelId").toString()) + .map(sr -> sr.getAdditionalProperties().get("HotelId").toString()) .collect(Collectors.toList()); - - assertEquals(expectedIds, actualIds); + assertEquals(Arrays.asList("1", "9", "4", "3", "5"), 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); + = new SuggestOptions("secret", "sg").setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - verifySuggestWithSelectedFields(suggestResult.iterableByPage().iterator().next()); + verifySuggestWithSelectedFields(client.suggest(suggestOptions)); } @Test @@ -479,44 +364,44 @@ public void testCanSuggestWithSelectedFieldsAsync() { SearchAsyncClient asyncClient = getAsyncClient(HOTEL_INDEX_NAME); SuggestOptions suggestOptions - = new SuggestOptions().setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); + = new SuggestOptions("secret", "sg").setSelect("HotelName", "Rating", "Address/City", "Rooms/Type"); - StepVerifier.create(asyncClient.suggest("secret", "sg", suggestOptions).byPage()) + StepVerifier.create(asyncClient.suggest(suggestOptions)) .assertNext(SuggestTests::verifySuggestWithSelectedFields) .verifyComplete(); } - static void verifySuggestionCount(SuggestPagedResponse response, int count) { + static void verifySuggestionCount(SuggestDocumentsResult response, int count) { assertNotNull(response); - assertEquals(count, response.getValue().size()); + assertEquals(count, response.getResults().size()); } - static void verifyHitHighlightingSuggest(SuggestPagedResponse suggestResultPagedResponse) { + static void verifyHitHighlightingSuggest(SuggestDocumentsResult suggestResultPagedResponse) { assertNotNull(suggestResultPagedResponse); - assertEquals(1, suggestResultPagedResponse.getValue().size()); - assertTrue(suggestResultPagedResponse.getValue().get(0).getText().startsWith("Best hotel in town")); + assertEquals(1, suggestResultPagedResponse.getResults().size()); + assertTrue(suggestResultPagedResponse.getResults().get(0).getText().startsWith("Best hotel in town")); } - static void verifyDynamicDocumentSuggest(SuggestPagedResponse suggestResultPagedResponse) { + static void verifyDynamicDocumentSuggest(SuggestDocumentsResult suggestResultPagedResponse) { assertNotNull(suggestResultPagedResponse); - assertEquals(2, suggestResultPagedResponse.getValue().size()); - Hotel hotel = suggestResultPagedResponse.getValue().get(0).getDocument(Hotel.class); + assertEquals(2, suggestResultPagedResponse.getResults().size()); + Hotel hotel = convertFromMapStringObject( + suggestResultPagedResponse.getResults().get(0).getAdditionalProperties(), Hotel::fromJson); assertEquals("10", hotel.hotelId()); } - static void verifyCanSuggestStaticallyTypedDocuments(SuggestPagedResponse suggestResultPagedResponse, + static void verifyCanSuggestStaticallyTypedDocuments(SuggestDocumentsResult suggestResultPagedResponse, List> expectedHotels) { //sanity assertNotNull(suggestResultPagedResponse); - List docs = suggestResultPagedResponse.getValue() + List> docs = suggestResultPagedResponse.getResults() .stream() - .map(suggestResult -> suggestResult.getDocument(SearchDocument.class)) + .map(SuggestResult::getAdditionalProperties) .collect(Collectors.toList()); - List hotelsList = suggestResultPagedResponse.getValue(); + List hotelsList = suggestResultPagedResponse.getResults(); - List expectedHotelsList = expectedHotels.stream() - .map(SearchDocument::new) - .filter(h -> h.get("HotelId").equals("10") || h.get("HotelId").equals("8")) + List> expectedHotelsList = expectedHotels.stream() + .filter(h -> "10".equals(h.get("HotelId")) || "8".equals(h.get("HotelId"))) .sorted(Comparator.comparing(h -> h.get("HotelId").toString())) .collect(Collectors.toList()); @@ -527,33 +412,33 @@ static void verifyCanSuggestStaticallyTypedDocuments(SuggestPagedResponse sugges expectedHotelsList.stream().map(hotel -> hotel.get("Description")).collect(Collectors.toList())); } - static void verifyMinimumCoverage(SuggestPagedResponse suggestResultPagedResponse) { + static void verifyMinimumCoverage(SuggestDocumentsResult suggestResultPagedResponse) { assertNotNull(suggestResultPagedResponse); - assertEquals(Double.valueOf(100.0), suggestResultPagedResponse.getCoverage()); + assertEquals(100.0D, suggestResultPagedResponse.getCoverage()); } - static void verifyTopDocumentSuggest(SuggestPagedResponse suggestResultPagedResponse) { + static void verifyTopDocumentSuggest(SuggestDocumentsResult suggestResultPagedResponse) { assertNotNull(suggestResultPagedResponse); - assertEquals(3, suggestResultPagedResponse.getValue().size()); - List resultIds = suggestResultPagedResponse.getValue() + assertEquals(3, suggestResultPagedResponse.getResults().size()); + List resultIds = suggestResultPagedResponse.getResults() .stream() - .map(hotel -> hotel.getDocument(Hotel.class).hotelId()) + .map(hotel -> convertFromMapStringObject(hotel.getAdditionalProperties(), Hotel::fromJson).hotelId()) .collect(Collectors.toList()); assertEquals(Arrays.asList("1", "10", "2"), resultIds); } - static void verifyCanSuggestWithDateTimeInStaticModel(SuggestPagedResponse suggestResultPagedResponse) { - List books = suggestResultPagedResponse.getValue(); + static void verifyCanSuggestWithDateTimeInStaticModel(SuggestDocumentsResult suggestResultPagedResponse) { + List books = suggestResultPagedResponse.getResults(); 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); + static void verifySuggestWithSelectedFields(SuggestDocumentsResult suggestResultPagedResponse) { + assertEquals(1, suggestResultPagedResponse.getResults().size()); + Map result = suggestResultPagedResponse.getResults().get(0).getAdditionalProperties(); assertEquals("Secret Point Motel", result.get("HotelName")); assertEquals(4, ((Number) result.get("Rating")).intValue()); 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 index 01bf71e6124c..6a3866d3242d 100644 --- 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 @@ -6,9 +6,11 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpPipeline; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.test.TestMode; import com.azure.core.test.http.AssertingHttpClientBuilder; import com.azure.core.test.utils.MockTokenCredential; @@ -17,7 +19,6 @@ 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.AzureCliCredentialBuilder; import com.azure.identity.AzurePipelinesCredential; import com.azure.identity.AzurePipelinesCredentialBuilder; @@ -26,10 +27,13 @@ import com.azure.json.JsonReader; import com.azure.json.JsonSerializable; import com.azure.json.JsonWriter; +import com.azure.json.ReadValueCallback; 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 com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -40,7 +44,6 @@ 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; @@ -49,15 +52,16 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; +import java.util.stream.Collectors; import static com.azure.search.documents.SearchTestBase.SEARCH_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.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; -import static org.junit.jupiter.api.Assertions.fail; /** * This class contains helper methods for running Azure AI Search tests. @@ -72,7 +76,6 @@ public final class TestHelpers { 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<>(); @@ -158,31 +161,6 @@ private static byte[] serializeJsonSerializable(JsonSerializable jsonSerializ } } - /** - * 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. * @@ -277,24 +255,22 @@ private static boolean shouldSkipField(String fieldName, Object value, boolean i return false; } + public static void assertHttpResponseException(Runnable exceptionThrower, int statusCode) { + assertHttpResponseException(exceptionThrower, statusCode, null); + } + public static void assertHttpResponseException(Runnable exceptionThrower, int statusCode, String expectedMessage) { - try { - exceptionThrower.run(); - fail(); - } catch (Throwable ex) { - verifyHttpResponseError(ex, statusCode, expectedMessage); - } + Throwable ex = assertThrows(Throwable.class, exceptionThrower::run); + verifyHttpResponseError(ex, statusCode, expectedMessage); } - public static void verifyHttpResponseError(Throwable ex, int statusCode, String expectedMessage) { - if (ex instanceof HttpResponseException) { - assertEquals(statusCode, ((HttpResponseException) ex).getResponse().getStatusCode()); + public static void verifyHttpResponseError(Throwable throwable, int statusCode, String expectedMessage) { + HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable, + "Expected exception to be instanceof HttpResponseException"); + assertEquals(statusCode, ex.getResponse().getStatusCode()); - if (expectedMessage != null) { - assertTrue(ex.getMessage().contains(expectedMessage)); - } - } else { - fail("Expected exception to be instanceof HttpResponseException", ex); + if (expectedMessage != null) { + assertTrue(throwable.getMessage().contains(expectedMessage)); } } @@ -324,36 +300,86 @@ static TestMode setupTestMode() { } } - public static void uploadDocuments(SearchClient client, List uploadDoc) { - client.uploadDocuments(uploadDoc); + public static void uploadDocuments(SearchClient client, List> uploadDoc) { + uploadDocumentsRaw(client, + uploadDoc.stream().map(TestHelpers::convertToMapStringObject).collect(Collectors.toList())); + waitForIndexing(); + } + + public static void uploadDocuments(SearchAsyncClient client, List> uploadDoc) { + uploadDocumentsRaw(client, + uploadDoc.stream().map(TestHelpers::convertToMapStringObject).collect(Collectors.toList())); + waitForIndexing(); + } + + public static void uploadDocument(SearchClient client, JsonSerializable uploadDoc) { + uploadDocumentRaw(client, convertToMapStringObject(uploadDoc)); waitForIndexing(); } - public static void uploadDocuments(SearchAsyncClient client, List uploadDoc) { - client.uploadDocuments(uploadDoc).block(); + public static void uploadDocument(SearchAsyncClient client, JsonSerializable uploadDoc) { + uploadDocumentRaw(client, convertToMapStringObject(uploadDoc)); waitForIndexing(); } - public static void uploadDocument(SearchClient client, T uploadDoc) { - client.uploadDocuments(Collections.singletonList(uploadDoc)); + public static void uploadDocumentRaw(SearchClient client, Map document) { + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, document))); waitForIndexing(); } - public static void uploadDocument(SearchAsyncClient client, T uploadDoc) { - client.uploadDocuments(Collections.singletonList(uploadDoc)).block(); + public static void uploadDocumentRaw(SearchAsyncClient client, Map document) { + client.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, document))).block(); waitForIndexing(); } + public static void uploadDocumentsRaw(SearchClient client, List> documents) { + client.indexDocuments(new IndexDocumentsBatch(documents.stream() + .map(doc -> createIndexAction(IndexActionType.UPLOAD, doc)) + .collect(Collectors.toList()))); + waitForIndexing(); + } + + public static void uploadDocumentsRaw(SearchAsyncClient client, List> documents) { + client.indexDocuments(new IndexDocumentsBatch( + documents.stream().map(doc -> createIndexAction(IndexActionType.UPLOAD, doc)).collect(Collectors.toList()))) + .block(); + waitForIndexing(); + } + + public static Map convertToMapStringObject(JsonSerializable pojo) { + try (JsonReader jsonReader = JsonProviders.createReader(pojo.toJsonBytes())) { + return jsonReader.readMap(JsonReader::readUntyped); + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + + public static T convertFromMapStringObject(Map additionalProperties, + ReadValueCallback converter) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeMap(additionalProperties, JsonWriter::writeUntyped); + } + + try (JsonReader jsonReader = JsonProviders.createReader(outputStream.toByteArray())) { + return converter.read(jsonReader); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } + } + public static List> uploadDocumentsJson(SearchClient client, String dataJson) { List> documents = readJsonFileToList(dataJson); - uploadDocuments(client, documents); + uploadDocumentsRaw(client, documents); return documents; } public static List> uploadDocumentsJson(SearchAsyncClient client, String dataJson) { List> documents = readJsonFileToList(dataJson); - uploadDocuments(client, documents); + uploadDocumentsRaw(client, documents); return documents; } @@ -374,18 +400,6 @@ public static List> readJsonFileToList(String filename) { } } - 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); @@ -396,7 +410,7 @@ public static SearchIndexClient setupSharedIndex(String indexName, String indexD .retryPolicy(SERVICE_THROTTLE_SAFE_RETRY_POLICY) .buildClient(); - searchIndexClient.createOrUpdateIndex(createTestIndex(indexName, baseIndex)); + searchIndexClient.createIndex(createTestIndex(indexName, baseIndex)); if (indexData != null) { uploadDocumentsJson(searchIndexClient.getSearchClient(indexName), indexData); @@ -456,8 +470,7 @@ private static TokenCredential tryGetPipelineCredential() { } static SearchIndex createTestIndex(String testIndexName, SearchIndex baseIndex) { - return new SearchIndex(testIndexName).setFields(baseIndex.getFields()) - .setScoringProfiles(baseIndex.getScoringProfiles()) + return new SearchIndex(testIndexName, baseIndex.getFields()).setScoringProfiles(baseIndex.getScoringProfiles()) .setDefaultScoringProfile(baseIndex.getDefaultScoringProfile()) .setCorsOptions(baseIndex.getCorsOptions()) .setSuggesters(baseIndex.getSuggesters()) @@ -472,7 +485,7 @@ static SearchIndex createTestIndex(String testIndexName, SearchIndex baseIndex) } public static HttpClient buildSyncAssertingClient(HttpClient httpClient) { - return new AssertingHttpClientBuilder(httpClient).skipRequest((httpRequest, context) -> false) + return new AssertingHttpClientBuilder(httpClient).skipRequest((ignoredRequest, ignoredContext) -> false) .assertSync() .build(); } @@ -485,28 +498,10 @@ public static SearchIndexClient createSharedSearchIndexClient() { .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(); + URI fileUri = AutocompleteTests.class.getClassLoader().getResource(fName).toURI(); return Files.readAllBytes(Paths.get(fileUri)); } catch (Exception ex) { @@ -514,4 +509,17 @@ static byte[] loadResource(String fileName) { } }); } + + public static IndexAction createIndexAction(IndexActionType actionType, Map additionalProperties) { + return new IndexAction().setActionType(actionType).setAdditionalProperties(additionalProperties); + } + + public static IndexAction convertToIndexAction(JsonSerializable pojo, IndexActionType actionType) { + return new IndexAction().setActionType(actionType).setAdditionalProperties(convertToMapStringObject(pojo)); + } + + public static RequestOptions ifMatch(String eTag) { + return new RequestOptions().setHeader(HttpHeaderName.IF_MATCH, eTag); + } + } 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/VectorSearchTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchTests.java index d5397d59e997..1fb4dd412380 100644 --- 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 @@ -17,6 +17,9 @@ import com.azure.search.documents.indexes.models.VectorSearch; import com.azure.search.documents.indexes.models.VectorSearchCompressionRescoreStorageMethod; import com.azure.search.documents.indexes.models.VectorSearchProfile; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; +import com.azure.search.documents.models.LookupDocument; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -25,9 +28,11 @@ import reactor.test.StepVerifier; import java.util.ArrayList; -import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import static com.azure.search.documents.TestHelpers.createIndexAction; import static com.azure.search.documents.TestHelpers.waitForIndexing; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -60,7 +65,7 @@ public void deleteIndexes() { public void updateExistingIndexToAddVectorFieldsAsync() { String indexName = randomIndexName("addvectorasync"); SearchIndex searchIndex - = new SearchIndex(indexName).setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), + = new SearchIndex(indexName, new SearchField("Id", SearchFieldDataType.STRING).setKey(true), new SearchField("Name", SearchFieldDataType.STRING).setSearchable(true).setFilterable(true)); SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); @@ -68,19 +73,20 @@ public void updateExistingIndexToAddVectorFieldsAsync() { indexesToDelete.add(indexName); // Upload data - SearchDocument document = new SearchDocument(); + Map document = new LinkedHashMap<>(); document.put("Id", "1"); document.put("Name", "Countryside Hotel"); SearchAsyncClient searchClient = searchIndexClient.getSearchAsyncClient(indexName); - searchClient.uploadDocuments(Collections.singletonList(document)).block(); + searchClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, 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")); + StepVerifier.create(searchClient.getDocument("1")).assertNext(response -> { + assertEquals(document.get("Id"), response.getAdditionalProperties().get("Id")); + assertEquals(document.get("Name"), response.getAdditionalProperties().get("Name")); }).verifyComplete(); // Update created index to add vector field @@ -91,16 +97,15 @@ public void updateExistingIndexToAddVectorFieldsAsync() { SearchField vectorField = new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) .setSearchable(true) - .setHidden(false) + .setRetrievable(true) .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")))); + createdIndex.setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config"))); return searchIndexClient.createOrUpdateIndex(createdIndex); }); @@ -114,22 +119,20 @@ public void updateExistingIndexToAddVectorFieldsAsync() { // 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); - } - }); + Mono> getAndUpdateDocument = searchClient.getDocument("1").flatMap(resultDoc -> { + // Update document to add vector field data + resultDoc.getAdditionalProperties() + .put("DescriptionVector", VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION); + return searchClient.indexDocuments( + new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, resultDoc.getAdditionalProperties()))); + }).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) { + waitForIndexing(); + } + return searchClient.getDocument("1").map(LookupDocument::getAdditionalProperties); + }); // Get the document StepVerifier.create(getAndUpdateDocument).assertNext(response -> { @@ -145,24 +148,24 @@ public void updateExistingIndexToAddVectorFieldsAsync() { public void updateExistingIndexToAddVectorFieldsSync() { String indexName = randomIndexName("addvectorsync"); SearchIndex searchIndex - = new SearchIndex(indexName).setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), + = new SearchIndex(indexName, 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(); + Map document = new LinkedHashMap<>(); document.put("Id", "1"); document.put("Name", "Countryside Hotel"); SearchClient searchClient = searchIndexClient.getSearchClient(indexName); - searchClient.uploadDocuments(Collections.singletonList(document)); + searchClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, document))); waitForIndexing(); // Get the document - SearchDocument responseDocument = searchClient.getDocument("1", SearchDocument.class); + Map responseDocument = searchClient.getDocument("1").getAdditionalProperties(); assertEquals(document.get("Id"), responseDocument.get("Id")); assertEquals(document.get("Name"), responseDocument.get("Name")); @@ -176,15 +179,15 @@ public void updateExistingIndexToAddVectorFieldsSync() { SearchField vectorField = new SearchField("DescriptionVector", SearchFieldDataType.collection(SearchFieldDataType.SINGLE)) .setSearchable(true) - .setHidden(false) + .setRetrievable(true) .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")))); + createdIndex.setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config"))); // Update index SearchIndex responseIndex = searchIndexClient.createOrUpdateIndex(createdIndex); @@ -195,16 +198,16 @@ public void updateExistingIndexToAddVectorFieldsSync() { // Update document to add vector field's data // Get the document - SearchDocument resultDoc = searchClient.getDocument("1", SearchDocument.class); + Map resultDoc = searchClient.getDocument("1").getAdditionalProperties(); // Update document to add vector field data resultDoc.put("DescriptionVector", VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION); - searchClient.mergeDocuments(Collections.singletonList(resultDoc)); + searchClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.MERGE, resultDoc))); waitForIndexing(); // Get the document - responseDocument = searchClient.getDocument("1", SearchDocument.class); + responseDocument = searchClient.getDocument("1").getAdditionalProperties(); assertEquals(document.get("Id"), responseDocument.get("Id")); assertEquals(document.get("Name"), responseDocument.get("Name")); @@ -219,19 +222,18 @@ public void testVectorSearchCompressionTruncationDimensionSync() { String indexName = randomIndexName("compressiontruncationdimension"); String compressionName = "vector-compression-100"; - SearchIndex searchIndex = new SearchIndex(indexName) - .setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), + SearchIndex searchIndex + = new SearchIndex(indexName, 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) + .setRetrievable(true) .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))); + .setVectorSearchProfileName("my-vector-profile")).setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config")) + .setCompressions( + new BinaryQuantizationCompression(compressionName).setTruncationDimension(100))); SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); searchIndexClient.createIndex(searchIndex); @@ -252,19 +254,18 @@ public void testVectorSearchCompressionTruncationDimensionAsync() { String indexName = randomIndexName("compressiontruncationdimensionasync"); String compressionName = "vector-compression-100"; - SearchIndex searchIndex = new SearchIndex(indexName) - .setFields(new SearchField("Id", SearchFieldDataType.STRING).setKey(true), + SearchIndex searchIndex + = new SearchIndex(indexName, 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) + .setRetrievable(true) .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))); + .setVectorSearchProfileName("my-vector-profile")).setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config")) + .setCompressions( + new ScalarQuantizationCompression(compressionName).setTruncationDimension(100))); SearchIndexAsyncClient searchIndexAsyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); searchIndexAsyncClient.createIndex(searchIndex).block(); @@ -287,21 +288,16 @@ public void testVectorSearchCompressionBinaryQuantizationAsync() { 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))); + = new SearchIndex(indexName, 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) + .setRetrievable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("my-vector-profile")).setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config")) + .setCompressions(new BinaryQuantizationCompression(compressionName))); SearchIndexAsyncClient searchIndexAsyncClient = getSearchIndexClientBuilder(false).buildAsyncClient(); searchIndexAsyncClient.createIndex(searchIndex).block(); @@ -323,21 +319,16 @@ public void testVectorSearchCompressionBinaryQuantizationSync() { 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))); + = new SearchIndex(indexName, 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) + .setRetrievable(true) + .setVectorSearchDimensions(5) + .setVectorSearchProfileName("my-vector-profile")).setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config")) + .setCompressions(new BinaryQuantizationCompression(compressionName))); SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); searchIndexClient.createIndex(searchIndex); @@ -352,23 +343,21 @@ public void testVectorSearchCompressionBinaryQuantizationSync() { public void testVectorSearchCompressionsEnableRescoringDiscardOriginalsSync() { String indexName = randomIndexName("compressiontruncationdimension"); String compressionName = "vector-compression-100"; - RescoringOptions rescoringOptions = new RescoringOptions().setRescoringEnabled(true) + RescoringOptions rescoringOptions = new RescoringOptions().setEnableRescoring(true) .setRescoreStorageMethod(VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS); - 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) - .setRescoringOptions(rescoringOptions))); + SearchIndex searchIndex = new SearchIndex(indexName, + 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) + .setRetrievable(true) + .setVectorSearchDimensions(1536) + .setVectorSearchProfileName("my-vector-profile")).setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config")) + .setCompressions(new BinaryQuantizationCompression(compressionName).setTruncationDimension(100) + .setRescoringOptions(rescoringOptions))); SearchIndexClient searchIndexClient = getSearchIndexClientBuilder(true).buildClient(); searchIndexClient.createIndex(searchIndex); @@ -380,7 +369,7 @@ public void testVectorSearchCompressionsEnableRescoringDiscardOriginalsSync() { BinaryQuantizationCompression compression = (BinaryQuantizationCompression) retrievedIndex.getVectorSearch().getCompressions().get(0); assertEquals(compressionName, compression.getCompressionName()); - assertEquals(true, compression.getRescoringOptions().isRescoringEnabled()); + assertEquals(true, compression.getRescoringOptions().isEnableRescoring()); assertEquals(VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS, compression.getRescoringOptions().getRescoreStorageMethod()); } @@ -389,23 +378,21 @@ public void testVectorSearchCompressionsEnableRescoringDiscardOriginalsSync() { public void testVectorSearchCompressionsEnableRescoringDiscardOriginalsAsync() { String indexName = randomIndexName("compressiontruncationdimension"); String compressionName = "vector-compression-100"; - RescoringOptions rescoringOptions = new RescoringOptions().setRescoringEnabled(true) + RescoringOptions rescoringOptions = new RescoringOptions().setEnableRescoring(true) .setRescoreStorageMethod(VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS); - 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) - .setRescoringOptions(rescoringOptions))); + SearchIndex searchIndex = new SearchIndex(indexName, + 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) + .setRetrievable(true) + .setVectorSearchDimensions(1536) + .setVectorSearchProfileName("my-vector-profile")).setVectorSearch( + new VectorSearch().setProfiles(new VectorSearchProfile("my-vector-profile", "my-vector-config")) + .setAlgorithms(new HnswAlgorithmConfiguration("my-vector-config")) + .setCompressions(new BinaryQuantizationCompression(compressionName).setTruncationDimension(100) + .setRescoringOptions(rescoringOptions))); SearchIndexAsyncClient searchIndexClient = getSearchIndexClientBuilder(false).buildAsyncClient(); searchIndexClient.createIndex(searchIndex).block(); @@ -417,7 +404,7 @@ public void testVectorSearchCompressionsEnableRescoringDiscardOriginalsAsync() { BinaryQuantizationCompression compression = (BinaryQuantizationCompression) retrievedIndex.getVectorSearch().getCompressions().get(0); assertEquals(compressionName, compression.getCompressionName()); - assertEquals(true, compression.getRescoringOptions().isRescoringEnabled()); + assertEquals(true, compression.getRescoringOptions().isEnableRescoring()); assertEquals(VectorSearchCompressionRescoreStorageMethod.DISCARD_ORIGINALS, compression.getRescoringOptions().getRescoreStorageMethod()); }).verifyComplete(); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchWithSharedIndexTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchWithSharedIndexTests.java index eb51fe929639..1a58f0900cc6 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchWithSharedIndexTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/VectorSearchWithSharedIndexTests.java @@ -5,7 +5,6 @@ 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.indexes.SearchIndexClient; import com.azure.search.documents.indexes.SearchIndexClientBuilder; import com.azure.search.documents.indexes.models.DistanceScoringFunction; @@ -24,22 +23,20 @@ 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.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; 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.SearchPagedResponse; 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.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 com.azure.search.documents.testingmodels.HotelAddress; +import com.azure.search.documents.testingmodels.HotelRoom; +import com.azure.search.documents.testingmodels.VectorHotel; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -47,12 +44,13 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; +import static com.azure.search.documents.TestHelpers.convertToMapStringObject; +import static com.azure.search.documents.TestHelpers.createIndexAction; import static com.azure.search.documents.TestHelpers.waitForIndexing; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -80,7 +78,10 @@ public static void setupClass() { searchIndexClient.createIndex(getVectorIndex()); - searchIndexClient.getSearchClient(HOTEL_INDEX_NAME).uploadDocuments(VECTORIZED_HOTELS); + IndexDocumentsBatch batch = new IndexDocumentsBatch(VECTORIZED_HOTELS.stream() + .map(hotel -> createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(hotel))) + .collect(Collectors.toList())); + searchIndexClient.getSearchClient(HOTEL_INDEX_NAME).index(batch); waitForIndexing(); } @@ -102,42 +103,36 @@ protected static void cleanupClass() { public void singleVectorSearchAsync() { SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) - .setSelect("HotelId", "HotelName"); + SearchOptions searchOptions + = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()).setSelect("HotelId", "HotelName"); - StepVerifier.create(searchClient.search(null, searchOptions).collectList()) - .assertNext(results -> assertKeysEqual(results, - r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), "3", "5", "1")) + StepVerifier.create(searchClient.search(searchOptions).collectList()) + .assertNext(results -> assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), + "3", "5", "1")) .verifyComplete(); } @Test public void singleVectorSearchSync() { SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); + SearchOptions searchOptions + = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()).setSelect("HotelId", "HotelName"); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) - .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"), "3", "5", "1"); + List results = searchClient.search(searchOptions).stream().collect(Collectors.toList()); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "3", "5", "1"); } @Test public void singleVectorSearchWithFilterAsync() { SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) + SearchOptions searchOptions = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()) .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"), "3", "5", "4")) + StepVerifier.create(searchClient.search(searchOptions).collectList()) + .assertNext(results -> assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), + "3", "5", "4")) .verifyComplete(); } @@ -145,28 +140,25 @@ public void singleVectorSearchWithFilterAsync() { public void singleVectorSearchWithFilterSync() { SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) + SearchOptions searchOptions = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()) .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"), "3", "5", "4"); + List results = searchClient.search(searchOptions).stream().collect(Collectors.toList()); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "3", "5", "4"); } @Test public void simpleHybridSearchAsync() { SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) + SearchOptions searchOptions = new SearchOptions().setSearchText("Top hotels in town") + .setVectorQueries(createDescriptionVectorQuery()) .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"), "3", "1", "5", "2", "10", "4", "9")) + StepVerifier.create(searchClient.search(searchOptions).collectList()) + .assertNext(results -> assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), + "3", "1", "5", "2", "10", "4", "9")) .verifyComplete(); } @@ -174,16 +166,13 @@ public void simpleHybridSearchAsync() { public void simpleHybridSearchSync() { SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) + SearchOptions searchOptions = new SearchOptions().setSearchText("Top hotels in town") + .setVectorQueries(createDescriptionVectorQuery()) .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"), "3", "1", "5", "2", - "10", "4", "9"); + List results = searchClient.search(searchOptions).stream().collect(Collectors.toList()); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "3", "1", "5", "2", "10", + "4", "9"); } @Test @@ -191,39 +180,37 @@ public void semanticHybridSearchAsync() { SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) + .setSearchText( + "Is there any hotel located on the main commercial artery of the city in the heart of New York?") + .setVectorQueries(createDescriptionVectorQuery()) .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(page1.getSemanticResults().getQueryAnswers()); - assertEquals(1, page1.getSemanticResults().getQueryAnswers().size()); - assertEquals("9", page1.getSemanticResults().getQueryAnswers().get(0).getKey()); - assertNotNull(page1.getSemanticResults().getQueryAnswers().get(0).getHighlights()); - assertNotNull(page1.getSemanticResults().getQueryAnswers().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()); - } + .setSemanticConfigurationName("my-semantic-config") + .setCaptions(QueryCaptionType.EXTRACTIVE) + .setAnswers(QueryAnswerType.EXTRACTIVE); + + StepVerifier.create(searchClient.search(searchOptions).byPage().collectList()).assertNext(pages -> { + SearchPagedResponse page1 = pages.get(0); + assertNotNull(page1.getAnswers()); + assertEquals(1, page1.getAnswers().size()); + assertEquals("9", page1.getAnswers().get(0).getKey()); + assertNotNull(page1.getAnswers().get(0).getHighlights()); + assertNotNull(page1.getAnswers().get(0).getText()); + + List results = new ArrayList<>(); + for (SearchPagedResponse page : pages) { + for (SearchResult result : page.getElements()) { + results.add(result); + + assertNotNull(result.getCaptions()); + assertNotNull(result.getCaptions().get(0).getHighlights()); + assertNotNull(result.getCaptions().get(0).getText()); } + } - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), "9", "3", - "2", "5", "10", "1", "4"); - }).verifyComplete(); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "9", "3", "2", "5", "10", + "1", "4"); + }).verifyComplete(); } @Test @@ -231,39 +218,38 @@ public void semanticHybridSearchSync() { SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery())) + .setSearchText( + "Is there any hotel located on the main commercial artery of the city in the heart of New York?") + .setVectorQueries(createDescriptionVectorQuery()) .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))); + .setSemanticConfigurationName("my-semantic-config") + .setCaptions(QueryCaptionType.EXTRACTIVE) + .setAnswers(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()); + List pages + = searchClient.search(searchOptions).streamByPage().collect(Collectors.toList()); SearchPagedResponse page1 = pages.get(0); - assertNotNull(page1.getSemanticResults().getQueryAnswers()); - assertEquals(1, page1.getSemanticResults().getQueryAnswers().size()); - assertEquals("9", page1.getSemanticResults().getQueryAnswers().get(0).getKey()); - assertNotNull(page1.getSemanticResults().getQueryAnswers().get(0).getHighlights()); - assertNotNull(page1.getSemanticResults().getQueryAnswers().get(0).getText()); + assertNotNull(page1.getAnswers()); + assertEquals(1, page1.getAnswers().size()); + assertEquals("9", page1.getAnswers().get(0).getKey()); + assertNotNull(page1.getAnswers().get(0).getHighlights()); + assertNotNull(page1.getAnswers().get(0).getText()); List results = new ArrayList<>(); for (SearchPagedResponse page : pages) { - for (SearchResult result : page.getValue()) { + for (SearchResult result : page.getElements()) { results.add(result); - assertNotNull(result.getSemanticSearch().getQueryCaptions()); - assertNotNull(result.getSemanticSearch().getQueryCaptions().get(0).getHighlights()); - assertNotNull(result.getSemanticSearch().getQueryCaptions().get(0).getText()); + assertNotNull(result.getCaptions()); + assertNotNull(result.getCaptions().get(0).getHighlights()); + assertNotNull(result.getCaptions().get(0).getText()); } } - assertKeysEqual(results, r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), "9", "3", "2", "5", - "10", "1", "4"); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "9", "3", "2", "5", "10", + "1", "4"); } // a test that creates a hybrid search query with a vector search query and a regular search query, and utilizes the @@ -272,36 +258,35 @@ public void semanticHybridSearchSync() { public void hybridSearchWithVectorFilterOverrideSync() { // 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") + SearchOptions searchOptions = new SearchOptions().setSearchText("fancy") + .setFilter("Rating ge 3") .setSelect("HotelId", "HotelName", "Rating") - .setVectorSearchOptions(new VectorSearchOptions() - .setQueries(createDescriptionVectorQuery().setFilterOverride("HotelId eq '1'"))); + .setVectorQueries(createDescriptionVectorQuery().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()); + List results = searchClient.search(searchOptions).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")); + assertEquals("1", results.get(0).getAdditionalProperties().get("HotelId")); } @Test public void hybridSearchWithVectorFilterOverrideAsync() { // 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") + SearchOptions searchOptions = new SearchOptions().setSearchText("fancy") + .setFilter("Rating ge 3") .setSelect("HotelId", "HotelName", "Rating") - .setVectorSearchOptions(new VectorSearchOptions() - .setQueries(createDescriptionVectorQuery().setFilterOverride("HotelId eq '1'"))); + .setVectorQueries(createDescriptionVectorQuery().setFilterOverride("HotelId eq '1'")); // run the hybrid search query SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - StepVerifier.create(searchClient.search("fancy", searchOptions).collectList()).assertNext(results -> { + StepVerifier.create(searchClient.search(searchOptions).collectList()).assertNext(results -> { // check that the results are as expected assertEquals(1, results.size()); - assertEquals("1", results.get(0).getDocument(SearchDocument.class).get("HotelId")); + assertEquals("1", results.get(0).getAdditionalProperties().get("HotelId")); }).verifyComplete(); } @@ -309,29 +294,25 @@ public void hybridSearchWithVectorFilterOverrideAsync() { public void vectorSearchWithPostFilterModeSync() { SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery()) - .setFilterMode(VectorFilterMode.POST_FILTER)) + SearchOptions searchOptions = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()) + .setVectorFilterMode(VectorFilterMode.POST_FILTER) .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"), "3", "5", "1"); + List results = searchClient.search(searchOptions).stream().collect(Collectors.toList()); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "3", "5", "1"); } @Test public void vectorSearchWithPostFilterModeAsync() { SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery()) - .setFilterMode(VectorFilterMode.POST_FILTER)) + SearchOptions searchOptions = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()) + .setVectorFilterMode(VectorFilterMode.POST_FILTER) .setSelect("HotelId", "HotelName"); - StepVerifier.create(searchClient.search(null, searchOptions).collectList()) - .assertNext(results -> assertKeysEqual(results, - r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), "3", "5", "1")) + StepVerifier.create(searchClient.search(searchOptions).collectList()) + .assertNext(results -> assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), + "3", "5", "1")) .verifyComplete(); } @@ -339,34 +320,30 @@ public void vectorSearchWithPostFilterModeAsync() { public void vectorSearchWithStrictPostFilterModeSync() { SearchClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, true).buildClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery()) - .setFilterMode(VectorFilterMode.STRICT_POST_FILTER)) + SearchOptions searchOptions = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()) + .setVectorFilterMode(VectorFilterMode.STRICT_POST_FILTER) .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"), "3", "5", "1"); + List results = searchClient.search(searchOptions).stream().collect(Collectors.toList()); + assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), "3", "5", "1"); } @Test public void vectorSearchWithStrictPostFilterModeAsync() { SearchAsyncClient searchClient = getSearchClientBuilder(HOTEL_INDEX_NAME, false).buildAsyncClient(); - SearchOptions searchOptions = new SearchOptions() - .setVectorSearchOptions(new VectorSearchOptions().setQueries(createDescriptionVectorQuery()) - .setFilterMode(VectorFilterMode.STRICT_POST_FILTER)) + SearchOptions searchOptions = new SearchOptions().setVectorQueries(createDescriptionVectorQuery()) + .setVectorFilterMode(VectorFilterMode.STRICT_POST_FILTER) .setSelect("HotelId", "HotelName"); - StepVerifier.create(searchClient.search(null, searchOptions).collectList()) - .assertNext(results -> assertKeysEqual(results, - r -> (String) r.getDocument(SearchDocument.class).get("HotelId"), "3", "5", "1")) + StepVerifier.create(searchClient.search(searchOptions).collectList()) + .assertNext(results -> assertKeysEqual(results, r -> (String) r.getAdditionalProperties().get("HotelId"), + "3", "5", "1")) .verifyComplete(); } private static VectorQuery createDescriptionVectorQuery() { - return new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighborsCount(3) + return new VectorizedQuery(VectorSearchEmbeddings.SEARCH_VECTORIZE_DESCRIPTION).setKNearestNeighbors(3) .setFields("DescriptionVector"); } @@ -385,95 +362,89 @@ private static void assertKeysEqual(List results, Function> 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) { - try { - return jsonSerializable.toJsonString(); - } 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 index 46b3483a666e..16b8dedcdd6b 100644 --- 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 @@ -2,76 +2,15 @@ // 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.BinaryData; 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.indexes.models.*; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.SearchOptions; import com.azure.search.documents.models.SearchResult; import org.junit.jupiter.api.Test; @@ -84,16 +23,18 @@ 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.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; 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.createIndexAction; +import static com.azure.search.documents.TestHelpers.ifMatch; import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; import static com.azure.search.documents.TestHelpers.waitForIndexing; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -136,13 +77,13 @@ public void canSearchWithCustomAnalyzerSyncAndAsync() { SearchAsyncClient searchAsyncClient = searchIndexAsyncClient.getSearchAsyncClient(searchClient.getIndexName()); Iterator iterator - = searchClient.search("someone@somewhere.something", new SearchOptions(), Context.NONE).iterator(); + = searchClient.search(new SearchOptions().setSearchText("someone@somewhere.something")).iterator(); - assertEquals("1", iterator.next().getDocument(SearchDocument.class).get("id")); + assertEquals("1", iterator.next().getAdditionalProperties().get("id")); assertFalse(iterator.hasNext()); - StepVerifier.create(searchAsyncClient.search("someone@somewhere.something", new SearchOptions())) - .assertNext(searchResult -> assertEquals("1", searchResult.getDocument(SearchDocument.class).get("id"))) + StepVerifier.create(searchAsyncClient.search(new SearchOptions().setSearchText("someone@somewhere.something"))) + .assertNext(searchResult -> assertEquals("1", searchResult.getAdditionalProperties().get("id"))) .verifyComplete(); } @@ -150,28 +91,30 @@ private T setupSearchIndexForCustomAnalyzerSearch(Function client 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(), "@", "_")); + SearchIndex index = new SearchIndex(randomIndexName("testindex"), + 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(); + Map document1 = new HashMap<>(); document1.put("id", "1"); document1.put("message", "My email is someone@somewhere.something."); - SearchDocument document2 = new SearchDocument(); + Map document2 = new HashMap<>(); document2.put("id", "2"); document2.put("message", "His email is someone@nowhere.nothing."); - List documents = Arrays.asList(document1, document2); + IndexDocumentsBatch batch = new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, document1), + createIndexAction(IndexActionType.UPLOAD, document2)); - searchClient.uploadDocuments(documents); + searchClient.indexDocuments(batch); waitForIndexing(); return clientCreator.apply(index.getName()); @@ -202,36 +145,36 @@ public void canAnalyzeSyncAndAsync() { searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); - AnalyzeTextOptions request = new AnalyzeTextOptions("One two", LexicalAnalyzerName.WHITESPACE); + AnalyzeTextOptions request = new AnalyzeTextOptions("One two").setAnalyzerName(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()); + AnalyzeResult results = searchIndexClient.analyzeText(index.getName(), request); + assertEquals(2, results.getTokens().size()); + assertTokenInfoEqual("One", 0, 3, 0, results.getTokens().get(0)); + assertTokenInfoEqual("two", 4, 7, 1, results.getTokens().get(1)); // 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(); + StepVerifier.create(searchIndexAsyncClient.analyzeText(index.getName(), request)).assertNext(analyzeResults -> { + assertEquals(2, analyzeResults.getTokens().size()); + assertTokenInfoEqual("One", 0, 3, 0, analyzeResults.getTokens().get(0)); + assertTokenInfoEqual("two", 4, 7, 1, analyzeResults.getTokens().get(1)); + }).verifyComplete(); - request = new AnalyzeTextOptions("One's ", LexicalTokenizerName.WHITESPACE) + request = new AnalyzeTextOptions("One's ").setTokenizerName(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()); + assertEquals(1, results.getTokens().size()); + assertTokenInfoEqual("One", 0, 5, 0, results.getTokens().get(0)); // async - StepVerifier.create(searchIndexAsyncClient.analyzeText(index.getName(), request)) - .assertNext(analyzedTokenInfo -> assertTokenInfoEqual("One", 0, 5, 0, analyzedTokenInfo)) - .verifyComplete(); + StepVerifier.create(searchIndexAsyncClient.analyzeText(index.getName(), request)).assertNext(analyzeResults -> { + assertEquals(1, analyzeResults.getTokens().size()); + assertTokenInfoEqual("One", 0, 5, 0, analyzeResults.getTokens().get(0)); + }).verifyComplete(); } @Test @@ -245,26 +188,26 @@ public void canAnalyzeWithAllPossibleNamesSyncAndAsync() { 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 -> { - })); + .map(an -> new AnalyzeTextOptions("One two").setAnalyzerName(an)) + .forEach(r -> searchIndexClient.analyzeText(index.getName(), r)); Flux.fromIterable(threadSafeLexicalAnalyzerNames) .parallel() .runOn(Schedulers.boundedElastic()) - .flatMap(an -> searchIndexAsyncClient.analyzeText(index.getName(), new AnalyzeTextOptions("One two", an))) + .flatMap(an -> searchIndexAsyncClient.analyzeText(index.getName(), + new AnalyzeTextOptions("One two").setAnalyzerName(an))) .then() .block(); threadSafeLexicalTokenizerNames.parallelStream() - .map(tn -> new AnalyzeTextOptions("One two", tn)) - .forEach(r -> searchIndexClient.analyzeText(index.getName(), r).forEach(ignored -> { - })); + .map(tn -> new AnalyzeTextOptions("One two").setTokenizerName(tn)) + .forEach(r -> searchIndexClient.analyzeText(index.getName(), r)); Flux.fromIterable(threadSafeLexicalTokenizerNames) .parallel() .runOn(Schedulers.boundedElastic()) - .flatMap(tn -> searchIndexAsyncClient.analyzeText(index.getName(), new AnalyzeTextOptions("One two", tn))) + .flatMap(tn -> searchIndexAsyncClient.analyzeText(index.getName(), + new AnalyzeTextOptions("One two").setTokenizerName(tn))) .then() .block(); } @@ -292,8 +235,11 @@ public void canAddCustomAnalyzerWithIndexDowntimeSync() { indexesToCleanup.add(index.getName()); addAnalyzerToIndex(index, new StopAnalyzer("a2")); - SearchIndex updatedIndex - = searchIndexClient.createOrUpdateIndexWithResponse(index, true, false, Context.NONE).getValue(); + SearchIndex updatedIndex = searchIndexClient + .createOrUpdateIndexWithResponse(index.getName(), BinaryData.fromObject(index), + ifMatch(index.getETag()).addQueryParam("allowIndexDowntime", "true")) + .getValue() + .toObject(SearchIndex.class); assertAnalysisComponentsEqual(index, updatedIndex); } @@ -306,8 +252,11 @@ public void canAddCustomAnalyzerWithIndexDowntimeAsync() { addAnalyzerToIndex(index, new StopAnalyzer("a2")); - StepVerifier.create(searchIndexAsyncClient.createOrUpdateIndexWithResponse(index, true, false)) - .assertNext(response -> assertAnalysisComponentsEqual(index, response.getValue())) + StepVerifier + .create(searchIndexAsyncClient.createOrUpdateIndexWithResponse(index.getName(), + BinaryData.fromObject(index), ifMatch(index.getETag()).addQueryParam("allowIndexDowntime", "true"))) + .assertNext( + response -> assertAnalysisComponentsEqual(index, response.getValue().toObject(SearchIndex.class))) .verifyComplete(); } @@ -430,18 +379,6 @@ 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(); @@ -557,11 +494,11 @@ List prepareIndexesWithAllAnalysisComponentOptions() { 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); + for (MicrosoftStemmingTokenizerLanguage tokenizer : MicrosoftStemmingTokenizerLanguage.values()) { + tokenizers.add(new MicrosoftLanguageStemmingTokenizer(generateName()).setMaxTokenLength(200) + .setIsSearchTokenizer(false) + .setLanguage(tokenizer)); + } index.setTokenizers(tokenizers); // Set token filters @@ -569,27 +506,28 @@ List prepareIndexesWithAllAnalysisComponentOptions() { 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); + for (EdgeNGramTokenFilterSide filter : EdgeNGramTokenFilterSide.values()) { + tokenFilters.add(new EdgeNGramTokenFilterV2(generateName()).setMinGram(1).setMaxGram(2).setSide(filter)); + } - Arrays.stream(PhoneticEncoder.values()) - .map(pe -> new PhoneticTokenFilter(generateName()).setEncoder(pe).setOriginalTokensReplaced(false)) - .forEach(tokenFilters::add); + for (PhoneticEncoder filter : PhoneticEncoder.values()) { + tokenFilters + .add(new PhoneticTokenFilter(generateName()).setEncoder(filter).setReplaceOriginalTokens(false)); + } - Arrays.stream(SnowballTokenFilterLanguage.values()) - .map(l -> new SnowballTokenFilter(generateName(), l)) - .forEach(tokenFilters::add); + for (SnowballTokenFilterLanguage filter : SnowballTokenFilterLanguage.values()) { + tokenFilters.add(new SnowballTokenFilter(generateName(), filter)); + } - Arrays.stream(StemmerTokenFilterLanguage.values()) - .map(l -> new StemmerTokenFilter(generateName(), l)) - .forEach(tokenFilters::add); + for (StemmerTokenFilterLanguage filter : StemmerTokenFilterLanguage.values()) { + tokenFilters.add(new StemmerTokenFilter(generateName(), filter)); + } - Arrays.stream(StopwordsList.values()) - .map(l -> new StopwordsTokenFilter(generateName()).setStopwordsList(l) - .setCaseIgnored(false) - .setTrailingStopWordsRemoved(true)) - .forEach(tokenFilters::add); + for (StopwordsList stopwordsList : StopwordsList.values()) { + tokenFilters.add(new StopwordsTokenFilter(generateName()).setStopwordsList(stopwordsList) + .setIgnoreCase(false) + .setRemoveTrailingStopWords(true)); + } index.setTokenFilters(tokenFilters); @@ -626,7 +564,7 @@ SearchIndex prepareIndexWithAllLexicalAnalyzerNames() { fields.add(new SearchField("id", SearchFieldDataType.STRING).setKey(true)); - return new SearchIndex(randomIndexName("hotel")).setFields(fields); + return new SearchIndex(randomIndexName("hotel"), fields); } SearchIndex prepareIndexWithAllAnalysisComponentNames() { @@ -645,7 +583,7 @@ SearchIndex prepareIndexWithAllAnalysisComponentNames() { analyzers.add(analyzerWithAllTokenFilterAndCharFilters); String nameBase = generateName(); - List analyzerNames = LEXICAL_TOKENIZER_NAMES; + List analyzerNames = new ArrayList<>(LEXICAL_TOKENIZER_NAMES); analyzerNames.sort(Comparator.comparing(LexicalTokenizerName::toString)); analyzerNames.stream().map(tn -> new CustomAnalyzer(nameBase + tn, tn)).forEach(analyzers::add); @@ -734,20 +672,20 @@ SearchIndex prepareIndexWithAllAnalysisComponentTypes() { .setTokenChars(TokenCharacterKind.LETTER), new NGramTokenizer(generateName()).setMinGram(2).setMaxGram(4).setTokenChars(TokenCharacterKind.LETTER), new ClassicTokenizer(generateName()).setMaxTokenLength(100), - new KeywordTokenizer(generateName()).setMaxTokenLength(100), + new KeywordTokenizerV2(generateName()).setMaxTokenLength(100), new MicrosoftLanguageStemmingTokenizer(generateName()).setMaxTokenLength(100) - .setIsSearchTokenizerUsed(true) + .setIsSearchTokenizer(true) .setLanguage(MicrosoftStemmingTokenizerLanguage.CROATIAN), new MicrosoftLanguageTokenizer(generateName()).setMaxTokenLength(100) .setIsSearchTokenizer(true) .setLanguage(MicrosoftTokenizerLanguage.THAI), - new PathHierarchyTokenizer(generateName()).setDelimiter(':') - .setReplacement('_') + new PathHierarchyTokenizerV2(generateName()).setDelimiter(":") + .setReplacement("_") .setMaxTokenLength(300) - .setTokenOrderReversed(true) + .setReverseTokenOrder(true) .setNumberOfTokensToSkip(2), new PatternTokenizer(generateName()).setPattern(".*").setFlags(RegexFlags.MULTILINE).setGroup(0), - new LuceneStandardTokenizer(generateName()).setMaxTokenLength(100), + new LuceneStandardTokenizerV2(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) @@ -755,30 +693,26 @@ SearchIndex prepareIndexWithAllAnalysisComponentTypes() { 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) + new CommonGramTokenFilter(generateName(), "hello", "goodbye").setIgnoreCase(true).setUseQueryMode(true), + new CommonGramTokenFilter(generateName(), "at"), + new DictionaryDecompounderTokenFilter(generateName(), "Schadenfreude").setMinWordSize(10) .setMinSubwordSize(5) .setMaxSubwordSize(13) - .setOnlyLongestMatched(true), - new EdgeNGramTokenFilter(generateName()).setMinGram(2) + .setOnlyLongestMatch(true), + new EdgeNGramTokenFilterV2(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 KeepTokenFilter(generateName(), "aloha"), new KeepTokenFilter(generateName(), "e", "komo", "mai"), + new KeywordMarkerTokenFilter(generateName(), "key", "words"), + new KeywordMarkerTokenFilter(generateName(), "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 LimitTokenFilter(generateName()).setMaxTokenCount(10).setConsumeAllTokens(true), + new NGramTokenFilterV2(generateName()).setMinGram(2).setMaxGram(3), + new PatternCaptureTokenFilter(generateName(), ".*").setPreserveOriginal(false), new PatternReplaceTokenFilter(generateName(), "abc", "123"), new PhoneticTokenFilter(generateName()).setEncoder(PhoneticEncoder.SOUNDEX) - .setOriginalTokensReplaced(false), + .setReplaceOriginalTokens(false), new ShingleTokenFilter(generateName()).setMaxShingleSize(10) .setMinShingleSize(5) .setOutputUnigrams(false) @@ -786,31 +720,30 @@ SearchIndex prepareIndexWithAllAnalysisComponentTypes() { .setTokenSeparator(" ") .setFilterToken("|"), new SnowballTokenFilter(generateName(), SnowballTokenFilterLanguage.ENGLISH), - new StemmerOverrideTokenFilter(generateName(), Collections.singletonList("ran => run")), + new StemmerOverrideTokenFilter(generateName(), "ran => run"), new StemmerTokenFilter(generateName(), StemmerTokenFilterLanguage.FRENCH), - new StopwordsTokenFilter(generateName()).setStopwords(Arrays.asList("a", "the")) - .setCaseIgnored(true) - .setTrailingStopWordsRemoved(false), + new StopwordsTokenFilter(generateName()).setStopwords("a", "the") + .setIgnoreCase(true) + .setRemoveTrailingStopWords(false), new StopwordsTokenFilter(generateName()).setStopwordsList(StopwordsList.ITALIAN) - .setCaseIgnored(true) - .setTrailingStopWordsRemoved(false), - new SynonymTokenFilter(generateName(), Collections.singletonList("great, good")).setCaseIgnored(true) - .setExpand(false), + .setIgnoreCase(true) + .setRemoveTrailingStopWords(false), + new SynonymTokenFilter(generateName(), "great, good").setIgnoreCase(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) + .setCatenateWords(true) + .setCatenateNumbers(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 => $")), + .setCharFilters(new MappingCharFilter(customCharFilterName.toString(), "a => b"), // One custom char filter for CustomAnalyzer above. + new MappingCharFilter(generateName(), "s => $", "S => $"), new PatternReplaceCharFilter(generateName(), "abc", "123")); } @@ -818,80 +751,74 @@ 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++)), + .setAnalyzers(new PatternAnalyzer(generateSimpleName(i++)), + new LuceneStandardAnalyzer(generateSimpleName(i++))) + .setTokenizers(new EdgeNGramTokenizer(generateSimpleName(i++)), new NGramTokenizer(generateSimpleName(i++)), + new ClassicTokenizer(generateSimpleName(i++)), new KeywordTokenizerV2(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 PathHierarchyTokenizerV2(generateSimpleName(i++)), new PatternTokenizer(generateSimpleName(i++)), + new LuceneStandardTokenizerV2(generateSimpleName(i++)), + new UaxUrlEmailTokenizer(generateSimpleName(i++))) + .setTokenFilters(new DictionaryDecompounderTokenFilter(generateSimpleName(i++), "Bahnhof"), + new EdgeNGramTokenFilterV2(generateSimpleName(i++)), new LengthTokenFilter(generateSimpleName(i++)), + new LimitTokenFilter(generateSimpleName(i++)), new NGramTokenFilterV2(generateSimpleName(i++)), + new PatternCaptureTokenFilter(generateSimpleName(i++), "[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)))); + new SynonymTokenFilter(generateSimpleName(i++), "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), + .setAnalyzers(new PatternAnalyzer(generateSimpleName(i++)).setLowerCaseTerms(true).setPattern("\\W+"), + new LuceneStandardAnalyzer(generateSimpleName(i++)).setMaxTokenLength(255)) + .setTokenizers(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 KeywordTokenizerV2(generateSimpleName(i++)).setMaxTokenLength(256), new MicrosoftLanguageStemmingTokenizer(generateSimpleName(i++)).setMaxTokenLength(255) - .setIsSearchTokenizerUsed(false) + .setIsSearchTokenizer(false) .setLanguage(MicrosoftStemmingTokenizerLanguage.ENGLISH), new MicrosoftLanguageTokenizer(generateSimpleName(i++)).setMaxTokenLength(255) .setIsSearchTokenizer(false) .setLanguage(MicrosoftTokenizerLanguage.ENGLISH), - new PathHierarchyTokenizer(generateSimpleName(i++)).setDelimiter('/') - .setReplacement('/') + new PathHierarchyTokenizerV2(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) + new LuceneStandardTokenizerV2(generateSimpleName(i++)).setMaxTokenLength(255), + new UaxUrlEmailTokenizer(generateSimpleName(i++)).setMaxTokenLength(255)) + .setTokenFilters( + new DictionaryDecompounderTokenFilter(generateSimpleName(i++), "Bahnhof").setMinWordSize(5) .setMinSubwordSize(2) .setMaxSubwordSize(15), - new EdgeNGramTokenFilter(generateSimpleName(i++)).setMinGram(1) + new EdgeNGramTokenFilterV2(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 NGramTokenFilterV2(generateSimpleName(i++)).setMinGram(1).setMaxGram(2), + new PatternCaptureTokenFilter(generateSimpleName(i++), "[a-z]*").setPreserveOriginal(true), new PhoneticTokenFilter(generateSimpleName(i++)).setEncoder(PhoneticEncoder.METAPHONE) - .setOriginalTokensReplaced(true), + .setReplaceOriginalTokens(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), + .setRemoveTrailingStopWords(true), + new SynonymTokenFilter(generateSimpleName(i++), "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))); + .setStemEnglishPossessive(true)); } static void assertTokenInfoEqual(String expectedToken, Integer expectedStartOffset, Integer expectedEndOffset, 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 index c9e63319e126..78d8a46e665e 100644 --- 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 @@ -5,10 +5,11 @@ import com.azure.core.exception.HttpResponseException; import com.azure.core.http.rest.Response; -import com.azure.core.util.Context; +import com.azure.core.util.BinaryData; 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.DataSourceCredentials; import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; @@ -37,6 +38,7 @@ 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.ifMatch; import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -44,7 +46,6 @@ 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; @Execution(ExecutionMode.SAME_THREAD) public class DataSourceTests extends SearchTestBase { @@ -94,6 +95,7 @@ public void canCreateAndListDataSourcesSync() { dataSourcesToDelete.add(dataSource2.getName()); Map actualDataSources = client.listDataSourceConnections() + .getDataSources() .stream() .collect(Collectors.toMap(SearchIndexerDataSourceConnection::getName, ds -> ds)); @@ -113,8 +115,10 @@ public void canCreateAndListDataSourcesAsync() { = Flux.fromIterable(Arrays.asList(dataSource1, dataSource2)) .flatMap(asyncClient::createOrUpdateDataSourceConnection) .doOnNext(ds -> dataSourcesToDelete.add(ds.getName())) - .thenMany(asyncClient.listDataSourceConnections()) - .collectMap(SearchIndexerDataSourceConnection::getName); + .then(asyncClient.listDataSourceConnections()) + .map(result -> result.getDataSources() + .stream() + .collect(Collectors.toMap(SearchIndexerDataSourceConnection::getName, ds -> ds))); StepVerifier.create(listMono) .assertNext(actualDataSources -> compareMaps(expectedDataSources, actualDataSources, @@ -131,13 +135,14 @@ public void canCreateAndListDataSourcesWithResponseSync() { expectedDataSources.add(dataSource1.getName()); expectedDataSources.add(dataSource2.getName()); - client.createOrUpdateDataSourceConnectionWithResponse(dataSource1, false, Context.NONE); + client.createOrUpdateDataSourceConnectionWithResponse(dataSource1.getName(), BinaryData.fromObject(dataSource1), + null); dataSourcesToDelete.add(dataSource1.getName()); - client.createOrUpdateDataSourceConnectionWithResponse(dataSource2, false, Context.NONE); + client.createOrUpdateDataSourceConnectionWithResponse(dataSource2.getName(), BinaryData.fromObject(dataSource2), + null); dataSourcesToDelete.add(dataSource2.getName()); - Set actualDataSources - = client.listDataSourceConnectionNames(Context.NONE).stream().collect(Collectors.toSet()); + Set actualDataSources = new HashSet<>(client.listDataSourceConnectionNames()); assertEquals(expectedDataSources.size(), actualDataSources.size()); expectedDataSources.forEach(ds -> assertTrue(actualDataSources.contains(ds), "Missing expected data source.")); @@ -153,10 +158,12 @@ public void canCreateAndListDataSourcesWithResponseAsync() { 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()); + .flatMap(ds -> asyncClient.createOrUpdateDataSourceConnectionWithResponse(ds.getName(), + BinaryData.fromObject(ds), null)) + .doOnNext(ds -> dataSourcesToDelete + .add(ds.getValue().toObject(SearchIndexerDataSourceConnection.class).getName())) + .then(asyncClient.listDataSourceConnectionNames()) + .map(HashSet::new); StepVerifier.create(listMono).assertNext(actualDataSources -> { assertEquals(expectedDataSources.size(), actualDataSources.size()); @@ -187,17 +194,17 @@ 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); + Response result = client.deleteDataSourceConnectionWithResponse(dataSource.getName(), null); 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); + result = client.deleteDataSourceConnectionWithResponse(dataSource.getName(), null); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, result.getStatusCode()); // Again, expect to fail - result = client.deleteDataSourceConnectionWithResponse(dataSource, false, Context.NONE); + result = client.deleteDataSourceConnectionWithResponse(dataSource.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); } @@ -206,7 +213,7 @@ 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)) + StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); @@ -214,20 +221,22 @@ public void deleteDataSourceIsIdempotentAsync() { 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)) + StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) .verifyComplete(); // Again, expect to fail - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource, false)) + StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(dataSource.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); } @Test public void createDataSourceFailsWithUsefulMessageOnUserErrorSyncAndAsync() { - SearchIndexerDataSourceConnection dataSource = createTestSqlDataSourceObject(); - dataSource.setType(SearchIndexerDataSourceType.fromString("thistypedoesnotexist")); + SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("invalid", + SearchIndexerDataSourceType.fromString("thistypedoesnotexist"), + new DataSourceCredentials().setConnectionString(FAKE_AZURE_SQL_CONNECTION_STRING), + new SearchIndexerDataContainer("GeoNamesRI")); assertHttpResponseException(() -> client.createOrUpdateDataSourceConnection(dataSource), HttpURLConnection.HTTP_BAD_REQUEST, "Data source type 'thistypedoesnotexist' is not supported"); @@ -244,16 +253,15 @@ public void canUpdateDataSourceSync() { // 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 updatedExpected = createTestSqlDataSourceObject(initial.getName(), + new SearchIndexerDataContainer("somethingdifferent"), null, null).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. + updatedExpected.getCredentials().setConnectionString(null); // Create doesn't return connection strings. TestHelpers.assertObjectEquals(updatedExpected, updatedActual, false, "etag", "@odata.etag", "@odata.type"); } @@ -265,17 +273,16 @@ public void canUpdateDataSourceAsync() { 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")); + SearchIndexerDataSourceConnection updatedExpected = createTestSqlDataSourceObject(initial.getName(), + new SearchIndexerDataContainer("somethingdifferent"), null, null).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(); + assertObjectEquals(updatedExpected.getCredentials().setConnectionString(null), actual, false, "etag", + "@odata.etag", "@odata.type")).verifyComplete(); } @Test @@ -284,7 +291,8 @@ public void createOrUpdateDatasourceIfNotExistsSucceedsOnNoResourceSync() { dataSourcesToDelete.add(dataSource.getName()); SearchIndexerDataSourceConnection response - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, true, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, ifMatch(dataSource.getETag())) + .getValue(); assertNotNull(response.getETag()); } @@ -294,7 +302,9 @@ public void createOrUpdateDatasourceIfNotExistsSucceedsOnNoResourceAsync() { SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); dataSourcesToDelete.add(dataSource.getName()); - StepVerifier.create(asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, true)) + StepVerifier + .create( + asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, ifMatch(dataSource.getETag()))) .assertNext(response -> assertNotNull(response.getValue().getETag())) .verifyComplete(); } @@ -305,21 +315,20 @@ public void deleteDataSourceIfExistsWorksOnlyWhenResourceExistsSyncAndAsync() { dataSourcesToDelete.add(dataSource.getName()); SearchIndexerDataSourceConnection response - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).getValue(); - client.deleteDataSourceConnectionWithResponse(response, true, Context.NONE); + client.deleteDataSourceConnectionWithResponse(response.getName(), ifMatch(response.getETag())); - 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()); - } + HttpResponseException ex = assertThrows(HttpResponseException.class, + () -> client.deleteDataSourceConnectionWithResponse(response.getName(), ifMatch(response.getETag())), + "Second call to delete with specified ETag should have failed due to non existent data source."); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(response, true)) + StepVerifier + .create(asyncClient.deleteDataSourceConnectionWithResponse(response.getName(), ifMatch(response.getETag()))) .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); + HttpResponseException ex2 = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex2.getResponse().getStatusCode()); }); } @@ -328,25 +337,24 @@ public void deleteDataSourceIfNotChangedWorksOnlyOnCurrentResourceSyncAndAsync() SearchIndexerDataSourceConnection dataSource = createTestBlobDataSource(null); SearchIndexerDataSourceConnection stale - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).getValue(); SearchIndexerDataSourceConnection current - = client.createOrUpdateDataSourceConnectionWithResponse(stale, false, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(stale, null).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()); - } + HttpResponseException ex = assertThrows(HttpResponseException.class, + () -> client.deleteDataSourceConnectionWithResponse(stale.getName(), ifMatch(stale.getETag())), + "Delete specifying a stale ETag should have failed due to precondition."); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - StepVerifier.create(asyncClient.deleteDataSourceConnectionWithResponse(stale, true)) + StepVerifier + .create(asyncClient.deleteDataSourceConnectionWithResponse(stale.getName(), ifMatch(stale.getETag()))) .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); + HttpResponseException ex2 = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex2.getResponse().getStatusCode()); }); - client.deleteDataSourceConnectionWithResponse(current, true, Context.NONE); + client.deleteDataSourceConnectionWithResponse(current.getName(), ifMatch(current.getETag())); } @Test @@ -355,13 +363,13 @@ public void updateDataSourceIfExistsSucceedsOnExistingResourceSync() { dataSourcesToDelete.add(dataSource.getName()); SearchIndexerDataSourceConnection original - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).getValue(); String originalETag = original.getETag(); - SearchIndexerDataSourceConnection updated = client - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), false, Context.NONE) - .getValue(); + SearchIndexerDataSourceConnection updated + = client.createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), null) + .getValue(); String updatedETag = updated.getETag(); @@ -375,12 +383,12 @@ public void updateDataSourceIfExistsSucceedsOnExistingResourceAsync() { dataSourcesToDelete.add(dataSource.getName()); Mono> createThenUpdateMono - = asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, false).flatMap(response -> { + = asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).flatMap(response -> { SearchIndexerDataSourceConnection original = response.getValue(); String originalETag = original.getETag(); return asyncClient - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), false) + .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), null) .map(updated -> Tuples.of(originalETag, updated.getValue().getETag())); }); @@ -396,25 +404,23 @@ public void updateDataSourceIfNotChangedFailsWhenResourceChangedSyncAndAsync() { dataSourcesToDelete.add(dataSource.getName()); SearchIndexerDataSourceConnection original - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).getValue(); String originalETag = original.getETag(); - SearchIndexerDataSourceConnection updated = client - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), false, Context.NONE) - .getValue(); + SearchIndexerDataSourceConnection updated + = client.createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), null) + .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()); - } + HttpResponseException ex = assertThrows(HttpResponseException.class, + () -> client.createOrUpdateDataSourceConnectionWithResponse(original, ifMatch(originalETag)), + "createOrUpdateDefinition should have failed due to precondition."); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - StepVerifier.create(asyncClient.createOrUpdateDataSourceConnectionWithResponse(original, true)) + StepVerifier.create(asyncClient.createOrUpdateDataSourceConnectionWithResponse(original, ifMatch(originalETag))) .verifyErrorSatisfies(throwable -> { - HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); - assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); + HttpResponseException ex2 = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex2.getResponse().getStatusCode()); }); assertNotNull(originalETag); @@ -428,11 +434,11 @@ public void updateDataSourceIfNotChangedSucceedsWhenResourceUnchangedSync() { dataSourcesToDelete.add(dataSource.getName()); SearchIndexerDataSourceConnection original - = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, false, Context.NONE).getValue(); + = client.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).getValue(); String originalETag = original.getETag(); SearchIndexerDataSourceConnection updated = client - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), true, Context.NONE) + .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), ifMatch(originalETag)) .getValue(); String updatedETag = updated.getETag(); @@ -448,12 +454,13 @@ public void updateDataSourceIfNotChangedSucceedsWhenResourceUnchangedAsync() { dataSourcesToDelete.add(dataSource.getName()); Mono> etagUpdatesOnChangeMono - = asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, false).flatMap(response -> { + = asyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, null).flatMap(response -> { SearchIndexerDataSourceConnection original = response.getValue(); String originalETag = original.getETag(); return asyncClient - .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), true) + .createOrUpdateDataSourceConnectionWithResponse(original.setDescription("an update"), + ifMatch(originalETag)) .map(updated -> Tuples.of(originalETag, updated.getValue().getETag())); }); @@ -498,7 +505,7 @@ private void createAndValidateDataSource(SearchIndexerDataSourceConnection expec SearchIndexerDataSourceConnection actualDataSource = client.createOrUpdateDataSourceConnection(expectedDataSource); - expectedDataSource.setConnectionString(null); + expectedDataSource.getCredentials().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()); @@ -518,12 +525,14 @@ private void createGetAndValidateDataSourceSync(SearchIndexerDataSourceConnectio String dataSourceName = expectedDataSource.getName(); // Get doesn't return connection strings. - expectedDataSource.setConnectionString(null); + expectedDataSource.getCredentials().setConnectionString(null); SearchIndexerDataSourceConnection actualDataSource = client.getDataSourceConnection(dataSourceName); TestHelpers.assertObjectEquals(expectedDataSource, actualDataSource, false, "etag", "@odata.etag"); - actualDataSource = client.getDataSourceConnectionWithResponse(dataSourceName, Context.NONE).getValue(); + actualDataSource = client.getDataSourceConnectionWithResponse(dataSourceName, null) + .getValue() + .toObject(SearchIndexerDataSourceConnection.class); TestHelpers.assertObjectEquals(expectedDataSource, actualDataSource, false, "etag", "@odata.etag"); client.deleteDataSourceConnection(dataSourceName); @@ -542,16 +551,16 @@ private void createGetAndValidateDataSourceAsync(SearchIndexerDataSourceConnecti String dataSourceName = expectedDataSource.getName(); // Get doesn't return connection strings. - expectedDataSource.setConnectionString(null); + expectedDataSource.getCredentials().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")) + StepVerifier.create(asyncClient.getDataSourceConnectionWithResponse(dataSourceName, null)) + .assertNext(response -> assertObjectEquals(expectedDataSource, + response.getValue().toObject(SearchIndexerDataSourceConnection.class), false, "etag", "@odata.etag")) .verifyComplete(); asyncClient.deleteDataSourceConnection(dataSourceName).block(); @@ -591,10 +600,11 @@ public void canCreateDataSourceAsync() { public void canCreateDataSourceWithResponseSync() { SearchIndexerDataSourceConnection expectedDataSource = createTestBlobDataSource(null); dataSourcesToDelete.add(expectedDataSource.getName()); - Response response - = client.createDataSourceConnectionWithResponse(expectedDataSource, Context.NONE); + Response response + = client.createDataSourceConnectionWithResponse(BinaryData.fromObject(expectedDataSource), null); - assertEquals(expectedDataSource.getName(), response.getValue().getName()); + assertEquals(expectedDataSource.getName(), + response.getValue().toObject(SearchIndexerDataSourceConnection.class).getName()); assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); } @@ -603,9 +613,11 @@ public void canCreateDataSourceWithResponseAsync() { SearchIndexerDataSourceConnection expectedDataSource = createTestBlobDataSource(null); dataSourcesToDelete.add(expectedDataSource.getName()); - StepVerifier.create(asyncClient.createDataSourceConnectionWithResponse(expectedDataSource)) + StepVerifier + .create(asyncClient.createDataSourceConnectionWithResponse(BinaryData.fromObject(expectedDataSource), null)) .assertNext(response -> { - assertEquals(expectedDataSource.getName(), response.getValue().getName()); + assertEquals(expectedDataSource.getName(), + response.getValue().toObject(SearchIndexerDataSourceConnection.class).getName()); assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); }) .verifyComplete(); @@ -619,32 +631,39 @@ public void canUpdateConnectionData() { // Create an initial dataSource SearchIndexerDataSourceConnection initial = createTestBlobDataSource(null); - assertEquals(FAKE_STORAGE_CONNECTION_STRING, initial.getConnectionString()); + assertEquals(FAKE_STORAGE_CONNECTION_STRING, initial.getCredentials().getConnectionString()); // tweak the connection string and verify it was changed String newConnString = "DefaultEndpointsProtocol=https;AccountName=NotaRealYetDifferentAccount;AccountKey=AnotherFakeKey;"; - initial.setConnectionString(newConnString); + initial.getCredentials().setConnectionString(newConnString); - assertEquals(newConnString, initial.getConnectionString()); + assertEquals(newConnString, initial.getCredentials().getConnectionString()); } SearchIndexerDataSourceConnection createTestBlobDataSource(DataDeletionDetectionPolicy deletionDetectionPolicy) { - return SearchIndexerDataSources.createFromAzureBlobStorage( - testResourceNamer.randomName(BLOB_DATASOURCE_TEST_NAME, 32), FAKE_STORAGE_CONNECTION_STRING, - "fakecontainer", "/fakefolder/", FAKE_DESCRIPTION, deletionDetectionPolicy); + return new SearchIndexerDataSourceConnection(testResourceNamer.randomName(BLOB_DATASOURCE_TEST_NAME, 32), + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString(FAKE_STORAGE_CONNECTION_STRING), + new SearchIndexerDataContainer("fakecontainer").setQuery("/fakefolder/")).setDescription(FAKE_DESCRIPTION) + .setDataDeletionDetectionPolicy(deletionDetectionPolicy); } static SearchIndexerDataSourceConnection createTestTableStorageDataSource() { - return SearchIndexerDataSources.createFromAzureTableStorage("azs-java-test-tablestorage", - FAKE_STORAGE_CONNECTION_STRING, "faketable", "fake query", FAKE_DESCRIPTION, null); + return new SearchIndexerDataSourceConnection("azs-java-test-tablestorage", + SearchIndexerDataSourceType.AZURE_TABLE, + new DataSourceCredentials().setConnectionString(FAKE_STORAGE_CONNECTION_STRING), + new SearchIndexerDataContainer("faketable").setQuery("fake query")).setDescription(FAKE_DESCRIPTION); } 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); + return new SearchIndexerDataSourceConnection("azs-java-test-cosmos", SearchIndexerDataSourceType.COSMOS_DB, + new DataSourceCredentials().setConnectionString(FAKE_COSMOS_CONNECTION_STRING), + new SearchIndexerDataContainer("faketable").setQuery("SELECT ... FROM x where x._ts > @HighWaterMark")) + .setDescription(FAKE_DESCRIPTION) + .setDataChangeDetectionPolicy(useChangeDetection ? new HighWaterMarkChangeDetectionPolicy("_ts") : null) + .setDataDeletionDetectionPolicy(deletionDetectionPolicy); } private static void assertDataSourceEquals(SearchIndexerDataSourceConnection expect, 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 index 716216098a95..6cae50367bd9 100644 --- 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 @@ -3,15 +3,10 @@ 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 com.azure.search.documents.testingmodels.Hotel; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -47,14 +42,11 @@ protected void afterTest() { @Test public void createIndexWithFieldBuilderSync() { - SynonymMap synonymMap = new SynonymMap(synonymMapName).setSynonyms("hotel,motel"); + SynonymMap synonymMap = new SynonymMap(synonymMapName, "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()))); + SearchIndex index = new SearchIndex(testResourceNamer.randomName("fieldbuilder", 32), + SearchIndexClient.buildSearchFields(Hotel.class)); client.createIndex(index); indexesToDelete.add(index.getName()); @@ -63,14 +55,11 @@ public void createIndexWithFieldBuilderSync() { @Test public void createIndexWithFieldBuilderAsync() { - SynonymMap synonymMap = new SynonymMap(synonymMapName).setSynonyms("hotel,motel"); + SynonymMap synonymMap = new SynonymMap(synonymMapName, "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()))); + SearchIndex index = new SearchIndex(testResourceNamer.randomName("fieldbuilder", 32), + SearchIndexClient.buildSearchFields(Hotel.class)); Mono createThenGetIndex = asyncClient.createIndex(index).flatMap(actual -> { indexesToDelete.add(actual.getName()); 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 index ef42ec59eb0b..7e26290992b8 100644 --- 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 @@ -8,15 +8,15 @@ import com.azure.search.documents.indexes.models.LexicalNormalizerName; 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 com.azure.search.documents.testingmodels.HotelAnalyzerException; +import com.azure.search.documents.testingmodels.HotelCircularDependencies; +import com.azure.search.documents.testingmodels.HotelRenameProperty; +import com.azure.search.documents.testingmodels.HotelSearchException; +import com.azure.search.documents.testingmodels.HotelSearchableExceptionOnList; +import com.azure.search.documents.testingmodels.HotelTwoDimensional; +import com.azure.search.documents.testingmodels.HotelWithArray; +import com.azure.search.documents.testingmodels.HotelWithEmptyInSynonymMaps; +import com.azure.search.documents.testingmodels.HotelWithIgnoredFields; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -42,15 +42,15 @@ public class FieldBuilderTests { @Test public void hotelSearchableThrowException() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelSearchException.class, null)); + IllegalStateException exception = assertThrows(IllegalStateException.class, + () -> SearchIndexClient.buildSearchFields(HotelSearchException.class)); assertExceptionMassageAndDataType(exception, SearchFieldDataType.INT32, "getHotelId"); } @Test public void hotelListFieldSearchableThrowException() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelSearchableExceptionOnList.class, null)); + IllegalStateException exception = assertThrows(IllegalStateException.class, + () -> SearchIndexClient.buildSearchFields(HotelSearchableExceptionOnList.class)); assertExceptionMassageAndDataType(exception, SearchFieldDataType.collection(SearchFieldDataType.INT32), "getPasscode"); } @@ -58,7 +58,7 @@ public void hotelListFieldSearchableThrowException() { @Test public void hotelCircularDependencies() { List actualFields - = sortByFieldName(SearchIndexClient.buildSearchFields(HotelCircularDependencies.class, null)); + = sortByFieldName(SearchIndexClient.buildSearchFields(HotelCircularDependencies.class)); List expectedFields = sortByFieldName(buildHotelCircularDependenciesModel()); assertListFieldEquals(expectedFields, actualFields); } @@ -67,13 +67,13 @@ public void hotelCircularDependencies() { @Disabled("Temporarily disabled") 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 actualFields = SearchIndexClient.buildSearchFields(HotelWithEmptyInSynonymMaps.class); List expectedFields = Collections.singletonList( new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setSearchable(true) .setKey(false) .setStored(true) - .setHidden(false) + .setRetrievable(true) .setFilterable(false) .setSortable(false) .setFacetable(false) @@ -84,23 +84,22 @@ public void hotelWithEmptySynonymMaps() { @Test public void hotelWithTwoDimensionalType() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelTwoDimensional.class, null)); - assertExceptionMassageAndDataType(exception, null, "single-dimensional"); + IllegalStateException exception = assertThrows(IllegalStateException.class, + () -> SearchIndexClient.buildSearchFields(HotelTwoDimensional.class)); + assertExceptionMassageAndDataType(exception, null, "cannot be a nested array or Iterable."); } @Test public void hotelAnalyzerException() { - Exception exception = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(HotelAnalyzerException.class, null)); + IllegalStateException exception = assertThrows(IllegalStateException.class, + () -> SearchIndexClient.buildSearchFields(HotelAnalyzerException.class)); assertExceptionMassageAndDataType(exception, null, "either analyzer or both searchAnalyzer and indexAnalyzer"); } @Test @Disabled("Temporarily disabled") public void hotelWithArrayType() { - List actualFields - = sortByFieldName(SearchIndexClient.buildSearchFields(HotelWithArray.class, null)); + List actualFields = sortByFieldName(SearchIndexClient.buildSearchFields(HotelWithArray.class)); List expectedFields = sortByFieldName(buildHotelWithArrayModel()); assertListFieldEquals(expectedFields, actualFields); } @@ -108,8 +107,8 @@ public void hotelWithArrayType() { @Test public void propertyRename() { List actualFields - = sortByFieldName(SearchIndexClient.buildSearchFields(HotelRenameProperty.class, null)); - List expectedFieldNames = Arrays.asList("HotelName", "hotelId", "description"); + = sortByFieldName(SearchIndexClient.buildSearchFields(HotelRenameProperty.class)); + 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()); @@ -118,219 +117,244 @@ public void propertyRename() { @Test public void ignoredPropertyName() { - List actualFields = SearchIndexClient.buildSearchFields(HotelWithIgnoredFields.class, null); + List actualFields = SearchIndexClient.buildSearchFields(HotelWithIgnoredFields.class); assertEquals(1, actualFields.size()); - assertEquals("notIgnoredName", actualFields.get(0).getName()); + assertEquals("NotIgnoredName", actualFields.get(0).getName()); } @Test public void supportedFields() { - List fields = SearchIndexClient.buildSearchFields(AllSupportedFields.class, null); + List fields = SearchIndexClient.buildSearchFields(AllSupportedFields.class); 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")); + 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 + // 1. name = 'NullableInt', OData type = INT32 + @BasicField(name = "NullableInt") private Integer nullableInt; public Integer getNullableInt() { return nullableInt; } - // 2. name = 'primitiveInt', OData type = INT32 + // 2. name = 'PrimitiveInt', OData type = INT32 + @BasicField(name = "PrimitiveInt") private int primitiveInt; public int getPrimitiveInt() { return primitiveInt; } - // 3. name = 'nullableLong', OData type = INT64 + // 3. name = 'NullableLong', OData type = INT64 + @BasicField(name = "NullableLong") private Long nullableLong; public Long getNullableLong() { return nullableLong; } - // 4. name = 'primitiveLong', OData type = INT64 + // 4. name = 'PrimitiveLong', OData type = INT64 + @BasicField(name = "PrimitiveLong") private long primitiveLong; public long getPrimitiveLong() { return primitiveLong; } - // 5. name = 'nullableDouble', OData type = DOUBLE + // 5. name = 'NullableDouble', OData type = DOUBLE + @BasicField(name = "NullableDouble") private Double nullableDouble; public Double getNullableDouble() { return nullableDouble; } - // 6. name = 'primitiveDouble', OData type = DOUBLE + // 6. name = 'PrimitiveDouble', OData type = DOUBLE + @BasicField(name = "PrimitiveDouble") private double primitiveDouble; public double getPrimitiveDouble() { return primitiveDouble; } - // 7. name = 'nullableBoolean', OData type = BOOLEAN + // 7. name = 'NullableBoolean', OData type = BOOLEAN + @BasicField(name = "NullableBoolean") private Boolean nullableBoolean; public Boolean getNullableBoolean() { return nullableBoolean; } - // 8. name = 'primitiveBoolean', OData type = BOOLEAN + // 8. name = 'PrimitiveBoolean', OData type = BOOLEAN + @BasicField(name = "PrimitiveBoolean") private boolean primitiveBoolean; public boolean isPrimitiveBoolean() { return primitiveBoolean; } - // 9. name = 'string', OData type = STRING + // 9. name = 'String', OData type = STRING + @BasicField(name = "String") private String string; public String getString() { return string; } - // 10. name = 'charSequence', OData type = STRING + // 10. name = 'CharSequence', OData type = STRING + @BasicField(name = "CharSequence") private CharSequence charSequence; public CharSequence getCharSequence() { return charSequence; } - // 11. name = 'nullableChar', OData type = STRING + // 11. name = 'NullableChar', OData type = STRING + @BasicField(name = "NullableChar") private Character nullableChar; public Character getNullableChar() { return nullableChar; } - // 12. name = 'primitiveChar', OData type = STRING + // 12. name = 'PrimitiveChar', OData type = STRING + @BasicField(name = "PrimitiveChar") private char primitiveChar; public char getPrimitiveChar() { return primitiveChar; } - // 13. name = 'date', OData type = DATE_TIME_OFFSET + // 13. name = 'Date', OData type = DATE_TIME_OFFSET + @BasicField(name = "Date") private Date date; public Date getDate() { return date; } - // 14. name = 'offsetDateTime', OData type = DATE_TIME_OFFSET + // 14. name = 'OffsetDateTime', OData type = DATE_TIME_OFFSET + @BasicField(name = "OffsetDateTime") private OffsetDateTime offsetDateTime; public OffsetDateTime getOffsetDateTime() { return offsetDateTime; } - // 15. name = 'geoPoint', OData type = GEOGRAPHY_POINT + // 15. name = 'GeoPoint', OData type = GEOGRAPHY_POINT + @BasicField(name = "GeoPoint") private GeoPoint geoPoint; public GeoPoint getGeoPoint() { return geoPoint; } - // 16. name = 'intArray', OData type = COMPLEX + // 16. name = 'IntArray', OData type = COMPLEX + @BasicField(name = "IntArray") private int[] intArray; public int[] getIntArray() { return intArray; } - // 17. name = 'intList', OData type = COMPLEX + // 17. name = 'IntList', OData type = COMPLEX + @BasicField(name = "IntList") private List intList; public List getIntList() { return intList; } - // 18. name = 'floatList', OData type = COMPLEX + // 18. name = 'FloatList', OData type = COMPLEX + @BasicField(name = "FloatList") private List floatList; public List getFloatList() { return floatList; } - // 19. name = 'floatArray', OData type = COMPLEX + // 19. name = 'FloatArray', OData type = COMPLEX + @BasicField(name = "FloatArray") private Float[] floatArray; public Float[] getFloatArray() { return floatArray; } - // 20. name = 'primitiveShort', OData type = INT16 + // 20. name = 'PrimitiveShort', OData type = INT16 + @BasicField(name = "PrimitiveShort") private short primitiveShort; public short getPrimitiveShort() { return primitiveShort; } - // 21. name = 'nullableShort', OData type = INT16 + // 21. name = 'NullableShort', OData type = INT16 + @BasicField(name = "NullableShort") private Short nullableShort; public Short getNullableShort() { return nullableShort; } - // 22. name = 'primitiveByte', OData type = SBYTE + // 22. name = 'PrimitiveByte', OData type = SBYTE + @BasicField(name = "PrimitiveByte") private byte primitiveByte; public byte getPrimitiveByte() { return primitiveByte; } - // 23. name = 'nullableByte', OData type = SBYTE + // 23. name = 'NullableByte', OData type = SBYTE + @BasicField(name = "NullableByte") private Byte nullableByte; public Byte getNullableByte() { return nullableByte; } - // 24. name = 'byteArray', OData type = COMPLEX + // 24. name = 'ByteArray', OData type = COMPLEX + @BasicField(name = "ByteArray") private byte[] byteArray; public byte[] getByteArray() { return byteArray; } - // 25. name = 'byteList', OData type = COMPLEX + // 25. name = 'ByteList', OData type = COMPLEX + @BasicField(name = "ByteList") private List byteList; public List getByteList() { @@ -340,7 +364,7 @@ public List getByteList() { @Test public void validNormalizerField() { - List fields = SearchIndexClient.buildSearchFields(ValidNormalizer.class, null); + List fields = SearchIndexClient.buildSearchFields(ValidNormalizer.class); assertEquals(1, fields.size()); @@ -350,34 +374,34 @@ public void validNormalizerField() { @SuppressWarnings("unused") public static final class ValidNormalizer { - @SimpleField(normalizerName = "standard", isFilterable = true) + @BasicField(name = "ValidNormalizer", normalizerName = "standard", isFilterable = BasicField.BooleanHelper.TRUE) public String validNormalizer; } @ParameterizedTest @ValueSource(classes = { NonStringNormalizer.class, MissingFunctionalityNormalizer.class }) public void invalidNormalizerField(Class type) { - RuntimeException ex - = assertThrows(RuntimeException.class, () -> SearchIndexClient.buildSearchFields(type, null)); + IllegalStateException ex + = assertThrows(IllegalStateException.class, () -> SearchIndexClient.buildSearchFields(type)); assertTrue(ex.getMessage().contains("A field with a normalizer name")); } @SuppressWarnings("unused") public static final class NonStringNormalizer { - @SimpleField(normalizerName = "standard") + @BasicField(name = "WrongTypeForNormalizer", normalizerName = "standard") public int wrongTypeForNormalizer; } @SuppressWarnings("unused") public static final class MissingFunctionalityNormalizer { - @SimpleField(normalizerName = "standard") + @BasicField(name = "RightTypeWrongFunctionality", normalizerName = "standard") public String rightTypeWrongFunctionality; } @Test public void onlyAnalyzerNameSetsOnlyAnalyzerName() { - List fields = SearchIndexClient.buildSearchFields(OnlyAnalyzerName.class, null); + List fields = SearchIndexClient.buildSearchFields(OnlyAnalyzerName.class); assertEquals(1, fields.size()); @@ -389,13 +413,13 @@ public void onlyAnalyzerNameSetsOnlyAnalyzerName() { @SuppressWarnings("unused") public static final class OnlyAnalyzerName { - @SearchableField(analyzerName = "onlyAnalyzer") + @BasicField(name = "OnlyAnalyzer", analyzerName = "onlyAnalyzer") public String onlyAnalyzer; } @Test public void indexAndSearchAnalyzersSetCorrectly() { - List fields = SearchIndexClient.buildSearchFields(IndexAndSearchAnalyzerNames.class, null); + List fields = SearchIndexClient.buildSearchFields(IndexAndSearchAnalyzerNames.class); assertEquals(1, fields.size()); @@ -407,13 +431,16 @@ public void indexAndSearchAnalyzersSetCorrectly() { @SuppressWarnings("unused") public static final class IndexAndSearchAnalyzerNames { - @SearchableField(indexAnalyzerName = "indexAnalyzer", searchAnalyzerName = "searchAnalyzer") + @BasicField( + name = "indexAndSearchAnalyzer", + indexAnalyzerName = "indexAnalyzer", + searchAnalyzerName = "searchAnalyzer") public String indexAndSearchAnalyzer; } @Test public void vectorSearchField() { - List fields = SearchIndexClient.buildSearchFields(VectorSearchField.class, null); + List fields = SearchIndexClient.buildSearchFields(VectorSearchField.class); assertEquals(1, fields.size()); @@ -424,35 +451,35 @@ public void vectorSearchField() { @SuppressWarnings("unused") public static final class VectorSearchField { - @SearchableField(vectorSearchDimensions = 1536, vectorSearchProfileName = "myprofile") + @BasicField(name = "vectorSearchField", vectorSearchDimensions = 1536, vectorSearchProfileName = "myprofile") public List vectorSearchField; } @Test public void vectorFieldMissingDimensions() { - RuntimeException ex = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(VectorFieldMissingDimensions.class, null)); + IllegalStateException ex = assertThrows(IllegalStateException.class, + () -> SearchIndexClient.buildSearchFields(VectorFieldMissingDimensions.class)); assertTrue(ex.getMessage().contains("Please specify both vectorSearchDimensions and vectorSearchProfile")); } @SuppressWarnings("unused") public static final class VectorFieldMissingDimensions { - @SearchableField(vectorSearchProfileName = "myprofile") + @BasicField(name = "vectorSearchField", vectorSearchProfileName = "myprofile") public List vectorSearchField; } @Test public void vectorFieldMissingProfile() { - RuntimeException ex = assertThrows(RuntimeException.class, - () -> SearchIndexClient.buildSearchFields(VectorFieldMissingProfile.class, null)); + IllegalStateException ex = assertThrows(IllegalStateException.class, + () -> SearchIndexClient.buildSearchFields(VectorFieldMissingProfile.class)); assertTrue(ex.getMessage().contains("Please specify both vectorSearchDimensions and vectorSearchProfile")); } @SuppressWarnings("unused") public static final class VectorFieldMissingProfile { - @SearchableField(vectorSearchDimensions = 1536) + @BasicField(name = "vectorSearchField", vectorSearchDimensions = 1536) public List vectorSearchField; } @@ -472,28 +499,27 @@ private void assertExceptionMassageAndDataType(Exception exception, SearchFieldD private List buildHotelCircularDependenciesModel() { SearchField homeAddress - = new SearchField("homeAddress", SearchFieldDataType.COMPLEX).setFields(buildHotelInAddress()); + = new SearchField("HomeAddress", SearchFieldDataType.COMPLEX).setFields(buildHotelInAddress()); SearchField billingAddress - = new SearchField("billingAddress", SearchFieldDataType.COMPLEX).setFields(buildHotelInAddress()); + = 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); + return Collections.singletonList(new SearchField("Hotel", SearchFieldDataType.COMPLEX)); } private List buildHotelWithArrayModel() { - SearchField hotelId = new SearchField("hotelId", SearchFieldDataType.STRING).setKey(true) + SearchField hotelId = new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true) .setSortable(true) .setStored(true) - .setHidden(false) + .setRetrievable(true) .setSearchable(false) .setFacetable(false) .setFilterable(false); SearchField tags - = new SearchField("tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setKey(false) - .setHidden(false) + = new SearchField("Tags", SearchFieldDataType.collection(SearchFieldDataType.STRING)).setKey(false) + .setRetrievable(true) .setStored(true) .setSearchable(true) .setSortable(false) 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 index 1eced9a0bda2..33bf42dec669 100644 --- 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 @@ -4,18 +4,18 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.rest.RequestOptions; import com.azure.core.http.rest.Response; import com.azure.core.test.TestMode; import com.azure.core.util.BinaryData; -import com.azure.core.util.Context; import com.azure.json.JsonProviders; import com.azure.json.JsonReader; import com.azure.search.documents.SearchClient; import com.azure.search.documents.SearchClientBuilder; -import com.azure.search.documents.SearchServiceVersion; 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.GetIndexStatisticsResult; import com.azure.search.documents.indexes.models.IndexStatisticsSummary; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; import com.azure.search.documents.indexes.models.MagnitudeScoringFunction; @@ -26,17 +26,19 @@ 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.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.SynonymMap; +import com.azure.search.documents.models.AutocompleteOptions; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.documents.models.QueryType; -import com.azure.search.documents.util.SearchPagedIterable; import com.azure.search.documents.models.SearchOptions; - +import com.azure.search.documents.models.SearchPagedIterable; +import com.azure.search.documents.models.SuggestOptions; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; @@ -56,6 +58,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; @@ -67,6 +70,8 @@ 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.createIndexAction; +import static com.azure.search.documents.TestHelpers.ifMatch; import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -89,7 +94,7 @@ public class IndexManagementTests extends SearchTestBase { @BeforeAll public static void setupSharedResources() { - sharedSynonymMap = new SynonymMap("sharedhotelmotel").setSynonyms("hotel,motel"); + sharedSynonymMap = new SynonymMap("sharedhotelmotel", Collections.singletonList("hotel,motel")); if (TEST_MODE == TestMode.PLAYBACK) { return; @@ -157,27 +162,33 @@ public void createAndGetIndexReturnsCorrectDefinitionAsync() { @Test public void createAndGetIndexReturnsCorrectDefinitionWithResponseSync() { SearchIndex index = createTestIndex("hotel2"); - Response createIndexResponse = client.createIndexWithResponse(index, Context.NONE); - indexesToDelete.add(createIndexResponse.getValue().getName()); + SearchIndex created + = client.createIndexWithResponse(BinaryData.fromObject(index), null).getValue().toObject(SearchIndex.class); + indexesToDelete.add(created.getName()); - assertObjectEquals(index, createIndexResponse.getValue(), true, "etag"); + assertObjectEquals(index, created, true, "etag"); - Response getIndexResponse = client.getIndexWithResponse(index.getName(), Context.NONE); - assertObjectEquals(index, getIndexResponse.getValue(), true, "etag"); + SearchIndex retrieved + = client.getIndexWithResponse(index.getName(), null).getValue().toObject(SearchIndex.class); + assertObjectEquals(index, retrieved, true, "etag"); } @Test public void createAndGetIndexReturnsCorrectDefinitionWithResponseAsync() { SearchIndex index = createTestIndex("hotel2"); - StepVerifier.create(asyncClient.createIndexWithResponse(index)).assertNext(response -> { - indexesToDelete.add(response.getValue().getName()); + StepVerifier.create(asyncClient.createIndexWithResponse(BinaryData.fromObject(index), null)) + .assertNext(response -> { + SearchIndex created = response.getValue().toObject(SearchIndex.class); + indexesToDelete.add(created.getName()); - assertObjectEquals(index, response.getValue(), true, "etag"); - }).verifyComplete(); + assertObjectEquals(index, created, true, "etag"); + }) + .verifyComplete(); - StepVerifier.create(asyncClient.getIndexWithResponse(index.getName())) - .assertNext(response -> assertObjectEquals(index, response.getValue(), true, "etag")) + StepVerifier.create(asyncClient.getIndexWithResponse(index.getName(), null)) + .assertNext( + response -> assertObjectEquals(index, response.getValue().toObject(SearchIndex.class), true, "etag")) .verifyComplete(); } @@ -214,10 +225,10 @@ public void createIndexReturnsCorrectDefaultValuesAsync() { @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); + SearchIndex index + = new SearchIndex(indexName, 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()); @@ -228,8 +239,8 @@ public void createIndexFailsWithUsefulMessageOnUserErrorSync() { @Test public void createIndexFailsWithUsefulMessageOnUserErrorAsync() { String indexName = HOTEL_INDEX_NAME; - SearchIndex index = new SearchIndex(indexName) - .setFields(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(false)); + SearchIndex index + = new SearchIndex(indexName, 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); @@ -259,22 +270,19 @@ public void deleteIndexIfNotChangedWorksOnlyOnCurrentResourceSync() { SearchIndex indexToCreate = createTestIndex(null); // Create the resource in the search service - SearchIndex originalIndex - = client.createOrUpdateIndexWithResponse(indexToCreate, false, false, Context.NONE).getValue(); + SearchIndex originalIndex = client.createOrUpdateIndexWithResponse(indexToCreate, null).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(); + SearchIndex updatedIndex = client + .createOrUpdateIndexWithResponse(originalIndex.setCorsOptions(new CorsOptions("https://test.com/")), null) + .getValue(); HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteIndexWithResponse(originalIndex, true, Context.NONE)); + () -> client.deleteIndexWithResponse(originalIndex.getName(), ifMatch(originalIndex.getETag()))); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - assertDoesNotThrow(() -> client.deleteIndexWithResponse(updatedIndex, true, Context.NONE)); + assertDoesNotThrow( + () -> client.deleteIndexWithResponse(updatedIndex.getName(), ifMatch(updatedIndex.getETag()))); } @Test @@ -282,51 +290,54 @@ public void deleteIndexIfNotChangedWorksOnlyOnCurrentResourceAsync() { SearchIndex indexToCreate = createTestIndex(null); // Create the resource in the search service - SearchIndex originalIndex = asyncClient.createOrUpdateIndexWithResponse(indexToCreate, false, false) + SearchIndex originalIndex = asyncClient.createOrUpdateIndexWithResponse(indexToCreate, null) .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) + SearchIndex updatedIndex = asyncClient + .createOrUpdateIndexWithResponse( + originalIndex.setCorsOptions(new CorsOptions(Collections.singletonList("https://test.com/"))), null) .map(Response::getValue) .block(); - StepVerifier.create(asyncClient.deleteIndexWithResponse(originalIndex, true)) + StepVerifier + .create(asyncClient.deleteIndexWithResponse(originalIndex.getName(), ifMatch(originalIndex.getETag()))) .verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); }); - StepVerifier.create(asyncClient.deleteIndexWithResponse(updatedIndex, true)) + StepVerifier + .create(asyncClient.deleteIndexWithResponse(updatedIndex.getName(), ifMatch(updatedIndex.getETag()))) .expectNextCount(1) .verifyComplete(); } @Test public void deleteIndexIfExistsWorksOnlyWhenResourceExistsSync() { - SearchIndex index - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); + SearchIndex index = client.createOrUpdateIndexWithResponse(createTestIndex(null), null).getValue(); - client.deleteIndexWithResponse(index, true, Context.NONE); + client.deleteIndexWithResponse(index.getName(), ifMatch(index.getETag())); // Try to delete again and expect to fail HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteIndexWithResponse(index, true, Context.NONE)); + () -> client.deleteIndexWithResponse(index.getName(), ifMatch(index.getETag()))); 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(); + Mono> mono + = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), null).flatMap(response -> { + SearchIndex index = response.getValue(); + return asyncClient.deleteIndexWithResponse(index.getName(), ifMatch(index.getETag())) + .then(asyncClient.deleteIndexWithResponse(index.getName(), ifMatch(index.getETag()))); + }); // Try to delete again and expect to fail - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, true)).verifyErrorSatisfies(throwable -> { + StepVerifier.create(mono).verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); }); @@ -334,41 +345,41 @@ public void deleteIndexIfExistsWorksOnlyWhenResourceExistsAsync() { @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); + SearchIndex index + = new SearchIndex(HOTEL_INDEX_NAME, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true)); + Response deleteResponse = client.deleteIndexWithResponse(index.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - Response createResponse = client.createIndexWithResponse(index, Context.NONE); + Response createResponse = client.createIndexWithResponse(BinaryData.fromObject(index), null); assertEquals(HttpURLConnection.HTTP_CREATED, createResponse.getStatusCode()); // Delete the same index twice - deleteResponse = client.deleteIndexWithResponse(index, false, Context.NONE); + deleteResponse = client.deleteIndexWithResponse(index.getName(), null); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, deleteResponse.getStatusCode()); - deleteResponse = client.deleteIndexWithResponse(index, false, Context.NONE); + deleteResponse = client.deleteIndexWithResponse(index.getName(), null); 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)); + SearchIndex index + = new SearchIndex(HOTEL_INDEX_NAME, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true)); - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, false)) + StepVerifier.create(asyncClient.deleteIndexWithResponse(index.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(asyncClient.createIndexWithResponse(index)) + StepVerifier.create(asyncClient.createIndexWithResponse(BinaryData.fromObject(index), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode())) .verifyComplete(); // Delete the same index twice - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, false)) + StepVerifier.create(asyncClient.deleteIndexWithResponse(index.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(asyncClient.deleteIndexWithResponse(index, false)) + StepVerifier.create(asyncClient.deleteIndexWithResponse(index.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); } @@ -411,7 +422,7 @@ public void canListIndexesWithSelectedFieldSyncAndAsync() { indexesToDelete.add(index2.getName()); Set expectedIndexNames = new HashSet<>(Arrays.asList(index1.getName(), index2.getName())); - Set actualIndexNames = client.listIndexNames(Context.NONE).stream().collect(Collectors.toSet()); + Set actualIndexNames = client.listIndexNames().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. @@ -424,9 +435,9 @@ public void canListIndexesWithSelectedFieldSyncAndAsync() { @Test public void canAddSynonymFieldPropertySync() { - SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME).setFields(Arrays.asList( + SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSynonymMapNames(sharedSynonymMap.getName()))); + new SearchField("HotelName", SearchFieldDataType.STRING).setSynonymMapNames(sharedSynonymMap.getName())); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -438,9 +449,9 @@ public void canAddSynonymFieldPropertySync() { @Test public void canAddSynonymFieldPropertyAsync() { - SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME).setFields(Arrays.asList( + SearchIndex index = new SearchIndex(HOTEL_INDEX_NAME, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSynonymMapNames(sharedSynonymMap.getName()))); + new SearchField("HotelName", SearchFieldDataType.STRING).setSynonymMapNames(sharedSynonymMap.getName())); StepVerifier.create(asyncClient.createIndex(index)).assertNext(createdIndex -> { indexesToDelete.add(createdIndex.getName()); @@ -466,7 +477,7 @@ public void canUpdateSynonymFieldPropertySync() { hotelNameField.setSynonymMapNames(Collections.emptyList()); SearchIndex updatedIndex - = client.createOrUpdateIndexWithResponse(existingIndex, true, false, Context.NONE).getValue(); + = client.createOrUpdateIndexWithResponse(existingIndex, ifMatch(existingIndex.getETag())).getValue(); assertObjectEquals(existingIndex, updatedIndex, true, "etag", "@odata.etag"); } @@ -484,7 +495,7 @@ public void canUpdateSynonymFieldPropertyAsync() { = asyncClient.getIndex(index.getName()).flatMap(existingIndex -> { getFieldByName(existingIndex, "HotelName").setSynonymMapNames(Collections.emptyList()); - return asyncClient.createOrUpdateIndexWithResponse(existingIndex, true, false) + return asyncClient.createOrUpdateIndexWithResponse(existingIndex, ifMatch(existingIndex.getETag())) .map(response -> Tuples.of(existingIndex, response.getValue())); }); @@ -520,7 +531,7 @@ public void canUpdateIndexDefinitionSync() { SearchIndex existingIndex = client.getIndex(fullFeaturedIndex.getName()); SearchField tagsField = getFieldByName(existingIndex, "Description_Custom"); - tagsField.setHidden(true) + tagsField.setRetrievable(false) .setSearchAnalyzerName(LexicalAnalyzerName.WHITESPACE) .setSynonymMapNames(sharedSynonymMap.getName()); @@ -530,9 +541,10 @@ public void canUpdateIndexDefinitionSync() { existingIndex.getFields().add(hotelWebSiteField); SearchField hotelNameField = getFieldByName(existingIndex, "HotelName"); - hotelNameField.setHidden(true); + hotelNameField.setRetrievable(false); - updatedIndex = client.createOrUpdateIndexWithResponse(existingIndex, true, false, Context.NONE).getValue(); + updatedIndex + = client.createOrUpdateIndexWithResponse(existingIndex, ifMatch(existingIndex.getETag())).getValue(); assertObjectEquals(existingIndex, updatedIndex, true, "etag", "@odata.etag"); } @@ -567,7 +579,7 @@ public void canUpdateIndexDefinitionAsync() { .orElseThrow(NoSuchElementException::new); SearchField tagsField = getFieldByName(existingIndex, "Description_Custom"); - tagsField.setHidden(true) + tagsField.setRetrievable(false) .setSearchAnalyzerName(LexicalAnalyzerName.WHITESPACE) .setSynonymMapNames(sharedSynonymMap.getName()); @@ -577,9 +589,10 @@ public void canUpdateIndexDefinitionAsync() { existingIndex.getFields().add(hotelWebSiteField); SearchField hotelNameField = getFieldByName(existingIndex, "HotelName"); - hotelNameField.setHidden(true); + hotelNameField.setRetrievable(false); - StepVerifier.create(asyncClient.createOrUpdateIndexWithResponse(existingIndex, true, false)) + StepVerifier + .create(asyncClient.createOrUpdateIndexWithResponse(existingIndex, ifMatch(existingIndex.getETag()))) .assertNext(response -> assertObjectEquals(existingIndex, response.getValue(), true, "etag", "@odata.etag")) .verifyComplete(); } @@ -598,7 +611,7 @@ public void canUpdateSuggesterWithNewIndexFieldsSync() { existingIndex.setSuggesters(new SearchSuggester("Suggestion", Arrays.asList("HotelAmenities", "HotelRewards"))); SearchIndex updatedIndex - = client.createOrUpdateIndexWithResponse(existingIndex, true, false, Context.NONE).getValue(); + = client.createOrUpdateIndexWithResponse(existingIndex, ifMatch(existingIndex.getETag())).getValue(); assertObjectEquals(existingIndex, updatedIndex, true, "etag", "@odata.etag"); } @@ -612,7 +625,7 @@ public void canUpdateSuggesterWithNewIndexFieldsAsync() { new SearchField("HotelRewards", SearchFieldDataType.STRING))); index.setSuggesters(new SearchSuggester("Suggestion", Arrays.asList("HotelAmenities", "HotelRewards"))); - return asyncClient.createOrUpdateIndexWithResponse(index, true, false) + return asyncClient.createOrUpdateIndexWithResponse(index, ifMatch(index.getETag())) .map(response -> Tuples.of(index, response.getValue())); }); @@ -679,7 +692,7 @@ public void createOrUpdateIndexCreatesWhenIndexDoesNotExistAsync() { public void createOrUpdateIndexCreatesWhenIndexDoesNotExistWithResponseSync() { SearchIndex expected = createTestIndex(null); - SearchIndex actual = client.createOrUpdateIndexWithResponse(expected, false, false, Context.NONE).getValue(); + SearchIndex actual = client.createOrUpdateIndexWithResponse(expected, null).getValue(); indexesToDelete.add(actual.getName()); assertObjectEquals(expected, actual, true, "etag"); } @@ -688,7 +701,7 @@ public void createOrUpdateIndexCreatesWhenIndexDoesNotExistWithResponseSync() { public void createOrUpdateIndexCreatesWhenIndexDoesNotExistWithResponseAsync() { Function>> createAndValidateFunction = indexName -> { SearchIndex expected = createTestIndex(indexName); - return asyncClient.createOrUpdateIndexWithResponse(expected, false, false) + return asyncClient.createOrUpdateIndexWithResponse(expected, null) .map(response -> Tuples.of(expected, response.getValue())); }; @@ -701,7 +714,10 @@ public void createOrUpdateIndexCreatesWhenIndexDoesNotExistWithResponseAsync() { @Test public void createOrUpdateIndexIfNotExistsSucceedsOnNoResourceSync() { SearchIndex index - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, true, Context.NONE).getValue(); + = client + .createOrUpdateIndexWithResponse(createTestIndex(null), + new RequestOptions().addQueryParam("allowIndexDowntime", "true")) + .getValue(); indexesToDelete.add(index.getName()); assertNotNull(index.getETag()); @@ -709,23 +725,20 @@ public void createOrUpdateIndexIfNotExistsSucceedsOnNoResourceSync() { @Test public void createOrUpdateIndexIfNotExistsSucceedsOnNoResourceAsync() { - StepVerifier.create(asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, true)) - .assertNext(response -> { + StepVerifier.create(asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), + new RequestOptions().addQueryParam("allowIndexDowntime", "true"))).assertNext(response -> { indexesToDelete.add(response.getValue().getName()); assertNotNull(response.getValue().getETag()); - }) - .verifyComplete(); + }).verifyComplete(); } @Test public void createOrUpdateIndexIfExistsSucceedsOnExistingResourceSync() { - SearchIndex original - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); + SearchIndex original = client.createOrUpdateIndexWithResponse(createTestIndex(null), null).getValue(); indexesToDelete.add(original.getName()); SearchIndex updated - = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, false, Context.NONE) - .getValue(); + = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), null).getValue(); validateETagUpdate(original.getETag(), updated.getETag()); } @@ -733,12 +746,12 @@ public void createOrUpdateIndexIfExistsSucceedsOnExistingResourceSync() { @Test public void createOrUpdateIndexIfExistsSucceedsOnExistingResourceAsync() { Mono> createThenUpdateMono - = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false).flatMap(response -> { + = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), null).flatMap(response -> { SearchIndex original = response.getValue(); String originalETag = original.getETag(); indexesToDelete.add(original.getName()); - return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, false) + return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), null) .map(update -> Tuples.of(originalETag, update.getValue().getETag())); }); @@ -749,12 +762,13 @@ public void createOrUpdateIndexIfExistsSucceedsOnExistingResourceAsync() { @Test public void createOrUpdateIndexIfNotChangedSucceedsWhenResourceUnchangedSync() { - SearchIndex original - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); + SearchIndex original = client.createOrUpdateIndexWithResponse(createTestIndex(null), null).getValue(); indexesToDelete.add(original.getName()); String updatedETag - = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true, Context.NONE) + = client + .createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), + new RequestOptions().addQueryParam("allowIndexDowntime", "true")) .getValue() .getETag(); @@ -764,12 +778,14 @@ public void createOrUpdateIndexIfNotChangedSucceedsWhenResourceUnchangedSync() { @Test public void createOrUpdateIndexIfNotChangedSucceedsWhenResourceUnchangedAsync() { Mono> createThenUpdateMono - = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false).flatMap(response -> { + = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), null).flatMap(response -> { SearchIndex original = response.getValue(); String originalETag = original.getETag(); indexesToDelete.add(original.getName()); - return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true) + return asyncClient + .createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), + new RequestOptions().addQueryParam("allowIndexDowntime", "true")) .map(update -> Tuples.of(originalETag, update.getValue().getETag())); }); @@ -780,17 +796,19 @@ public void createOrUpdateIndexIfNotChangedSucceedsWhenResourceUnchangedAsync() @Test public void createOrUpdateIndexIfNotChangedFailsWhenResourceChangedSync() { - SearchIndex original - = client.createOrUpdateIndexWithResponse(createTestIndex(null), false, false, Context.NONE).getValue(); + SearchIndex original = client.createOrUpdateIndexWithResponse(createTestIndex(null), null).getValue(); indexesToDelete.add(original.getName()); String updatedETag - = client.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true, Context.NONE) + = client + .createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), + new RequestOptions().addQueryParam("allowIndexDowntime", "true")) .getValue() .getETag(); HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.createOrUpdateIndexWithResponse(original, false, true, Context.NONE), + () -> client.createOrUpdateIndexWithResponse(original, + ifMatch(original.getETag()).addQueryParam("allowIndexDowntime", "true")), "createOrUpdateDefinition should have failed due to precondition."); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); @@ -801,16 +819,19 @@ public void createOrUpdateIndexIfNotChangedFailsWhenResourceChangedSync() { @Test public void createOrUpdateIndexIfNotChangedFailsWhenResourceChangedAsync() { Mono> createUpdateThenFailUpdateMono - = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), false, false).flatMap(response -> { + = asyncClient.createOrUpdateIndexWithResponse(createTestIndex(null), null).flatMap(response -> { SearchIndex original = response.getValue(); String originalETag = original.getETag(); indexesToDelete.add(original.getName()); - return asyncClient.createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), false, true) + return asyncClient + .createOrUpdateIndexWithResponse(mutateCorsOptionsInIndex(original), + new RequestOptions().addQueryParam("allowIndexDowntime", "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)); + .flatMap(original -> asyncClient.createOrUpdateIndexWithResponse(original.getT3(), + ifMatch(original.getT1()).addQueryParam("allowIndexDowntime", "true"))); StepVerifier.create(createUpdateThenFailUpdateMono).verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); @@ -824,14 +845,15 @@ public void canCreateAndGetIndexStatsSync() { client.createOrUpdateIndex(index); indexesToDelete.add(index.getName()); - SearchIndexStatistics indexStatistics = client.getIndexStatistics(index.getName()); + GetIndexStatisticsResult 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()); + indexStatistics = client.getIndexStatisticsWithResponse(index.getName(), null) + .getValue() + .toObject(GetIndexStatisticsResult.class); + assertEquals(0, indexStatistics.getDocumentCount()); + assertEquals(0, indexStatistics.getStorageSize()); } @Test @@ -845,12 +867,11 @@ public void canCreateAndGetIndexStatsAsync() { assertEquals(0, indexStatistics.getStorageSize()); }).verifyComplete(); - StepVerifier.create(asyncClient.getIndexStatisticsWithResponse(index.getName())) - .assertNext(indexStatisticsResponse -> { - assertEquals(0, indexStatisticsResponse.getValue().getDocumentCount()); - assertEquals(0, indexStatisticsResponse.getValue().getStorageSize()); - }) - .verifyComplete(); + StepVerifier.create(asyncClient.getIndexStatisticsWithResponse(index.getName(), null)).assertNext(response -> { + GetIndexStatisticsResult indexStatistics = response.getValue().toObject(GetIndexStatisticsResult.class); + assertEquals(0, indexStatistics.getDocumentCount()); + assertEquals(0, indexStatistics.getStorageSize()); + }).verifyComplete(); } @Test @@ -858,14 +879,14 @@ public void canCreateAndGetIndexStatsAsync() { public void canCreateAndGetIndexStatsSummarySync() { List indexNames = new ArrayList<>(); - assertFalse(client.getIndexStatsSummary().stream().findAny().isPresent(), "Unexpected index stats summary."); + assertFalse(client.listIndexStatsSummary().stream().findAny().isPresent(), "Unexpected index stats summary."); SearchIndex index = createTestIndex(null); indexNames.add(index.getName()); client.createOrUpdateIndex(index); indexesToDelete.add(index.getName()); - assertEquals(1, client.getIndexStatsSummary().stream().count()); + assertEquals(1, client.listIndexStatsSummary().stream().count()); for (int i = 0; i < 4; i++) { index = createTestIndex(null); @@ -875,7 +896,7 @@ public void canCreateAndGetIndexStatsSummarySync() { } List returnedNames - = client.getIndexStatsSummary().stream().map(IndexStatisticsSummary::getName).collect(Collectors.toList()); + = client.listIndexStatsSummary().stream().map(IndexStatisticsSummary::getName).collect(Collectors.toList()); assertEquals(5, returnedNames.size()); for (String name : indexNames) { @@ -891,14 +912,14 @@ public void canCreateAndGetIndexStatsSummaryAsync() { List indexNames = new ArrayList<>(); - StepVerifier.create(asyncClient.getIndexStatsSummary()).expectNextCount(0).verifyComplete(); + StepVerifier.create(asyncClient.listIndexStatsSummary()).expectNextCount(0).verifyComplete(); SearchIndex index = createTestIndex(null); indexNames.add(index.getName()); asyncClient.createOrUpdateIndex(index).block(); indexesToDelete.add(index.getName()); - StepVerifier.create(asyncClient.getIndexStatsSummary()).expectNextCount(1).verifyComplete(); + StepVerifier.create(asyncClient.listIndexStatsSummary()).expectNextCount(1).verifyComplete(); for (int i = 0; i < 4; i++) { index = createTestIndex(null); @@ -907,7 +928,7 @@ public void canCreateAndGetIndexStatsSummaryAsync() { indexesToDelete.add(index.getName()); } - StepVerifier.create(asyncClient.getIndexStatsSummary().map(IndexStatisticsSummary::getName).collectList()) + StepVerifier.create(asyncClient.listIndexStatsSummary().map(IndexStatisticsSummary::getName).collectList()) .assertNext(returnedNames -> { assertEquals(5, returnedNames.size()); @@ -922,14 +943,13 @@ public void canCreateAndGetIndexStatsSummaryAsync() { @Test public void canCreateIndexWithProductScoringAggregationSync() { - SearchIndex index = new SearchIndex(randomIndexName("product-scoring-index")) - .setFields(Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("title", SearchFieldDataType.STRING).setSearchable(true), - new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true))) - .setScoringProfiles(Arrays.asList( + SearchIndex index = new SearchIndex(randomIndexName("product-scoring-index"), + new SearchField("id", SearchFieldDataType.STRING).setKey(true), + new SearchField("title", SearchFieldDataType.STRING).setSearchable(true), + new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true)).setScoringProfiles( new ScoringProfile("productScoringProfile").setFunctionAggregation(ScoringFunctionAggregation.PRODUCT) - .setFunctions(Arrays.asList( - new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))))); + .setFunctions( + new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -940,14 +960,13 @@ public void canCreateIndexWithProductScoringAggregationSync() { @Test public void canCreateIndexWithProductScoringAggregationAsync() { - SearchIndex index = new SearchIndex(randomIndexName("product-scoring-index")) - .setFields(Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("title", SearchFieldDataType.STRING).setSearchable(true), - new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true))) - .setScoringProfiles(Arrays.asList( + SearchIndex index = new SearchIndex(randomIndexName("product-scoring-index"), + new SearchField("id", SearchFieldDataType.STRING).setKey(true), + new SearchField("title", SearchFieldDataType.STRING).setSearchable(true), + new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true)).setScoringProfiles( new ScoringProfile("productScoringProfile").setFunctionAggregation(ScoringFunctionAggregation.PRODUCT) - .setFunctions(Arrays.asList( - new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))))); + .setFunctions( + new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))); StepVerifier.create(asyncClient.createIndex(index)).assertNext(createdIndex -> { indexesToDelete.add(createdIndex.getName()); @@ -958,7 +977,7 @@ public void canCreateIndexWithProductScoringAggregationAsync() { @Test public void readIndexWithProductScoringAggregationSync() { - SearchIndex index = createIndexWithScoringAggregation("read-test"); + SearchIndex index = createIndexWithScoringAggregation(); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -971,7 +990,7 @@ public void readIndexWithProductScoringAggregationSync() { @Test public void readIndexWithProductScoringAggregationAsync() { - SearchIndex index = createIndexWithScoringAggregation("read-test"); + SearchIndex index = createIndexWithScoringAggregation(); Mono> createAndRetrieveMono = asyncClient.createIndex(index).flatMap(createdIndex -> { @@ -992,13 +1011,12 @@ public void readIndexWithProductScoringAggregationAsync() { @Test public void updateIndexWithProductScoringAggregationSync() { - SearchIndex index = new SearchIndex(randomIndexName("update-test")) - .setFields(Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true))) - .setScoringProfiles( - Arrays.asList(new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.SUM) // Start with SUM - .setFunctions(Arrays.asList( - new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))))); + SearchIndex index = new SearchIndex(randomIndexName("update-test"), + new SearchField("id", SearchFieldDataType.STRING).setKey(true), + new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true)).setScoringProfiles( + new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.SUM) + .setFunctions( + new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -1013,13 +1031,12 @@ public void updateIndexWithProductScoringAggregationSync() { @Test public void updateIndexWithProductScoringAggregationAsync() { - SearchIndex index = new SearchIndex(randomIndexName("update-test")) - .setFields(Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true))) - .setScoringProfiles( - Arrays.asList(new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.SUM) - .setFunctions(Arrays.asList( - new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))))); + SearchIndex index = new SearchIndex(randomIndexName("update-test"), + new SearchField("id", SearchFieldDataType.STRING).setKey(true), + new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true)).setScoringProfiles( + new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.SUM) + .setFunctions( + new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))); Mono> createAndUpdateMono = asyncClient.createIndex(index).flatMap(createdIndex -> { @@ -1039,7 +1056,7 @@ public void updateIndexWithProductScoringAggregationAsync() { @Test public void deleteIndexWithProductScoringAggregationSync() { - SearchIndex index = createIndexWithScoringAggregation("delete-test"); + SearchIndex index = createIndexWithScoringAggregation(); indexesToDelete.add(index.getName()); ScoringProfile profile = index.getScoringProfiles().get(0); @@ -1051,7 +1068,7 @@ public void deleteIndexWithProductScoringAggregationSync() { @Test public void deleteIndexWithProductScoringAggregationAsync() { - SearchIndex index = createIndexWithScoringAggregation("delete-test"); + SearchIndex index = createIndexWithScoringAggregation(); Mono createAndDeleteMono = asyncClient.createIndex(index).flatMap(createdIndex -> { indexesToDelete.add(createdIndex.getName()); @@ -1059,7 +1076,7 @@ public void deleteIndexWithProductScoringAggregationAsync() { assertEquals(ScoringFunctionAggregation.PRODUCT, profile.getFunctionAggregation()); return asyncClient.deleteIndex(createdIndex.getName()) - .doOnSuccess(unused -> indexesToDelete.remove(createdIndex.getName())); + .doOnSuccess(ignored -> indexesToDelete.remove(createdIndex.getName())); }); StepVerifier.create(createAndDeleteMono).verifyComplete(); @@ -1067,7 +1084,7 @@ public void deleteIndexWithProductScoringAggregationAsync() { @Test public void testProductScoringAggregationApiVersionCompatibility() { - SearchIndex index = createIndexWithScoringAggregation("api-version-test"); + SearchIndex index = createIndexWithScoringAggregation(); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -1075,26 +1092,24 @@ public void testProductScoringAggregationApiVersionCompatibility() { assertEquals(ScoringFunctionAggregation.PRODUCT, profile.getFunctionAggregation()); } - @Test - public void testProductScoringAggregationWithOlderApiVersions() { - SearchIndexClient olderApiClient - = getSearchIndexClientBuilder(true).serviceVersion(SearchServiceVersion.V2023_11_01).buildClient(); - - SearchIndex index = createIndexWithScoringAggregation("older-api-test"); - - HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { - olderApiClient.createIndex(index); - }); - - assertEquals(400, exception.getResponse().getStatusCode()); - } + // @Test + // public void testProductScoringAggregationWithOlderApiVersions() { + // SearchIndexClient olderApiClient + // = getSearchIndexClientBuilder(true).serviceVersion(SearchServiceVersion.V2023_11_01).buildClient(); + // + // SearchIndex index = createIndexWithScoringAggregation("older-api-test"); + // + // HttpResponseException exception = assertThrows(HttpResponseException.class, + // () -> olderApiClient.createIndex(index)); + // + // assertEquals(400, exception.getResponse().getStatusCode()); + // } @Test public void testProductScoringAggregationSerialization() { - ScoringProfile profile = new ScoringProfile("testProfile") - .setFunctionAggregation(ScoringFunctionAggregation.PRODUCT) - .setFunctions( - Arrays.asList(new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))); + ScoringProfile profile + = new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.PRODUCT) + .setFunctions(new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0))); String json = BinaryData.fromObject(profile).toString(); assertTrue(json.contains("\"functionAggregation\":\"product\"")); @@ -1115,24 +1130,23 @@ public void testProductScoringAggregationDeserialization() { } } - private SearchIndex createIndexWithScoringAggregation(String suffix) { - return new SearchIndex(randomIndexName("agg-test")) - .setFields(Arrays.asList(new SearchField("id", SearchFieldDataType.STRING).setKey(true), - new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true))) - .setScoringProfiles(Arrays - .asList(new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.PRODUCT) - .setFunctions(Arrays.asList( - new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))))); + private SearchIndex createIndexWithScoringAggregation() { + return new SearchIndex(randomIndexName("agg-test"), + new SearchField("id", SearchFieldDataType.STRING).setKey(true), + new SearchField("rating", SearchFieldDataType.DOUBLE).setFilterable(true)).setScoringProfiles( + new ScoringProfile("testProfile").setFunctionAggregation(ScoringFunctionAggregation.PRODUCT) + .setFunctions( + new MagnitudeScoringFunction("rating", 2.0, new MagnitudeScoringParameters(1.0, 5.0)))); } @Test public void createIndexWithPurviewEnabledSucceeds() { String indexName = randomIndexName("purview-enabled-index"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true), new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) - .setSensitivityLabel(true))); + .setSensitivityLabel(true)).setPurviewEnabled(true); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -1147,13 +1161,11 @@ public void createIndexWithPurviewEnabledSucceeds() { @Test public void createIndexWithPurviewEnabledRequiresSensitivityLabelField() { String indexName = randomIndexName("purview-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true))); + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true)).setPurviewEnabled(true); - HttpResponseException exception = assertThrows(HttpResponseException.class, () -> { - client.createIndex(index); - }); + HttpResponseException exception = assertThrows(HttpResponseException.class, () -> client.createIndex(index)); assertEquals(400, exception.getResponse().getStatusCode()); assertTrue(exception.getMessage().toLowerCase().contains("sensitivity") @@ -1164,10 +1176,10 @@ public void createIndexWithPurviewEnabledRequiresSensitivityLabelField() { @Disabled("Uses System.getenv; requires specific environment setup") public void purviewEnabledIndexRejectsApiKeyAuth() { String indexName = randomIndexName("purview-api-key-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) - .setSensitivityLabel(true))); + .setSensitivityLabel(true)).setPurviewEnabled(true); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -1179,9 +1191,8 @@ public void purviewEnabledIndexRejectsApiKeyAuth() { .indexName(createdIndex.getName()) .buildClient(); - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> { - apiKeyClient.search("*").iterator().hasNext(); - }); + HttpResponseException ex = assertThrows(HttpResponseException.class, + () -> apiKeyClient.search(new SearchOptions()).iterator().hasNext()); assertTrue(ex.getResponse().getStatusCode() == 401 || ex.getResponse().getStatusCode() == 403 @@ -1191,36 +1202,33 @@ public void purviewEnabledIndexRejectsApiKeyAuth() { @Test public void purviewEnabledIndexDisablesAutocompleteAndSuggest() { String indexName = randomIndexName("purview-suggest-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true), new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) - .setSensitivityLabel(true))) - .setSuggesters( - Collections.singletonList(new SearchSuggester("sg", Collections.singletonList("HotelName")))); + .setSensitivityLabel(true)).setPurviewEnabled(true) + .setSuggesters(new SearchSuggester("sg", Collections.singletonList("HotelName"))); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); SearchClient searchClient = getSearchClientBuilder(createdIndex.getName(), true).buildClient(); - HttpResponseException ex1 = assertThrows(HttpResponseException.class, () -> { - searchClient.autocomplete("test", "sg").iterator().hasNext(); - }); + HttpResponseException ex1 = assertThrows(HttpResponseException.class, + () -> searchClient.autocomplete(new AutocompleteOptions("test", "sg"))); assertTrue(ex1.getResponse().getStatusCode() == 400 || ex1.getResponse().getStatusCode() == 403); - HttpResponseException ex2 = assertThrows(HttpResponseException.class, () -> { - searchClient.suggest("test", "sg").iterator().hasNext(); - }); + HttpResponseException ex2 + = assertThrows(HttpResponseException.class, () -> searchClient.suggest(new SuggestOptions("test", "sg"))); assertTrue(ex2.getResponse().getStatusCode() == 400 || ex2.getResponse().getStatusCode() == 403); } @Test public void cannotTogglePurviewEnabledAfterCreation() { String indexName = randomIndexName("purview-toggle-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(false) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), - new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true))); + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true)).setPurviewEnabled(false); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -1230,9 +1238,8 @@ public void cannotTogglePurviewEnabledAfterCreation() { .add(new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) .setSensitivityLabel(true)); - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> { - client.createOrUpdateIndex(createdIndex); - }); + HttpResponseException ex + = assertThrows(HttpResponseException.class, () -> client.createOrUpdateIndex(createdIndex)); assertEquals(400, ex.getResponse().getStatusCode()); assertTrue(ex.getMessage().toLowerCase().contains("immutable") @@ -1243,10 +1250,10 @@ public void cannotTogglePurviewEnabledAfterCreation() { @Test public void cannotModifySensitivityLabelFieldAfterCreation() { String indexName = randomIndexName("purview-field-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) - .setSensitivityLabel(true))); + .setSensitivityLabel(true)).setPurviewEnabled(true); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); @@ -1257,9 +1264,8 @@ public void cannotModifySensitivityLabelFieldAfterCreation() { .findFirst() .ifPresent(f -> f.setSensitivityLabel(false)); - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> { - client.createOrUpdateIndex(createdIndex); - }); + HttpResponseException ex + = assertThrows(HttpResponseException.class, () -> client.createOrUpdateIndex(createdIndex)); assertEquals(400, ex.getResponse().getStatusCode()); assertTrue(ex.getMessage().toLowerCase().contains("immutable") @@ -1269,56 +1275,55 @@ public void cannotModifySensitivityLabelFieldAfterCreation() { @Test public void purviewEnabledIndexSupportsBasicSearch() { String indexName = randomIndexName("purview-search-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true), new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) - .setSensitivityLabel(true))); + .setSensitivityLabel(true)).setPurviewEnabled(true); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); SearchClient searchClient = getSearchClientBuilder(createdIndex.getName(), true).buildClient(); - List> documents = Arrays.asList(createTestDocument("1", "Test Hotel", "Public")); - searchClient.uploadDocuments(documents); + Map document = createTestDocument(); + searchClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, document))); waitForIndexing(); - SearchPagedIterable results = searchClient.search("Test"); + SearchPagedIterable results = searchClient.search(new SearchOptions().setSearchText("Test")); assertNotNull(results); // getTotalCount() can be null, so check for non-null or use iterator - Long totalCount = results.getTotalCount(); + Long totalCount = results.iterableByPage().iterator().next().getCount(); assertTrue(totalCount == null || totalCount >= 0); - - // Verify we can iterate over results without errors - assertNotNull(results.iterator()); } @Test public void purviewEnabledIndexSupportsSemanticSearch() { String indexName = randomIndexName("purview-semantic-test"); - SearchIndex index = new SearchIndex(indexName).setPurviewEnabled(true) - .setFields(Arrays.asList(new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), + SearchIndex index + = new SearchIndex(indexName, new SearchField("HotelId", SearchFieldDataType.STRING).setKey(true), new SearchField("HotelName", SearchFieldDataType.STRING).setSearchable(true), new SearchField("SensitivityLabel", SearchFieldDataType.STRING).setFilterable(true) - .setSensitivityLabel(true))) - .setSemanticSearch(new SemanticSearch().setDefaultConfigurationName("semantic") - .setConfigurations(Collections.singletonList(new SemanticConfiguration("semantic", - new SemanticPrioritizedFields().setContentFields(new SemanticField("HotelName")))))); + .setSensitivityLabel(true)) + .setPurviewEnabled(true) + .setSemanticSearch(new SemanticSearch().setDefaultConfigurationName("semantic") + .setConfigurations(new SemanticConfiguration("semantic", + new SemanticPrioritizedFields().setContentFields(new SemanticField("HotelName"))))); SearchIndex createdIndex = client.createIndex(index); indexesToDelete.add(createdIndex.getName()); SearchClient searchClient = getSearchClientBuilder(createdIndex.getName(), true).buildClient(); - List> documents = Arrays.asList(createTestDocument("1", "Test Hotel", "Public")); - searchClient.uploadDocuments(documents); + Map document = createTestDocument(); + searchClient.indexDocuments(new IndexDocumentsBatch(createIndexAction(IndexActionType.UPLOAD, document))); waitForIndexing(); - SearchOptions searchOptions = new SearchOptions().setQueryType(QueryType.SEMANTIC); + SearchOptions searchOptions = new SearchOptions().setSearchText("Test").setQueryType(QueryType.SEMANTIC); - SearchPagedIterable results = searchClient.search("Test", searchOptions, null); + SearchPagedIterable results = searchClient.search(searchOptions); assertNotNull(results); + results.iterableByPage().iterator().next(); } static SearchIndex mutateCorsOptionsInIndex(SearchIndex index) { @@ -1343,11 +1348,11 @@ static SearchField getFieldByName(SearchIndex index, String name) { "Unable to find a field with name '" + name + "' in index '" + index.getName() + "'."); } - private Map createTestDocument(String id, String hotelName, String sensitivityLabel) { - Map document = new HashMap<>(); - document.put("HotelId", id); - document.put("HotelName", hotelName); - document.put("SensitivityLabel", sensitivityLabel); + private Map createTestDocument() { + Map document = new LinkedHashMap<>(); + document.put("HotelId", "1"); + document.put("HotelName", "Test Hotel"); + document.put("SensitivityLabel", "Public"); return document; } 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 index 1c282fa3188e..d45995f78d28 100644 --- 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 @@ -6,14 +6,17 @@ 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.core.util.BinaryData; import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.TestHelpers; +import com.azure.search.documents.indexes.models.BlobIndexerDataToExtract; +import com.azure.search.documents.indexes.models.DataSourceCredentials; 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.IndexingParametersConfiguration; import com.azure.search.documents.indexes.models.IndexingSchedule; import com.azure.search.documents.indexes.models.InputFieldMappingEntry; import com.azure.search.documents.indexes.models.OcrSkill; @@ -54,6 +57,7 @@ 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.ifMatch; import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -61,7 +65,6 @@ 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"; @@ -138,7 +141,8 @@ public static void setupSharedResources() { .buildClient(); sharedSkillset = sharedIndexerClient.createSkillset(sharedSkillset); - sharedDatasource = sharedIndexerClient.createOrUpdateDataSourceConnection(sharedDatasource); + sharedDatasource + = sharedIndexerClient.createOrUpdateDataSourceConnection(sharedDatasource.getName(), sharedDatasource); sharedIndex = sharedIndexClient.createIndex(sharedIndex); } @@ -218,8 +222,10 @@ public void canCreateAndListIndexersSync() { expectedIndexers.put(indexer1.getName(), indexer1); expectedIndexers.put(indexer2.getName(), indexer2); - Map actualIndexers - = searchIndexerClient.listIndexers().stream().collect(Collectors.toMap(SearchIndexer::getName, si -> si)); + Map actualIndexers = searchIndexerClient.listIndexers() + .getIndexers() + .stream() + .collect(Collectors.toMap(SearchIndexer::getName, si -> si)); compareMaps(expectedIndexers, actualIndexers, (expected, actual) -> assertObjectEquals(expected, actual, true, "etag")); @@ -245,8 +251,8 @@ public void canCreateAndListIndexersAsync() { expectedIndexers.put(indexer1.getName(), indexer1); expectedIndexers.put(indexer2.getName(), indexer2); - Mono> listMono - = searchIndexerAsyncClient.listIndexers().collect(Collectors.toMap(SearchIndexer::getName, si -> si)); + Mono> listMono = searchIndexerAsyncClient.listIndexers() + .map(result -> result.getIndexers().stream().collect(Collectors.toMap(SearchIndexer::getName, si -> si))); StepVerifier.create(listMono) .assertNext(actualIndexers -> compareMaps(expectedIndexers, actualIndexers, @@ -291,7 +297,7 @@ public void canCreateAndListIndexerNamesAsync() { Set expectedIndexers = new HashSet<>(Arrays.asList(indexer1.getName(), indexer2.getName())); - StepVerifier.create(searchIndexerAsyncClient.listIndexerNames().collect(Collectors.toSet())) + StepVerifier.create(searchIndexerAsyncClient.listIndexerNames().map(HashSet::new)) .assertNext(actualIndexers -> { assertEquals(expectedIndexers.size(), actualIndexers.size()); assertTrue(actualIndexers.containsAll(expectedIndexers)); @@ -343,9 +349,11 @@ public void canResetIndexerAndGetIndexerStatusAsync() { public void canResetIndexerAndGetIndexerStatusWithResponseSync() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - searchIndexerClient.resetIndexerWithResponse(indexer.getName(), Context.NONE); + searchIndexerClient.resetIndexerWithResponse(indexer.getName(), null); SearchIndexerStatus indexerStatusResponse - = searchIndexerClient.getIndexerStatusWithResponse(indexer.getName(), Context.NONE).getValue(); + = searchIndexerClient.getIndexerStatusWithResponse(indexer.getName(), null) + .getValue() + .toObject(SearchIndexerStatus.class); assertEquals(IndexerStatus.RUNNING, indexerStatusResponse.getStatus()); assertEquals(IndexerExecutionStatus.RESET, indexerStatusResponse.getLastResult().getStatus()); } @@ -354,12 +362,13 @@ public void canResetIndexerAndGetIndexerStatusWithResponseSync() { public void canResetIndexerAndGetIndexerStatusWithResponseAsync() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - searchIndexerAsyncClient.resetIndexerWithResponse(indexer.getName()).block(); + searchIndexerAsyncClient.resetIndexerWithResponse(indexer.getName(), null).block(); - StepVerifier.create(searchIndexerAsyncClient.getIndexerStatusWithResponse(indexer.getName())) + StepVerifier.create(searchIndexerAsyncClient.getIndexerStatusWithResponse(indexer.getName(), null)) .assertNext(response -> { - assertEquals(IndexerStatus.RUNNING, response.getValue().getStatus()); - assertEquals(IndexerExecutionStatus.RESET, response.getValue().getLastResult().getStatus()); + SearchIndexerStatus indexerStatus = response.getValue().toObject(SearchIndexerStatus.class); + assertEquals(IndexerStatus.RUNNING, indexerStatus.getStatus()); + assertEquals(IndexerExecutionStatus.RESET, indexerStatus.getLastResult().getStatus()); }) .verifyComplete(); @@ -387,7 +396,7 @@ public void canRunIndexerAsync() { @Test public void canRunIndexerWithResponseSync() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - Response response = searchIndexerClient.runIndexerWithResponse(indexer.getName(), Context.NONE); + Response response = searchIndexerClient.runIndexerWithResponse(indexer.getName(), null); SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode()); @@ -398,7 +407,7 @@ public void canRunIndexerWithResponseSync() { public void canRunIndexerWithResponseAsync() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - StepVerifier.create(searchIndexerAsyncClient.runIndexerWithResponse(indexer.getName())) + StepVerifier.create(searchIndexerAsyncClient.runIndexerWithResponse(indexer.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode())) .verifyComplete(); @@ -423,7 +432,7 @@ public void canRunIndexerAndGetIndexerStatusSync() { SearchIndexerStatus indexerExecutionInfo = mockStatusClient.getIndexerStatus(indexer.getName()); assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); - Response indexerRunResponse = mockStatusClient.runIndexerWithResponse(indexer.getName(), Context.NONE); + Response indexerRunResponse = mockStatusClient.runIndexerWithResponse(indexer.getName(), null); assertEquals(HttpURLConnection.HTTP_ACCEPTED, indexerRunResponse.getStatusCode()); assertValidSearchIndexerStatus(mockStatusClient.getIndexerStatus(indexer.getName())); @@ -446,7 +455,7 @@ public void canRunIndexerAndGetIndexerStatusAsync() { .assertNext(info -> assertEquals(IndexerStatus.RUNNING, info.getStatus())) .verifyComplete(); - StepVerifier.create(mockStatusClient.runIndexerWithResponse(indexer.getName())) + StepVerifier.create(mockStatusClient.runIndexerWithResponse(indexer.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode())) .verifyComplete(); @@ -502,7 +511,7 @@ public void canUpdateIndexerFieldMappingSync() { indexersToDelete.add(initial.getName()); SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); + .setFieldMappings(new FieldMapping("state_alpha").setTargetFieldName("state")); SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); // verify the returned updated indexer is as expected @@ -520,7 +529,7 @@ public void canUpdateIndexerFieldMappingAsync() { indexersToDelete.add(initial.getName()); SearchIndexer updated = createBaseTestIndexerObject(initial.getName(), indexName, dataSourceName) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); + .setFieldMappings(new FieldMapping("state_alpha").setTargetFieldName("state")); StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexer(updated)).assertNext(indexerResponse -> { // verify the returned updated indexer is as expected @@ -532,7 +541,7 @@ public void canUpdateIndexerFieldMappingAsync() { @Test public void canCreateIndexerWithFieldMappingSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); + .setFieldMappings(new FieldMapping("state_alpha").setTargetFieldName("state")); createAndValidateIndexerSync(indexer); } @@ -540,7 +549,7 @@ public void canCreateIndexerWithFieldMappingSync() { @Test public void canCreateIndexerWithFieldMappingAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) - .setFieldMappings(Collections.singletonList(new FieldMapping("state_alpha").setTargetFieldName("state"))); + .setFieldMappings(new FieldMapping("state_alpha").setTargetFieldName("state")); createAndValidateIndexerAsync(indexer); } @@ -753,18 +762,18 @@ public void canCreateAndDeleteIndexerAsync() { @Test public void canCreateAndDeleteIndexerWithResponseSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerClient.createIndexerWithResponse(indexer, Context.NONE); + searchIndexerClient.createIndexerWithResponse(BinaryData.fromObject(indexer), null); - searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(indexer.getName(), null); assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName())); } @Test public void canCreateAndDeleteIndexerWithResponseAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - searchIndexerAsyncClient.createIndexerWithResponse(indexer).block(); + searchIndexerAsyncClient.createIndexerWithResponse(BinaryData.fromObject(indexer), null).block(); - searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false).block(); + searchIndexerAsyncClient.deleteIndexerWithResponse(indexer.getName(), null).block(); StepVerifier.create(searchIndexerAsyncClient.getIndexer(indexer.getName())) .verifyError(HttpResponseException.class); @@ -776,17 +785,17 @@ public void deleteIndexerIsIdempotentSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); // Try deleting before the indexer even exists. - Response result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); + Response result = searchIndexerClient.deleteIndexerWithResponse(indexer.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); // Actually create the indexer searchIndexerClient.createIndexer(indexer); // Now delete twice. - result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); + result = searchIndexerClient.deleteIndexerWithResponse(indexer.getName(), null); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, result.getStatusCode()); - result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, Context.NONE); + result = searchIndexerClient.deleteIndexerWithResponse(indexer.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); } @@ -796,7 +805,7 @@ public void deleteIndexerIsIdempotentAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); // Try deleting before the indexer even exists. - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false)) + StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); @@ -804,11 +813,11 @@ public void deleteIndexerIsIdempotentAsync() { searchIndexerAsyncClient.createIndexer(indexer).block(); // Now delete twice. - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false)) + StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer, false)) + StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(indexer.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); } @@ -822,7 +831,9 @@ public void canCreateAndGetIndexerSync() { SearchIndexer indexerResult = searchIndexerClient.getIndexer(indexer.getName()); assertObjectEquals(indexer, indexerResult, true, "etag"); - indexerResult = searchIndexerClient.getIndexerWithResponse(indexer.getName(), Context.NONE).getValue(); + indexerResult = searchIndexerClient.getIndexerWithResponse(indexer.getName(), null) + .getValue() + .toObject(SearchIndexer.class); assertObjectEquals(indexer, indexerResult, true, "etag"); } @@ -836,8 +847,9 @@ public void canCreateAndGetIndexerAsync() { .assertNext(indexerResult -> assertObjectEquals(indexer, indexerResult, true, "etag")) .verifyComplete(); - StepVerifier.create(searchIndexerAsyncClient.getIndexerWithResponse(indexer.getName())) - .assertNext(response -> assertObjectEquals(indexer, response.getValue(), true, "etag")) + StepVerifier.create(searchIndexerAsyncClient.getIndexerWithResponse(indexer.getName(), null)) + .assertNext(response -> assertObjectEquals(indexer, response.getValue().toObject(SearchIndexer.class), true, + "etag")) .verifyComplete(); } @@ -858,7 +870,7 @@ public void getIndexerThrowsOnNotFoundAsync() { public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResourceSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); SearchIndexer created - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, Context.NONE).getValue(); + = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, ifMatch(indexer.getETag())).getValue(); indexersToDelete.add(created.getName()); assertNotNull(created.getETag()); @@ -868,7 +880,8 @@ public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResourceSync() { public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResourceAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - StepVerifier.create(searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, true)) + StepVerifier + .create(searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, ifMatch(indexer.getETag()))) .assertNext(response -> { indexersToDelete.add(response.getValue().getName()); assertNotNull(response.getValue().getETag()); @@ -879,18 +892,14 @@ public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResourceAsync() { @Test public void deleteIndexerIfExistsWorksOnlyWhenResourceExistsSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer created - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); + SearchIndexer created = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, null).getValue(); - searchIndexerClient.deleteIndexerWithResponse(created, true, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(created.getName(), ifMatch(created.getETag())); // 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()); - } + assertHttpResponseException( + () -> searchIndexerClient.deleteIndexerWithResponse(created.getName(), ifMatch(created.getETag())), + HttpURLConnection.HTTP_PRECON_FAILED); } @Test @@ -898,9 +907,11 @@ 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))); + = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, null) + .flatMap(response -> searchIndexerAsyncClient + .deleteIndexerWithResponse(response.getValue().getName(), ifMatch(response.getValue().getETag())) + .then(searchIndexerAsyncClient.deleteIndexerWithResponse(response.getValue().getName(), + ifMatch(response.getValue().getETag())))); StepVerifier.create(createDeleteThenFailToDeleteMono).verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); @@ -912,37 +923,37 @@ public void deleteIndexerIfExistsWorksOnlyWhenResourceExistsAsync() { public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResourceSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); SearchIndexer stale - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, Context.NONE).getValue(); + = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, ifMatch(indexer.getETag())).getValue(); - SearchIndexer updated - = searchIndexerClient.createOrUpdateIndexerWithResponse(stale, false, Context.NONE).getValue(); + SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(stale, null).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()); - } + assertHttpResponseException( + () -> searchIndexerClient.deleteIndexerWithResponse(stale.getName(), ifMatch(stale.getETag())), + HttpURLConnection.HTTP_PRECON_FAILED); - searchIndexerClient.deleteIndexerWithResponse(updated, true, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(updated.getName(), ifMatch(updated.getETag())); } @Test public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResourceAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); SearchIndexer stale - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, true).map(Response::getValue).block(); + = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, ifMatch(indexer.getETag())) + .map(Response::getValue) + .block(); SearchIndexer updated - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(stale, false).map(Response::getValue).block(); + = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(stale, null).map(Response::getValue).block(); - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(stale, true)) + StepVerifier + .create(searchIndexerAsyncClient.deleteIndexerWithResponse(stale.getName(), ifMatch(stale.getETag()))) .verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); }); - StepVerifier.create(searchIndexerAsyncClient.deleteIndexerWithResponse(updated, true)) + StepVerifier + .create(searchIndexerAsyncClient.deleteIndexerWithResponse(updated.getName(), ifMatch(updated.getETag()))) .expectNextCount(1) .verifyComplete(); } @@ -950,13 +961,12 @@ public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResourceAsync() { @Test public void updateIndexerIfExistsSucceedsOnExistingResourceSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer original - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); + SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, null).getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); SearchIndexer updated = searchIndexerClient - .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), false, Context.NONE) + .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), null) .getValue(); String updatedETag = updated.getETag(); @@ -969,13 +979,13 @@ public void updateIndexerIfExistsSucceedsOnExistingResourceAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); Mono> createAndUpdateIndexerMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false).flatMap(response -> { + = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, null).flatMap(response -> { SearchIndexer original = response.getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); return searchIndexerAsyncClient - .createOrUpdateIndexerWithResponse(original.setDescription("an update"), false) + .createOrUpdateIndexerWithResponse(original.setDescription("an update"), null) .map(updated -> Tuples.of(originalETag, updated.getValue().getETag())); }); @@ -988,23 +998,19 @@ public void updateIndexerIfExistsSucceedsOnExistingResourceAsync() { @Test public void updateIndexerIfNotChangedFailsWhenResourceChangedSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer original - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); + SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, null).getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); SearchIndexer updated = searchIndexerClient - .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), true, Context.NONE) + .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), ifMatch(originalETag)) .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()); - } + assertHttpResponseException( + () -> searchIndexerClient.createOrUpdateIndexerWithResponse(original, ifMatch(originalETag)), + HttpURLConnection.HTTP_PRECON_FAILED); // Check eTags assertNotNull(originalETag); @@ -1017,19 +1023,21 @@ public void updateIndexerIfNotChangedFailsWhenResourceChangedAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); Mono> createUpdateAndFailToUpdateMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false).flatMap(response -> { + = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, null).flatMap(response -> { SearchIndexer original = response.getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); return searchIndexerAsyncClient - .createOrUpdateIndexerWithResponse(original.setDescription("an update"), true) + .createOrUpdateIndexerWithResponse(original.setDescription("an update"), ifMatch(originalETag)) .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)); + }) + .flatMap(original -> searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(original.getT3(), + ifMatch(original.getT3().getETag()))); StepVerifier.create(createUpdateAndFailToUpdateMono).verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); @@ -1040,13 +1048,12 @@ public void updateIndexerIfNotChangedFailsWhenResourceChangedAsync() { @Test public void updateIndexerIfNotChangedSucceedsWhenResourceUnchangedSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - SearchIndexer original - = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, Context.NONE).getValue(); + SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, null).getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); SearchIndexer updated = searchIndexerClient - .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), true, Context.NONE) + .createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), ifMatch(originalETag)) .getValue(); String updatedETag = updated.getETag(); @@ -1060,15 +1067,17 @@ public void updateIndexerIfNotChangedSucceedsWhenResourceUnchangedSync() { public void updateIndexerIfNotChangedSucceedsWhenResourceUnchangedAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()); - Mono> createAndUpdateIndexerMono - = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, false).flatMap(response -> { - SearchIndexer original = response.getValue(); + Mono> createAndUpdateIndexerMono = searchIndexerAsyncClient + .createOrUpdateIndexerWithResponse(indexer.getName(), BinaryData.fromObject(indexer), null) + .flatMap(response -> { + SearchIndexer original = response.getValue().toObject(SearchIndexer.class); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); return searchIndexerAsyncClient - .createOrUpdateIndexerWithResponse(original.setDescription("an update"), true) - .map(update -> Tuples.of(originalETag, update.getValue().getETag())); + .createOrUpdateIndexerWithResponse(original.getName(), + BinaryData.fromObject(original.setDescription("an update")), ifMatch(originalETag)) + .map(update -> Tuples.of(originalETag, update.getValue().toObject(SearchIndexer.class).getETag())); }); StepVerifier.create(createAndUpdateIndexerMono).assertNext(etags -> { @@ -1133,7 +1142,7 @@ public void canCreateIndexerWithAllowSkillsetToReadFileDataSync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) .setSkillsetName(sharedSkillset.getName()) .setParameters(new IndexingParameters() - .setConfiguration(Collections.singletonMap("allowSkillsetToReadFileData", true))); + .setConfiguration(new IndexingParametersConfiguration().setAllowSkillsetToReadFileData(true))); createAndValidateIndexerSync(indexer); @@ -1144,7 +1153,7 @@ public void canCreateIndexerWithAllowSkillsetToReadFileDataAsync() { SearchIndexer indexer = createBaseTestIndexerObject(sharedIndex.getName(), sharedDatasource.getName()) .setSkillsetName(sharedSkillset.getName()) .setParameters(new IndexingParameters() - .setConfiguration(Collections.singletonMap("allowSkillsetToReadFileData", true))); + .setConfiguration(new IndexingParametersConfiguration().setAllowSkillsetToReadFileData(true))); createAndValidateIndexerAsync(indexer); } @@ -1162,27 +1171,24 @@ private static SearchIndexerSkillset createSkillsetObject() { 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")); + SearchIndexerSkill skill = 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); + return new SearchIndexerSkillset("shared-ocr-skillset", skill) + .setDescription("Skillset for testing default configuration"); } private static SearchIndexerDataSourceConnection createSharedDataSource() { // create the new data source object for this storage account and container - return new SearchIndexerDataSourceConnection("shared-" + BLOB_DATASOURCE_NAME) - .setType(SearchIndexerDataSourceType.AZURE_BLOB) - .setDescription("real live blob") - .setIdentity(new SearchIndexerDataUserAssignedIdentity(USER_ASSIGNED_IDENTITY)) - .setConnectionString(String.format( + return new SearchIndexerDataSourceConnection("shared-" + BLOB_DATASOURCE_NAME, + SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString(String.format( "ResourceId=/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s;", - SUBSCRIPTION_ID, RESOURCE_GROUP, STORAGE_ACCOUNT_NAME)) - .setContainer(new SearchIndexerDataContainer(BLOB_CONTAINER_NAME).setQuery("/")); + SUBSCRIPTION_ID, RESOURCE_GROUP, STORAGE_ACCOUNT_NAME)), + new SearchIndexerDataContainer(BLOB_CONTAINER_NAME).setQuery("/")).setDescription("real live blob") + .setIdentity(new SearchIndexerDataUserAssignedIdentity(USER_ASSIGNED_IDENTITY)); } SearchIndexer createBaseTestIndexerObject(String targetIndexName, String dataSourceName) { @@ -1205,14 +1211,14 @@ SearchIndexer createBaseTestIndexerObject(String name, String targetIndexName, S * @return the newly created Index object */ private static SearchIndex createTestIndexForLiveDatasource() { - return new SearchIndex("shared" + IndexersManagementTests.TARGET_INDEX_NAME).setFields(Arrays.asList( + return new SearchIndex("shared" + IndexersManagementTests.TARGET_INDEX_NAME, 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))); + .setFilterable(Boolean.FALSE)); } /** @@ -1240,13 +1246,13 @@ SearchIndexer createIndexerWithStorageConfig(String name, String targetIndexName 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); + IndexingParametersConfiguration configuration + = new IndexingParametersConfiguration().setIndexedFileNameExtensions(".pdf,.docx") + .setExcludedFileNameExtensions(".xlsx") + .setDataToExtract(BlobIndexerDataToExtract.STORAGE_METADATA) + .setFailOnUnsupportedContentType(false); - IndexingParameters ip = new IndexingParameters().setConfiguration(config); + IndexingParameters ip = new IndexingParameters().setConfiguration(configuration); // modify it updatedExpected.setParameters(ip); 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 index 1227d3f37bc4..8a213819f21f 100644 --- 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 @@ -13,4 +13,12 @@ public static HttpPipeline getHttpPipeline(SearchIndexClient searchIndexClient) public static HttpPipeline getHttpPipeline(SearchIndexAsyncClient searchIndexAsyncClient) { return searchIndexAsyncClient.getHttpPipeline(); } + + public static String getEndpoint(SearchIndexClient searchIndexClient) { + return searchIndexClient.getEndpoint(); + } + + public static String getEndpoint(SearchIndexAsyncClient searchIndexAsyncClient) { + return searchIndexAsyncClient.getEndpoint(); + } } 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 index 8c4660e0a8a2..1bcbfaed43a0 100644 --- 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 @@ -34,15 +34,10 @@ static Stream> apiCallReturnsErrorSupplier() { .buildAsyncClient(); return Stream.of(client.createOrUpdateDataSourceConnection(null), - client.createOrUpdateDataSourceConnectionWithResponse(null, true), - client.createOrUpdateDataSourceConnectionWithResponse(null), - client.deleteDataSourceConnectionWithResponse(null, true), + client.createOrUpdateDataSourceConnectionWithResponse(null, null), - client.createOrUpdateIndexer(null), client.createOrUpdateIndexerWithResponse(null, true), - client.createOrUpdateIndexerWithResponse(null), client.deleteIndexerWithResponse(null, true), + client.createOrUpdateIndexer(null), client.createOrUpdateIndexerWithResponse(null, null), - client.createSkillset(null), client.createSkillsetWithResponse(null), client.createOrUpdateSkillset(null), - client.createOrUpdateSkillsetWithResponse(null, true), client.createOrUpdateSkillsetWithResponse(null), - client.deleteSkillsetWithResponse(null, true)); + client.createOrUpdateSkillset(null), client.createOrUpdateSkillsetWithResponse(null, null)); } } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/OptionBagsTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/OptionBagsTests.java deleted file mode 100644 index 3b895f74c147..000000000000 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/OptionBagsTests.java +++ /dev/null @@ -1,115 +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.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.CreateOrUpdateDataSourceConnectionOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateIndexerOptions; -import com.azure.search.documents.indexes.models.CreateOrUpdateSkillsetOptions; -import com.azure.search.documents.indexes.models.IndexerExecutionEnvironment; -import com.azure.search.documents.indexes.models.IndexingParameters; -import com.azure.search.documents.indexes.models.IndexingParametersConfiguration; -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 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.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Stream; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -@Execution(ExecutionMode.CONCURRENT) -public class OptionBagsTests { - private static final Map FOOL_SPOTBUGS = new HashMap<>(); - - @ParameterizedTest - @MethodSource("nullRequiredValuesThrowNullPointerExceptionsSupplier") - public void nullRequiredValuesThrowNullPointerExceptions(Executable constructorCallWithNullParameter) { - assertThrows(NullPointerException.class, constructorCallWithNullParameter); - } - - static Stream nullRequiredValuesThrowNullPointerExceptionsSupplier() { - return Stream.of( - () -> new CreateOrUpdateDataSourceConnectionOptions( - (SearchIndexerDataSourceConnection) FOOL_SPOTBUGS.get("value")), - () -> new CreateOrUpdateIndexerOptions((SearchIndexer) FOOL_SPOTBUGS.get("value")), - () -> new CreateOrUpdateSkillsetOptions((SearchIndexerSkillset) FOOL_SPOTBUGS.get("value"))); - } - - @ParameterizedTest - @MethodSource("getIndexingParametersConfigurationSupplier") - public void getIndexingParametersConfiguration(Map configuration, - Function parameterGetter, Object expected) { - IndexingParametersConfiguration indexingParametersConfiguration - = new IndexingParameters().setConfiguration(configuration).getIndexingParametersConfiguration(); - - assertEquals(expected, parameterGetter.apply(indexingParametersConfiguration)); - } - - static Stream getIndexingParametersConfigurationSupplier() { - return Stream.of( - createArguments("parsingMode", BlobIndexerParsingMode.DEFAULT, - IndexingParametersConfiguration::getParsingMode), - - createArguments("excludedFileNameExtensions", "parquet", - IndexingParametersConfiguration::getExcludedFileNameExtensions), - - createArguments("indexedFileNameExtensions", "json", - IndexingParametersConfiguration::getIndexedFileNameExtensions), - - createArguments("failOnUnsupportedContentType", true, - IndexingParametersConfiguration::isFailOnUnsupportedContentType), - - createArguments("failOnUnprocessableDocument", true, - IndexingParametersConfiguration::isFailOnUnprocessableDocument), - - createArguments("indexStorageMetadataOnlyForOversizedDocuments", true, - IndexingParametersConfiguration::isIndexStorageMetadataOnlyForOversizedDocuments), - - createArguments("delimitedTextHeaders", "headers", - IndexingParametersConfiguration::getDelimitedTextHeaders), - - createArguments("delimitedTextDelimiter", ",", IndexingParametersConfiguration::getDelimitedTextDelimiter), - - createArguments("firstLineContainsHeaders", true, - IndexingParametersConfiguration::isFirstLineContainsHeaders), - - createArguments("documentRoot", "/", IndexingParametersConfiguration::getDocumentRoot), - - createArguments("dataToExtract", BlobIndexerDataToExtract.CONTENT_AND_METADATA, - IndexingParametersConfiguration::getDataToExtract), - - createArguments("imageAction", BlobIndexerImageAction.GENERATE_NORMALIZED_IMAGE_PER_PAGE, - IndexingParametersConfiguration::getImageAction), - - createArguments("allowSkillsetToReadFileData", true, - IndexingParametersConfiguration::isAllowSkillsetToReadFileData), - - createArguments("pdfTextRotationAlgorithm", BlobIndexerPdfTextRotationAlgorithm.DETECT_ANGLES, - IndexingParametersConfiguration::getPdfTextRotationAlgorithm), - - createArguments("executionEnvironment", IndexerExecutionEnvironment.STANDARD, - IndexingParametersConfiguration::getExecutionEnvironment), - - createArguments("queryTimeout", "1:00:00", IndexingParametersConfiguration::getQueryTimeout)); - } - - static Arguments createArguments(String key, Object expected, - Function getter) { - return Arguments.of(Collections.singletonMap(key, expected), getter, expected); - } -} 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 index 83f4f1904f13..edc2b77f49d2 100644 --- 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 @@ -46,7 +46,7 @@ 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; + private final SearchServiceVersion apiVersion = SearchServiceVersion.V2025_11_01_PREVIEW; @Test public void buildSyncClientTest() { @@ -118,11 +118,6 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { assertEquals(searchEndpoint, asyncClient.getEndpoint()); } - @Test - public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder().endpoint("")); - } - @Test public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, 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 index bd3d273bd8fb..3a13e61bbe0d 100644 --- 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 @@ -46,7 +46,7 @@ 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; + private final SearchServiceVersion apiVersion = SearchServiceVersion.V2025_11_01_PREVIEW; @Test public void buildSyncClientTest() { @@ -118,11 +118,6 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { assertEquals(searchEndpoint, asyncClient.getEndpoint()); } - @Test - public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexerClientBuilder().endpoint("")); - } - @Test public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { assertThrows(IllegalArgumentException.class, 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 index 1a13f7106ab2..5ab085b5253d 100644 --- 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 @@ -2,9 +2,10 @@ // Licensed under the MIT License. package com.azure.search.documents.indexes; +import com.azure.core.http.HttpHeaderName; import com.azure.core.http.rest.Response; import com.azure.core.test.annotation.LiveOnly; -import com.azure.core.util.Context; +import com.azure.core.util.BinaryData; import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.SearchServiceCounters; import com.azure.search.documents.indexes.models.SearchServiceStatistics; @@ -15,6 +16,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; public class SearchServiceTests extends SearchTestBase { + private static final HttpHeaderName REQUEST_ID = HttpHeaderName.fromString("request-id"); + private static final HttpHeaderName CLIENT_REQUEST_ID = HttpHeaderName.fromString("client-request-id"); @Test public void getServiceStatsReturnsCorrectDefinitionSync() { @@ -35,14 +38,16 @@ public void getServiceStatsReturnsCorrectDefinitionWithResponseSync() { SearchIndexClient serviceClient = getSearchIndexClientBuilder(true).buildClient(); SearchServiceStatistics searchServiceStatistics - = serviceClient.getServiceStatisticsWithResponse(Context.NONE).getValue(); + = serviceClient.getServiceStatisticsWithResponse(null).getValue().toObject(SearchServiceStatistics.class); validateServiceStatistics(searchServiceStatistics); } @Test public void getServiceStatsReturnsCorrectDefinitionWithResponseAsync() { - StepVerifier.create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatisticsWithResponse()) - .assertNext(response -> validateServiceStatistics(response.getValue())) + StepVerifier + .create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatisticsWithResponse(null)) + .assertNext( + response -> validateServiceStatistics(response.getValue().toObject(SearchServiceStatistics.class))) .verifyComplete(); } @@ -51,7 +56,7 @@ public void getServiceStatsReturnsCorrectDefinitionWithResponseAsync() { public void getServiceStatsReturnsRequestIdSync() { SearchIndexClient serviceClient = getSearchIndexClientBuilder(true).buildClient(); - Response response = serviceClient.getServiceStatisticsWithResponse(Context.NONE); + Response response = serviceClient.getServiceStatisticsWithResponse(null); /* * The service will always return a request-id and will conditionally return client-request-id if @@ -59,18 +64,19 @@ public void getServiceStatsReturnsRequestIdSync() { * 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"); + 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()); + validateServiceStatistics(response.getValue().toObject(SearchServiceStatistics.class)); } @Test @LiveOnly public void getServiceStatsReturnsRequestIdAsync() { - StepVerifier.create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatisticsWithResponse()) + StepVerifier + .create(getSearchIndexClientBuilder(false).buildAsyncClient().getServiceStatisticsWithResponse(null)) .assertNext(response -> { /* * The service will always return a request-id and will conditionally return client-request-id if @@ -78,12 +84,12 @@ public void getServiceStatsReturnsRequestIdAsync() { * 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"); + 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()); + validateServiceStatistics(response.getValue().toObject(SearchServiceStatistics.class)); }) .verifyComplete(); } 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 index d37ac71e24a0..f2f7883b3d76 100644 --- 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 @@ -6,17 +6,18 @@ 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.core.util.BinaryData; +import com.azure.search.documents.SearchServiceVersion; import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.CognitiveServicesAccount; import com.azure.search.documents.indexes.models.CognitiveServicesAccountKey; import com.azure.search.documents.indexes.models.ConditionalSkill; import com.azure.search.documents.indexes.models.ContentUnderstandingSkill; +import com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties; +import com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit; +import com.azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions; 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.EntityRecognitionSkillV3; import com.azure.search.documents.indexes.models.ImageAnalysisSkill; import com.azure.search.documents.indexes.models.ImageAnalysisSkillLanguage; import com.azure.search.documents.indexes.models.ImageDetail; @@ -30,19 +31,14 @@ 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.SentimentSkillV3; 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.WebApiHttpHeaders; import com.azure.search.documents.indexes.models.WebApiSkill; -import com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingProperties; -import com.azure.search.documents.indexes.models.ContentUnderstandingSkillChunkingUnit; -import com.azure.search.documents.indexes.models.ContentUnderstandingSkillExtractionOptions; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; @@ -62,11 +58,10 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import com.azure.core.util.BinaryData; -import com.azure.search.documents.SearchServiceVersion; import static com.azure.search.documents.TestHelpers.assertHttpResponseException; import static com.azure.search.documents.TestHelpers.assertObjectEquals; +import static com.azure.search.documents.TestHelpers.ifMatch; import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -125,22 +120,26 @@ public void createSkillsetReturnsCorrectDefinitionImageAnalysisKeyPhraseAsync() @Test public void createSkillsetReturnsCorrectDefinitionImageAnalysisKeyPhraseWithResponseSync() { SearchIndexerSkillset expectedSkillset = createTestSkillsetImageAnalysisKeyPhrase(); - Response skillsetResponse - = client.createSkillsetWithResponse(expectedSkillset, Context.NONE); - skillsetsToDelete.add(skillsetResponse.getValue().getName()); + SearchIndexerSkillset skillset + = client.createSkillsetWithResponse(BinaryData.fromObject(expectedSkillset), null) + .getValue() + .toObject(SearchIndexerSkillset.class); + skillsetsToDelete.add(skillset.getName()); - assertObjectEquals(expectedSkillset, skillsetResponse.getValue(), true, "etag"); + assertObjectEquals(expectedSkillset, skillset, 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(); - + StepVerifier.create(asyncClient.createSkillsetWithResponse(BinaryData.fromObject(expectedSkillset), null)) + .assertNext(response -> { + SearchIndexerSkillset skillset = response.getValue().toObject(SearchIndexerSkillset.class); + skillsetsToDelete.add(skillset.getName()); + assertObjectEquals(expectedSkillset, skillset, true, "etag"); + }) + .verifyComplete(); } @Test @@ -167,36 +166,33 @@ public void createSkillsetReturnsCorrectDefinitionMergeTextAsync() { public void createSkillsetReturnsCorrectDefinitionOcrEntitySync() { createAndValidateSkillsetSync(createTestSkillsetOcrEntity(null)); - createAndValidateSkillsetSync(createTestSkillsetOcrEntity( - Arrays.asList(EntityCategory.LOCATION, EntityCategory.ORGANIZATION, EntityCategory.PERSON))); + createAndValidateSkillsetSync(createTestSkillsetOcrEntity(Arrays.asList("location", "organization", "person"))); } @Test public void createSkillsetReturnsCorrectDefinitionOcrEntityAsync() { createAndValidateSkillsetAsync(createTestSkillsetOcrEntity(null)); - createAndValidateSkillsetAsync(createTestSkillsetOcrEntity( - Arrays.asList(EntityCategory.LOCATION, EntityCategory.ORGANIZATION, EntityCategory.PERSON))); + createAndValidateSkillsetAsync( + createTestSkillsetOcrEntity(Arrays.asList("location", "organization", "person"))); } @Test public void createSkillsetReturnsCorrectDefinitionOcrHandwritingSentimentSync() { - createAndValidateSkillsetSync( - createTestSkillsetOcrSentiment(OcrSkillLanguage.PT, SentimentSkillLanguage.PT_PT)); + createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.PT, "pt_PT")); - createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.FI, SentimentSkillLanguage.FI)); + createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.FI, "fi")); - createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.EN, SentimentSkillLanguage.EN)); + createAndValidateSkillsetSync(createTestSkillsetOcrSentiment(OcrSkillLanguage.EN, "en")); } @Test public void createSkillsetReturnsCorrectDefinitionOcrHandwritingSentimentAsync() { - createAndValidateSkillsetAsync( - createTestSkillsetOcrSentiment(OcrSkillLanguage.PT, SentimentSkillLanguage.PT_PT)); + createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.PT, "pt_PT")); - createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.FI, SentimentSkillLanguage.FI)); + createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.FI, "fi")); - createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.EN, SentimentSkillLanguage.EN)); + createAndValidateSkillsetAsync(createTestSkillsetOcrSentiment(OcrSkillLanguage.EN, "en")); } @Test @@ -316,13 +312,13 @@ public void createSkillsetReturnsCorrectDefinitionWithMergeDefaultSettingsAsync( } @Test - public void createSkillsetReturnsCorrectDefinitionWithEntityRecognitionDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithEntityRecognitionDefaultSettings()); + public void createSkillsetReturnsCorrectDefinitionWithEntityRecognitionV3DefaultSettingsSync() { + createAndValidateSkillsetSync(createSkillsetWithEntityRecognitionV3DefaultSettings()); } @Test - public void createSkillsetReturnsCorrectDefinitionWithEntityRecognitionDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithEntityRecognitionDefaultSettings()); + public void createSkillsetReturnsCorrectDefinitionWithEntityRecognitionV3DefaultSettingsAsync() { + createAndValidateSkillsetAsync(createSkillsetWithEntityRecognitionV3DefaultSettings()); } @Test @@ -352,7 +348,8 @@ public void getOcrSkillsetReturnsCorrectDefinitionWithResponseSync() { client.createSkillset(expected); skillsetsToDelete.add(expected.getName()); - SearchIndexerSkillset actual = client.getSkillsetWithResponse(expected.getName(), Context.NONE).getValue(); + SearchIndexerSkillset actual + = client.getSkillsetWithResponse(expected.getName(), null).getValue().toObject(SearchIndexerSkillset.class); assertObjectEquals(expected, actual, true, "etag"); } @@ -362,8 +359,9 @@ public void getOcrSkillsetReturnsCorrectDefinitionWithResponseAsync() { asyncClient.createSkillset(expected).block(); skillsetsToDelete.add(expected.getName()); - StepVerifier.create(asyncClient.getSkillsetWithResponse(expected.getName(), Context.NONE)) - .assertNext(response -> assertObjectEquals(expected, response.getValue(), true, "etag")) + StepVerifier.create(asyncClient.getSkillsetWithResponse(expected.getName(), null)) + .assertNext(response -> assertObjectEquals(expected, + response.getValue().toObject(SearchIndexerSkillset.class), true, "etag")) .verifyComplete(); } @@ -389,13 +387,13 @@ public void getOcrSkillsetWithShouldDetectOrientationReturnsCorrectDefinitionAsy } @Test - public void createSkillsetReturnsCorrectDefinitionWithSentimentDefaultSettingsSync() { - createAndValidateSkillsetSync(createSkillsetWithSentimentDefaultSettings()); + public void createSkillsetReturnsCorrectDefinitionWithSentimentV3DefaultSettingsSync() { + createAndValidateSkillsetSync(createSkillsetWithSentimentV3DefaultSettings()); } @Test - public void createSkillsetReturnsCorrectDefinitionWithSentimentDefaultSettingsAsync() { - createAndValidateSkillsetAsync(createSkillsetWithSentimentDefaultSettings()); + public void createSkillsetReturnsCorrectDefinitionWithSentimentV3DefaultSettingsAsync() { + createAndValidateSkillsetAsync(createSkillsetWithSentimentV3DefaultSettings()); } @Test @@ -448,7 +446,7 @@ public void getSkillsetThrowsOnNotFoundAsync() { @Test public void canCreateAndListSkillsetsSyncAndAsync() { SearchIndexerSkillset skillset1 = createSkillsetWithCognitiveServicesKey(); - SearchIndexerSkillset skillset2 = createSkillsetWithEntityRecognitionDefaultSettings(); + SearchIndexerSkillset skillset2 = createSkillsetWithEntityRecognitionV3DefaultSettings(); client.createSkillset(skillset1); skillsetsToDelete.add(skillset1.getName()); @@ -460,13 +458,18 @@ public void canCreateAndListSkillsetsSyncAndAsync() { expectedSkillsets.put(skillset2.getName(), skillset2); Map actualSkillsets = client.listSkillsets() + .getSkillsets() .stream() .collect(Collectors.toMap(SearchIndexerSkillset::getName, skillset -> skillset)); compareMaps(expectedSkillsets, actualSkillsets, (expected, actual) -> assertObjectEquals(expected, actual, true)); - StepVerifier.create(asyncClient.listSkillsets().collectMap(SearchIndexerSkillset::getName)) + StepVerifier + .create(asyncClient.listSkillsets() + .map(result -> result.getSkillsets() + .stream() + .collect(Collectors.toMap(SearchIndexerSkillset::getName, skillset -> skillset)))) .assertNext(actualSkillsetsAsync -> compareMaps(expectedSkillsets, actualSkillsetsAsync, (expected, actual) -> assertObjectEquals(expected, actual, true))) .verifyComplete(); @@ -475,7 +478,7 @@ public void canCreateAndListSkillsetsSyncAndAsync() { @Test public void canListSkillsetsWithSelectedFieldSyncAndAsync() { SearchIndexerSkillset skillset1 = createSkillsetWithCognitiveServicesKey(); - SearchIndexerSkillset skillset2 = createSkillsetWithEntityRecognitionDefaultSettings(); + SearchIndexerSkillset skillset2 = createSkillsetWithEntityRecognitionV3DefaultSettings(); client.createSkillset(skillset1); skillsetsToDelete.add(skillset1.getName()); @@ -483,33 +486,31 @@ public void canListSkillsetsWithSelectedFieldSyncAndAsync() { skillsetsToDelete.add(skillset2.getName()); Set expectedSkillsetNames = new HashSet<>(Arrays.asList(skillset1.getName(), skillset2.getName())); - Set actualSkillsetNames = client.listSkillsetNames(Context.NONE).stream().collect(Collectors.toSet()); + Set actualSkillsetNames = new HashSet<>(client.listSkillsetNames()); 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(); + StepVerifier.create(asyncClient.listSkillsetNames().map(HashSet::new)).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); + Response deleteResponse = client.deleteSkillsetWithResponse(skillset.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); client.createSkillset(skillset); // Delete the same skillset twice - deleteResponse = client.deleteSkillsetWithResponse(skillset, false, Context.NONE); + deleteResponse = client.deleteSkillsetWithResponse(skillset.getName(), null); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, deleteResponse.getStatusCode()); - deleteResponse = client.deleteSkillsetWithResponse(skillset, false, Context.NONE); + deleteResponse = client.deleteSkillsetWithResponse(skillset.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); } @@ -517,18 +518,18 @@ public void deleteSkillsetIsIdempotentSync() { public void deleteSkillsetIsIdempotentAsync() { SearchIndexerSkillset skillset = createSkillsetWithOcrDefaultSettings(false); - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset, false)) + StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset.getName(), null)) .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)) + StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset, false)) + StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); } @@ -574,7 +575,7 @@ public void createOrUpdateCreatesWhenSkillsetDoesNotExistAsync() { public void createOrUpdateCreatesWhenSkillsetDoesNotExistWithResponseSync() { SearchIndexerSkillset expected = createTestOcrSkillset(); Response createOrUpdateResponse - = client.createOrUpdateSkillsetWithResponse(expected, false, Context.NONE); + = client.createOrUpdateSkillsetWithResponse(expected, null); skillsetsToDelete.add(createOrUpdateResponse.getValue().getName()); assertEquals(HttpURLConnection.HTTP_CREATED, createOrUpdateResponse.getStatusCode()); @@ -584,7 +585,7 @@ public void createOrUpdateCreatesWhenSkillsetDoesNotExistWithResponseSync() { public void createOrUpdateCreatesWhenSkillsetDoesNotExistWithResponseAsync() { SearchIndexerSkillset expected = createTestOcrSkillset(); - StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(expected, false)).assertNext(response -> { + StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(expected, null)).assertNext(response -> { skillsetsToDelete.add(response.getValue().getName()); assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); }).verifyComplete(); @@ -594,11 +595,11 @@ public void createOrUpdateCreatesWhenSkillsetDoesNotExistWithResponseAsync() { public void createOrUpdateUpdatesWhenSkillsetExistsSync() { SearchIndexerSkillset skillset = createTestOcrSkillset(); Response createOrUpdateResponse - = client.createOrUpdateSkillsetWithResponse(skillset, false, Context.NONE); + = client.createOrUpdateSkillsetWithResponse(skillset, null); skillsetsToDelete.add(createOrUpdateResponse.getValue().getName()); assertEquals(HttpURLConnection.HTTP_CREATED, createOrUpdateResponse.getStatusCode()); SearchIndexerSkillset updatedSkillset = createTestOcrSkillset(2, skillset.getName()); - createOrUpdateResponse = client.createOrUpdateSkillsetWithResponse(updatedSkillset, false, Context.NONE); + createOrUpdateResponse = client.createOrUpdateSkillsetWithResponse(updatedSkillset, null); assertEquals(HttpURLConnection.HTTP_OK, createOrUpdateResponse.getStatusCode()); } @@ -606,13 +607,13 @@ public void createOrUpdateUpdatesWhenSkillsetExistsSync() { public void createOrUpdateUpdatesWhenSkillsetExistsAsync() { SearchIndexerSkillset skillset = createTestOcrSkillset(); - StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(skillset, false)).assertNext(response -> { + StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(skillset, null)).assertNext(response -> { skillsetsToDelete.add(response.getValue().getName()); assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); }).verifyComplete(); StepVerifier - .create(asyncClient.createOrUpdateSkillsetWithResponse(createTestOcrSkillset(2, skillset.getName()), false)) + .create(asyncClient.createOrUpdateSkillsetWithResponse(createTestOcrSkillset(2, skillset.getName()), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_OK, response.getStatusCode())) .verifyComplete(); } @@ -624,7 +625,8 @@ public void createOrUpdateUpdatesSkillsSync() { skillsetsToDelete.add(createdSkillset.getName()); // update skills - createdSkillset.setSkills(getCreateOrUpdateSkills()); + createdSkillset.getSkills().clear(); + createdSkillset.getSkills().addAll(getCreateOrUpdateSkills()); assertObjectEquals(createdSkillset, client.createOrUpdateSkillset(createdSkillset), true, "etag", "@odata.etag"); @@ -636,7 +638,9 @@ public void createOrUpdateUpdatesSkillsAsync() { SearchIndexerSkillset createdSkillset = asyncClient.createSkillset(skillset).map(created -> { skillsetsToDelete.add(created.getName()); - return created.setSkills(getCreateOrUpdateSkills()); + created.getSkills().clear(); + created.getSkills().addAll(getCreateOrUpdateSkills()); + return created; }).block(); StepVerifier.create(asyncClient.createOrUpdateSkillset(createdSkillset)) @@ -711,9 +715,9 @@ public void createSkillsetReturnsCorrectDefinitionConditionalAsync() { @Test public void createOrUpdateSkillsetIfNotExistsSucceedsOnNoResourceSync() { + SearchIndexerSkillset initial = createSkillsetWithOcrDefaultSettings(false); SearchIndexerSkillset created - = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true, Context.NONE) - .getValue(); + = client.createOrUpdateSkillsetWithResponse(initial, ifMatch(initial.getETag())).getValue(); skillsetsToDelete.add(created.getName()); assertNotNull(created.getETag()); @@ -721,8 +725,8 @@ public void createOrUpdateSkillsetIfNotExistsSucceedsOnNoResourceSync() { @Test public void createOrUpdateSkillsetIfNotExistsSucceedsOnNoResourceAsync() { - StepVerifier - .create(asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true)) + SearchIndexerSkillset initial = createSkillsetWithOcrDefaultSettings(false); + StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(initial, ifMatch(initial.getETag()))) .assertNext(response -> { skillsetsToDelete.add(response.getValue().getName()); assertNotNull(response.getValue().getETag()); @@ -732,14 +736,12 @@ public void createOrUpdateSkillsetIfNotExistsSucceedsOnNoResourceAsync() { @Test public void createOrUpdateSkillsetIfExistsSucceedsOnExistingResourceSync() { - SearchIndexerSkillset original = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); + SearchIndexerSkillset original + = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null).getValue(); skillsetsToDelete.add(original.getName()); SearchIndexerSkillset updated - = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), false, Context.NONE) - .getValue(); + = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), null).getValue(); validateETagUpdate(original.getETag(), updated.getETag()); } @@ -747,12 +749,12 @@ public void createOrUpdateSkillsetIfExistsSucceedsOnExistingResourceSync() { @Test public void createOrUpdateSkillsetIfExistsSucceedsOnExistingResourceAsync() { Mono> createAndUpdateMono - = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false) + = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null) .flatMap(response -> { SearchIndexerSkillset original = response.getValue(); skillsetsToDelete.add(original.getName()); - return asyncClient.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), false) + return asyncClient.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), null) .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); }); @@ -763,13 +765,12 @@ public void createOrUpdateSkillsetIfExistsSucceedsOnExistingResourceAsync() { @Test public void createOrUpdateSkillsetIfNotChangedSucceedsWhenResourceUnchangedSync() { - SearchIndexerSkillset original = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); + SearchIndexerSkillset original + = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null).getValue(); skillsetsToDelete.add(original.getName()); SearchIndexerSkillset updated - = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), true, Context.NONE) + = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), ifMatch(original.getETag())) .getValue(); validateETagUpdate(original.getETag(), updated.getETag()); @@ -778,12 +779,14 @@ public void createOrUpdateSkillsetIfNotChangedSucceedsWhenResourceUnchangedSync( @Test public void createOrUpdateSkillsetIfNotChangedSucceedsWhenResourceUnchangedAsync() { Mono> createAndUpdateMono - = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false) + = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null) .flatMap(response -> { SearchIndexerSkillset original = response.getValue(); skillsetsToDelete.add(original.getName()); - return asyncClient.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), true) + return asyncClient + .createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), + ifMatch(original.getETag())) .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); }); @@ -794,21 +797,20 @@ public void createOrUpdateSkillsetIfNotChangedSucceedsWhenResourceUnchangedAsync @Test public void createOrUpdateSkillsetIfNotChangedFailsWhenResourceChangedSyncAndAsync() { - SearchIndexerSkillset original = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); + SearchIndexerSkillset original + = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null).getValue(); skillsetsToDelete.add(original.getName()); SearchIndexerSkillset updated - = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), true, Context.NONE) + = client.createOrUpdateSkillsetWithResponse(mutateSkillsInSkillset(original), ifMatch(original.getETag())) .getValue(); // Update and check the eTags were changed HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.createOrUpdateSkillsetWithResponse(original, true, Context.NONE)); + () -> client.createOrUpdateSkillsetWithResponse(original, ifMatch(original.getETag()))); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(original, true)) + StepVerifier.create(asyncClient.createOrUpdateSkillsetWithResponse(original, ifMatch(original.getETag()))) .verifyErrorSatisfies(throwable -> { HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); @@ -820,52 +822,56 @@ public void createOrUpdateSkillsetIfNotChangedFailsWhenResourceChangedSyncAndAsy @Test public void deleteSkillsetIfNotChangedWorksOnlyOnCurrentResourceSync() { SearchIndexerSkillset stale - = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true, Context.NONE) - .getValue(); + = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null).getValue(); - SearchIndexerSkillset current = client.createOrUpdateSkillsetWithResponse(stale, true, Context.NONE).getValue(); + SearchIndexerSkillset current + = client.createOrUpdateSkillsetWithResponse(stale, ifMatch(stale.getETag())).getValue(); HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSkillsetWithResponse(stale, true, Context.NONE)); + () -> client.deleteSkillsetWithResponse(stale.getName(), ifMatch(stale.getETag()))); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - assertDoesNotThrow(() -> client.deleteSkillsetWithResponse(current, true, Context.NONE)); + assertDoesNotThrow(() -> client.deleteSkillsetWithResponse(current.getName(), ifMatch(current.getETag()))); } @Test public void deleteSkillsetIfNotChangedWorksOnlyOnCurrentResourceAsync() { SearchIndexerSkillset stale - = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), true) + = asyncClient.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null) .map(Response::getValue) .block(); - SearchIndexerSkillset current - = asyncClient.createOrUpdateSkillsetWithResponse(stale, true).map(Response::getValue).block(); + SearchIndexerSkillset current = asyncClient.createOrUpdateSkillsetWithResponse(stale, ifMatch(stale.getETag())) + .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(stale.getName(), ifMatch(stale.getETag()))) + .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(); + StepVerifier.create(asyncClient.deleteSkillsetWithResponse(current.getName(), ifMatch(current.getETag()))) + .expectNextCount(1) + .verifyComplete(); } @Test public void deleteSkillsetIfExistsWorksOnlyWhenResourceExistsSyncAndAsync() { - SearchIndexerSkillset skillset = client - .createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), false, Context.NONE) - .getValue(); + SearchIndexerSkillset skillset + = client.createOrUpdateSkillsetWithResponse(createSkillsetWithOcrDefaultSettings(false), null).getValue(); - client.deleteSkillsetWithResponse(skillset, true, Context.NONE); + client.deleteSkillsetWithResponse(skillset.getName(), ifMatch(skillset.getETag())); HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSkillsetWithResponse(skillset, true, Context.NONE)); + () -> client.deleteSkillsetWithResponse(skillset.getName(), ifMatch(skillset.getETag()))); 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()); - }); + StepVerifier.create(asyncClient.deleteSkillsetWithResponse(skillset.getName(), ifMatch(skillset.getETag()))) + .verifyErrorSatisfies(throwable -> { + HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); + }); } @Disabled("Test proxy issues") @@ -916,65 +922,34 @@ public void contentUnderstandingSkillSerializesCorrectly() { @Test @Disabled("Requires module access configuration for Jackson deserialization - Jackson cannot access private fields in module system") public void contentUnderstandingSkillDeserializesCorrectly() { - String json = "{\n" + " \"@odata.type\": \"#Microsoft.Skills.Util.ContentUnderstandingSkill\",\n" - + " \"inputs\": [{\"name\": \"file_data\", \"source\": \"/document/file_data\"}],\n" - + " \"outputs\": [{\"name\": \"text_sections\", \"targetName\": \"sections\"}],\n" - + " \"extractionOptions\": [\"images\", \"locationMetadata\"],\n" + " \"chunkingProperties\": {\n" - + " \"unit\": \"characters\",\n" + " \"maximumLength\": 1500,\n" + " \"overlapLength\": 150\n" - + " }\n" + "}"; + String json = "{\"@odata.type\":\"#Microsoft.Skills.Util.ContentUnderstandingSkill\"," + + "\"inputs\":[{\"name\":\"file_data\", \"source\": \"/document/file_data\"}]," + + "\"outputs\":[{\"name\":\"text_sections\", \"targetName\": \"sections\"}]," + + "\"extractionOptions\":[\"images\",\"locationMetadata\"],\"chunkingProperties\":{" + + "\"unit\":\"characters\",\"maximumLength\":1500,\"overlapLength\":150}}"; ContentUnderstandingSkill skill = BinaryData.fromString(json).toObject(ContentUnderstandingSkill.class); - assertEquals("images", skill.getExtractionOptions().get(0)); - assertEquals("locationMetadata", skill.getExtractionOptions().get(1)); - assertEquals("characters", skill.getChunkingProperties().getUnit()); + assertEquals("images", skill.getExtractionOptions().get(0).getValue()); + assertEquals("locationMetadata", skill.getExtractionOptions().get(1).getValue()); + assertEquals("characters", skill.getChunkingProperties().getUnit().getValue()); assertEquals(1500, skill.getChunkingProperties().getMaximumLength()); assertEquals(150, skill.getChunkingProperties().getOverlapLength()); } @Test public void contentUnderstandingSkillWithNullInputsThrows() { - ContentUnderstandingSkill skill = new ContentUnderstandingSkill(null, Arrays.asList()); + ContentUnderstandingSkill skill = new ContentUnderstandingSkill(null, Collections.emptyList()); assertNotNull(skill); } @Test public void contentUnderstandingSkillWithNullOutputsThrows() { ContentUnderstandingSkill skill = new ContentUnderstandingSkill( - Arrays.asList(new InputFieldMappingEntry("file_data").setSource("/document/file_data")), null); + Collections.singletonList(new InputFieldMappingEntry("file_data").setSource("/document/file_data")), null); assertNotNull(skill); } - @Test - public void contentUnderstandingSkillWithInvalidChunkingUnitThrows() { - ContentUnderstandingSkill skill = new ContentUnderstandingSkill( - Collections.singletonList(new InputFieldMappingEntry("file_data").setSource("/document/file_data")), - Collections.singletonList(new OutputFieldMappingEntry("text_sections").setTargetName("sections"))); - - try { - skill.setChunkingProperties(new ContentUnderstandingSkillChunkingProperties() - .setUnit(ContentUnderstandingSkillChunkingUnit.fromString("INVALID_UNIT")) - .setMaximumLength(1000)); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - } - - @Test - public void contentUnderstandingSkillWithNegativeChunkingLengthThrows() { - ContentUnderstandingSkill skill = new ContentUnderstandingSkill( - Collections.singletonList(new InputFieldMappingEntry("file_data").setSource("/document/file_data")), - Collections.singletonList(new OutputFieldMappingEntry("text_sections").setTargetName("sections"))); - - try { - skill.setChunkingProperties(new ContentUnderstandingSkillChunkingProperties() - .setUnit(ContentUnderstandingSkillChunkingUnit.CHARACTERS) - .setMaximumLength(-1)); - } catch (IllegalArgumentException e) { - assertTrue(true); - } - } - @Test @Disabled("Test proxy issues") public void contentUnderstandingSkillWorksWithPreviewApiVersion() { @@ -995,22 +970,21 @@ public void contentUnderstandingSkillWorksWithPreviewApiVersion() { skillsetsToDelete.add(created.getName()); } - @Test - public void contentUnderstandingSkillFailsWithOlderApiVersion() { - SearchIndexerClient indexerClient - = getSearchIndexerClientBuilder(true).serviceVersion(SearchServiceVersion.V2024_07_01).buildClient(); - - SearchIndexerSkillset skillset = createTestSkillsetContentUnderstanding(); - - HttpResponseException ex = assertThrows(HttpResponseException.class, () -> { - indexerClient.createSkillset(skillset); - }); - - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); - assertTrue(ex.getMessage().contains("ContentUnderstandingSkill") - || ex.getMessage().contains("unsupported") - || ex.getMessage().contains("not supported")); - } + // @Test + // public void contentUnderstandingSkillFailsWithOlderApiVersion() { + // SearchIndexerClient indexerClient + // = getSearchIndexerClientBuilder(true).serviceVersion(SearchServiceVersion.V2024_07_01).buildClient(); + // + // SearchIndexerSkillset skillset = createTestSkillsetContentUnderstanding(); + // + // HttpResponseException ex = assertThrows(HttpResponseException.class, + // () -> indexerClient.createSkillset(skillset)); + // + // assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); + // assertTrue(ex.getMessage().contains("ContentUnderstandingSkill") + // || ex.getMessage().contains("unsupported") + // || ex.getMessage().contains("not supported")); + // } private static InputFieldMappingEntry simpleInputFieldMappingEntry(String name, String source) { return new InputFieldMappingEntry(name).setSource(source); @@ -1044,9 +1018,8 @@ SearchIndexerSkillset createTestSkillsetImageAnalysisKeyPhrase() { .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); + return new SearchIndexerSkillset(testResourceNamer.randomName("image-analysis-key-phrase-skillset", 48), skills) + .setDescription("Skillset for testing"); } SearchIndexerSkillset createTestSkillsetLanguageDetection() { @@ -1056,14 +1029,12 @@ SearchIndexerSkillset createTestSkillsetLanguageDetection() { 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)); + SearchIndexerSkill skill = 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); + return new SearchIndexerSkillset(testResourceNamer.randomName("language-detection-skillset", 48), skill) + .setDescription("Skillset for testing"); } SearchIndexerSkillset createTestSkillsetMergeText() { @@ -1074,16 +1045,14 @@ SearchIndexerSkillset createTestSkillsetMergeText() { 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)); + SearchIndexerSkill skill = 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); + return new SearchIndexerSkillset(testResourceNamer.randomName("merge-text-skillset", 48), skill) + .setDescription("Skillset for testing"); } SearchIndexerSkillset createTestSkillsetOcrShaper() { @@ -1105,9 +1074,8 @@ SearchIndexerSkillset createTestSkillsetOcrShaper() { .setDescription("Tested Shaper skill") .setContext(CONTEXT_VALUE)); - return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-shaper-skillset", 48)) - .setDescription("Skillset for testing") - .setSkills(skills); + return new SearchIndexerSkillset(testResourceNamer.randomName("ocr-shaper-skillset", 48), skills) + .setDescription("Skillset for testing"); } SearchIndexerSkillset createSkillsetWithCognitiveServicesKey() { @@ -1117,13 +1085,12 @@ SearchIndexerSkillset createSkillsetWithCognitiveServicesKey() { 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)); + SearchIndexerSkill skill = 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) + return new SearchIndexerSkillset(testResourceNamer.randomName("cognitive-services-key-skillset", 48), skill) .setDescription("Skillset for testing") .setCognitiveServicesAccount(new DefaultCognitiveServicesAccount()); } @@ -1137,27 +1104,28 @@ SearchIndexerSkillset createTestSkillsetConditional() { List outputs = Collections.singletonList(createOutputFieldMappingEntry("output", "myLanguageCode")); - List skills - = Collections.singletonList(new ConditionalSkill(inputs, outputs).setName("myconditional") - .setDescription("Tested Conditional skill") - .setContext(CONTEXT_VALUE)); + SearchIndexerSkill skill = 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); + return new SearchIndexerSkillset(testResourceNamer.randomName("conditional-skillset", 48), skill) + .setDescription("Skillset for testing"); } 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) { + skillset.getSkills().clear(); + skillset.getSkills() + .add(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)); + return skillset; + } + + SearchIndexerSkillset createTestSkillsetOcrEntity(List categories) { List skills = new ArrayList<>(); List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), simpleInputFieldMappingEntry("queryString", "/document/queryString")); @@ -1172,20 +1140,19 @@ SearchIndexerSkillset createTestSkillsetOcrEntity(List categorie 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)); + skills.add(new EntityRecognitionSkillV3(inputs, outputs).setCategories(categories) + .setDefaultLanguageCode("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) { + String sentimentLanguageCode) { List skills = new ArrayList<>(); List inputs = Arrays.asList(simpleInputFieldMappingEntry("url", "/document/url"), simpleInputFieldMappingEntry("queryString", "/document/queryString")); @@ -1199,11 +1166,10 @@ SearchIndexerSkillset createTestSkillsetOcrSentiment(OcrSkillLanguage ocrLanguag 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)); + skills.add(new SentimentSkillV3(inputs, outputs).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"); @@ -1291,14 +1257,13 @@ SearchIndexerSkillset createSkillsetWithOcrDefaultSettings(Boolean shouldDetectO 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)); + SearchIndexerSkill skill = 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"); + skill).setDescription("Skillset for testing default configuration"); } SearchIndexerSkillset createSkillsetWithImageAnalysisDefaultSettings() { @@ -1308,12 +1273,11 @@ SearchIndexerSkillset createSkillsetWithImageAnalysisDefaultSettings() { 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)); + SearchIndexerSkill skill = new ImageAnalysisSkill(inputs, outputs).setName("myimage") + .setDescription("Tested image analysis skill") + .setContext(CONTEXT_VALUE); - return new SearchIndexerSkillset(testResourceNamer.randomName("image-analysis-skillset", 48), skills) + return new SearchIndexerSkillset(testResourceNamer.randomName("image-analysis-skillset", 48), skill) .setDescription("Skillset for testing default configuration"); } @@ -1324,12 +1288,11 @@ SearchIndexerSkillset createSkillsetWithKeyPhraseExtractionDefaultSettings() { 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)); + SearchIndexerSkill skill = 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) + return new SearchIndexerSkillset(testResourceNamer.randomName("key-phrase-extraction-skillset", 48), skill) .setDescription("Skillset for testing default configuration"); } @@ -1341,43 +1304,41 @@ SearchIndexerSkillset createSkillsetWithMergeDefaultSettings() { List outputs = Collections.singletonList(createOutputFieldMappingEntry("mergedText", "myMergedText")); - List skills = Collections.singletonList(new MergeSkill(inputs, outputs).setName("mymerge") + SearchIndexerSkill skill = new MergeSkill(inputs, outputs).setName("mymerge") .setDescription("Tested Merged Text skill") - .setContext(CONTEXT_VALUE)); + .setContext(CONTEXT_VALUE); - return new SearchIndexerSkillset(testResourceNamer.randomName("merge-skillset", 48), skills) + return new SearchIndexerSkillset(testResourceNamer.randomName("merge-skillset", 48), skill) .setDescription("Skillset for testing default configuration"); } - SearchIndexerSkillset createSkillsetWithSentimentDefaultSettings() { + SearchIndexerSkillset createSkillsetWithSentimentV3DefaultSettings() { 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)); + SearchIndexerSkill skill = new SentimentSkillV3(inputs, outputs).setName("mysentiment") + .setDescription("Tested Sentiment skill") + .setContext(CONTEXT_VALUE); - return new SearchIndexerSkillset(testResourceNamer.randomName("sentiment-skillset", 48), skills) + return new SearchIndexerSkillset(testResourceNamer.randomName("sentiment-skillset", 48), skill) .setDescription("Skillset for testing default configuration"); } - SearchIndexerSkillset createSkillsetWithEntityRecognitionDefaultSettings() { + SearchIndexerSkillset createSkillsetWithEntityRecognitionV3DefaultSettings() { 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)); + SearchIndexerSkill skill = new EntityRecognitionSkillV3(inputs, outputs).setName("myentity") + .setDescription("Tested Entity Recognition skill") + .setContext(CONTEXT_VALUE); - return new SearchIndexerSkillset(testResourceNamer.randomName("entity-recognition-skillset", 48), skills) + return new SearchIndexerSkillset(testResourceNamer.randomName("entity-recognition-skillset", 48), skill) .setDescription("Skillset for testing default configuration"); } @@ -1388,19 +1349,17 @@ SearchIndexerSkillset createSkillsetWithSplitDefaultSettings() { 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)); + SearchIndexerSkill skill = 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) + return new SearchIndexerSkillset(testResourceNamer.randomName("split-skillset", 48), skill) .setDescription("Skillset for testing default configuration"); } SearchIndexerSkillset createSkillsetWithCustomSkills() { - HashMap headers = new HashMap<>(); - headers.put("Ocp-Apim-Subscription-Key", "foobar"); + Map headers = Collections.singletonMap("Ocp-Apim-Subscription-Key", "foobar"); List inputs = Collections.singletonList(simpleInputFieldMappingEntry("text", "/document/mytext")); @@ -1410,31 +1369,30 @@ SearchIndexerSkillset createSkillsetWithCustomSkills() { SearchIndexerSkill webApiSkill = new WebApiSkill(inputs, outputs, "https://indexer-e2e-webskill.azurewebsites.net/api/InvokeTextAnalyticsV3?code=foo").setHttpMethod("POST") - .setHttpHeaders(headers) + .setHttpHeaders(new WebApiHttpHeaders().setAdditionalProperties(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"); + return new SearchIndexerSkillset(testResourceNamer.randomName("custom-skillset", 48), 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") + SearchIndexerSkill skill = new ShaperSkill(inputs, outputs).setName("myshaper") .setDescription("Tested Shaper skill") - .setContext(CONTEXT_VALUE)); + .setContext(CONTEXT_VALUE); - return new SearchIndexerSkillset(testResourceNamer.randomName("nested-skillset-with-sharperskill", 48), skills) + return new SearchIndexerSkillset(testResourceNamer.randomName("nested-skillset-with-sharperskill", 48), skill) .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/*")))); + .setInputs(simpleInputFieldMappingEntry("text", "/document/content"), + simpleInputFieldMappingEntry("images", "/document/normalized_images/*"))); } private static List createOutputFieldMappingEntry() { @@ -1460,8 +1418,7 @@ private SearchIndexerSkillset createTestSkillsetContentUnderstanding() { .setMaximumLength(1000) .setOverlapLength(100)); - return new SearchIndexerSkillset(testResourceNamer.randomName("content-understanding-skillset", 48)) - .setSkills(Collections.singletonList(skill)) + return new SearchIndexerSkillset(testResourceNamer.randomName("content-understanding-skillset", 48), skill) .setDescription("Test skillset with Content Understanding skill") .setCognitiveServicesAccount(createAIFoundryCognitiveServicesAccount()); } @@ -1471,17 +1428,16 @@ private SearchIndexerSkillset createTestSkillsetContentUnderstandingWithAllOptio Collections.singletonList(new InputFieldMappingEntry("file_data").setSource("/document/file_data")), Arrays.asList(new OutputFieldMappingEntry("text_sections").setTargetName("sections"), new OutputFieldMappingEntry("normalized_images").setTargetName("images"))) - .setExtractionOptions(Arrays.asList(ContentUnderstandingSkillExtractionOptions.IMAGES, - ContentUnderstandingSkillExtractionOptions.LOCATION_METADATA)) + .setExtractionOptions(ContentUnderstandingSkillExtractionOptions.IMAGES, + ContentUnderstandingSkillExtractionOptions.LOCATION_METADATA) .setChunkingProperties(new ContentUnderstandingSkillChunkingProperties() .setUnit(ContentUnderstandingSkillChunkingUnit.CHARACTERS) .setMaximumLength(2000) .setOverlapLength(200)); - return new SearchIndexerSkillset(testResourceNamer.randomName("content-understanding-all-options-skillset", 48)) - .setSkills(Collections.singletonList(skill)) - .setDescription("Test skillset with Content Understanding skill (all options)") - .setCognitiveServicesAccount(createAIFoundryCognitiveServicesAccount()); + return new SearchIndexerSkillset(testResourceNamer.randomName("content-understanding-all-options-skillset", 48), + skill).setDescription("Test skillset with Content Understanding skill (all options)") + .setCognitiveServicesAccount(createAIFoundryCognitiveServicesAccount()); } private CognitiveServicesAccount createAIFoundryCognitiveServicesAccount() { 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 index 7c441b629465..435130dc8c61 100644 --- 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 @@ -3,10 +3,9 @@ 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.core.util.BinaryData; import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.TestHelpers; import com.azure.search.documents.indexes.models.SynonymMap; @@ -31,6 +30,7 @@ import static com.azure.search.documents.TestHelpers.assertHttpResponseException; import static com.azure.search.documents.TestHelpers.assertObjectEquals; +import static com.azure.search.documents.TestHelpers.ifMatch; import static com.azure.search.documents.TestHelpers.verifyHttpResponseError; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -119,42 +119,50 @@ public void createSynonymMapReturnsCorrectDefinitionAsync() { @Test public void createSynonymMapReturnsCorrectDefinitionWithResponseSync() { SynonymMap expectedSynonymMap = createTestSynonymMap(); - SynonymMap actualSynonymMap = client.createSynonymMapWithResponse(expectedSynonymMap, Context.NONE).getValue(); + SynonymMap actualSynonymMap + = client.createSynonymMapWithResponse(BinaryData.fromObject(expectedSynonymMap), null) + .getValue() + .toObject(SynonymMap.class); synonymMapsToDelete.add(actualSynonymMap.getName()); assertSynonymMapsEqual(expectedSynonymMap, actualSynonymMap); - actualSynonymMap = client.getSynonymMapWithResponse(expectedSynonymMap.getName(), Context.NONE).getValue(); + actualSynonymMap = client.getSynonymMapWithResponse(expectedSynonymMap.getName(), null) + .getValue() + .toObject(SynonymMap.class); 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.createSynonymMapWithResponse(BinaryData.fromObject(expectedSynonymMap), null)) + .assertNext(response -> { + SynonymMap synonymMap = response.getValue().toObject(SynonymMap.class); + synonymMapsToDelete.add(synonymMap.getName()); + assertSynonymMapsEqual(expectedSynonymMap, synonymMap); + }) + .verifyComplete(); - StepVerifier.create(asyncClient.getSynonymMapWithResponse(expectedSynonymMap.getName())) - .assertNext(response -> assertSynonymMapsEqual(expectedSynonymMap, response.getValue())) + StepVerifier.create(asyncClient.getSynonymMapWithResponse(expectedSynonymMap.getName(), null)) + .assertNext( + response -> assertSynonymMapsEqual(expectedSynonymMap, response.getValue().toObject(SynonymMap.class))) .verifyComplete(); } @Test public void createSynonymMapFailsWithUsefulMessageOnUserErrorSync() { // Create SynonymMap with invalid synonym - SynonymMap expectedSynonymMap = createTestSynonymMap().setSynonyms("a => b => c"); + SynonymMap expectedSynonymMap = createTestSynonymMap("a => b => c"); - HttpResponseException ex - = assertThrows(HttpResponseException.class, () -> client.createSynonymMap(expectedSynonymMap)); - assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ex.getResponse().getStatusCode()); + assertHttpResponseException(() -> client.createSynonymMap(expectedSynonymMap), + HttpURLConnection.HTTP_BAD_REQUEST); } @Test public void createSynonymMapFailsWithUsefulMessageOnUserErrorAsync() { // Create SynonymMap with invalid synonym - SynonymMap expectedSynonymMap = createTestSynonymMap().setSynonyms("a => b => c"); + SynonymMap expectedSynonymMap = createTestSynonymMap("a => b => c"); StepVerifier.create(asyncClient.createSynonymMap(expectedSynonymMap)).verifyErrorSatisfies(throwable -> { HttpResponseException ex = assertInstanceOf(HttpResponseException.class, throwable); @@ -186,7 +194,7 @@ 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), + assertHttpResponseException(() -> client.getSynonymMapWithResponse(synonymMapName, null), HttpURLConnection.HTTP_NOT_FOUND, exceptionMessage); } @@ -195,7 +203,7 @@ 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)) + StepVerifier.create(asyncClient.getSynonymMapWithResponse(synonymMapName, null)) .verifyErrorSatisfies( throwable -> verifyHttpResponseError(throwable, HttpURLConnection.HTTP_NOT_FOUND, exceptionMessage)); } @@ -211,8 +219,7 @@ public void canUpdateSynonymMapSync() { SynonymMap updatedActual = client.createOrUpdateSynonymMap(updatedExpected); assertSynonymMapsEqual(updatedExpected, updatedActual); - PagedIterable synonymMaps = client.listSynonymMaps(); - assertEquals(1, synonymMaps.stream().count()); + assertEquals(1, client.listSynonymMaps().getSynonymMaps().size()); } @Test @@ -241,12 +248,10 @@ public void canUpdateSynonymMapWithResponseSync() { SynonymMap updatedExpected = new SynonymMap(initial.getName(), "newword1,newword2"); - SynonymMap updatedActual - = client.createOrUpdateSynonymMapWithResponse(updatedExpected, false, Context.NONE).getValue(); + SynonymMap updatedActual = client.createOrUpdateSynonymMapWithResponse(updatedExpected, null).getValue(); assertSynonymMapsEqual(updatedExpected, updatedActual); - PagedIterable synonymMaps = client.listSynonymMaps(); - assertEquals(1, synonymMaps.stream().count()); + assertEquals(1, client.listSynonymMaps().getSynonymMaps().size()); } @Test @@ -256,7 +261,7 @@ public void canUpdateSynonymMapWithResponseAsync() { synonymMapsToDelete.add(original.getName()); SynonymMap updatedExpected = new SynonymMap(original.getName(), "newword1,newword2"); - return asyncClient.createOrUpdateSynonymMapWithResponse(updatedExpected, false) + return asyncClient.createOrUpdateSynonymMapWithResponse(updatedExpected, null) .map(response -> Tuples.of(updatedExpected, response.getValue())); }); @@ -289,8 +294,7 @@ public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistAsync() { @Test public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistWithResponseSync() { SynonymMap expected = createTestSynonymMap(); - Response createOrUpdateResponse - = client.createOrUpdateSynonymMapWithResponse(expected, false, Context.NONE); + Response createOrUpdateResponse = client.createOrUpdateSynonymMapWithResponse(expected, null); synonymMapsToDelete.add(expected.getName()); assertEquals(HttpURLConnection.HTTP_CREATED, createOrUpdateResponse.getStatusCode()); @@ -301,7 +305,7 @@ public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistWithRespons public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistWithResponseAsync() { SynonymMap expected = createTestSynonymMap(); - StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(expected, false)).assertNext(response -> { + StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(expected, null)).assertNext(response -> { synonymMapsToDelete.add(response.getValue().getName()); assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode()); @@ -313,7 +317,7 @@ public void createOrUpdateSynonymMapCreatesWhenSynonymMapDoesNotExistWithRespons public void createOrUpdateSynonymMapIfNotExistsSucceedsOnNoResourceSync() { SynonymMap synonymMap = createTestSynonymMap(); - SynonymMap created = client.createOrUpdateSynonymMapWithResponse(synonymMap, true, Context.NONE).getValue(); + SynonymMap created = client.createOrUpdateSynonymMapWithResponse(synonymMap, null).getValue(); synonymMapsToDelete.add(created.getName()); assertNotNull(created.getETag()); @@ -323,7 +327,7 @@ public void createOrUpdateSynonymMapIfNotExistsSucceedsOnNoResourceSync() { public void createOrUpdateSynonymMapIfNotExistsSucceedsOnNoResourceAsync() { SynonymMap synonymMap = createTestSynonymMap(); - StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, true)).assertNext(response -> { + StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, null)).assertNext(response -> { synonymMapsToDelete.add(response.getValue().getName()); assertNotNull(response.getValue().getETag()); }).verifyComplete(); @@ -333,12 +337,12 @@ public void createOrUpdateSynonymMapIfNotExistsSucceedsOnNoResourceAsync() { public void createOrUpdateSynonymMapIfExistsSucceedsOnExistingResourceSync() { SynonymMap synonymMap = createTestSynonymMap(); - SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); + SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, null).getValue(); synonymMapsToDelete.add(original.getName()); - SynonymMap updated = client - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), false, Context.NONE) - .getValue(); + original.getSynonyms().clear(); + original.getSynonyms().add("mutated1, mutated2"); + SynonymMap updated = client.createOrUpdateSynonymMapWithResponse(original, null).getValue(); validateETagUpdate(original.getETag(), updated.getETag()); } @@ -348,12 +352,13 @@ public void createOrUpdateSynonymMapIfExistsSucceedsOnExistingResourceAsync() { SynonymMap synonymMap = createTestSynonymMap(); Mono> createAndUpdateMono - = asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, false).flatMap(response -> { + = asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, null).flatMap(response -> { SynonymMap original = response.getValue(); synonymMapsToDelete.add(original.getName()); - return asyncClient - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), false) + original.getSynonyms().clear(); + original.getSynonyms().add("mutated1, mutated2"); + return asyncClient.createOrUpdateSynonymMapWithResponse(original, null) .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); }); @@ -366,12 +371,13 @@ public void createOrUpdateSynonymMapIfExistsSucceedsOnExistingResourceAsync() { public void createOrUpdateSynonymMapIfNotChangedSucceedsWhenResourceUnchangedSync() { SynonymMap synonymMap = createTestSynonymMap(); - SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); + SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, null).getValue(); synonymMapsToDelete.add(original.getName()); - SynonymMap updated = client - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), true, Context.NONE) - .getValue(); + original.getSynonyms().clear(); + original.getSynonyms().add("mutated1, mutated2"); + SynonymMap updated + = client.createOrUpdateSynonymMapWithResponse(original, ifMatch(original.getETag())).getValue(); validateETagUpdate(original.getETag(), updated.getETag()); } @@ -381,12 +387,13 @@ public void createOrUpdateSynonymMapIfNotChangedSucceedsWhenResourceUnchangedAsy SynonymMap synonymMap = createTestSynonymMap(); Mono> createAndUpdateMono - = asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, false).flatMap(response -> { + = asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, null).flatMap(response -> { SynonymMap original = response.getValue(); synonymMapsToDelete.add(original.getName()); - return asyncClient - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), true) + original.getSynonyms().clear(); + original.getSynonyms().add("mutated1, mutated2"); + return asyncClient.createOrUpdateSynonymMapWithResponse(original, ifMatch(original.getETag())) .map(update -> Tuples.of(original.getETag(), update.getValue().getETag())); }); @@ -399,19 +406,20 @@ public void createOrUpdateSynonymMapIfNotChangedSucceedsWhenResourceUnchangedAsy public void createOrUpdateSynonymMapIfNotChangedFailsWhenResourceChangedSyncAndAsync() { SynonymMap synonymMap = createTestSynonymMap(); - SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, false, Context.NONE).getValue(); + SynonymMap original = client.createOrUpdateSynonymMapWithResponse(synonymMap, null).getValue(); synonymMapsToDelete.add(original.getName()); - SynonymMap updated = client - .createOrUpdateSynonymMapWithResponse(original.setSynonyms("mutated1, mutated2"), true, Context.NONE) - .getValue(); + original.getSynonyms().clear(); + original.getSynonyms().add("mutated1, mutated2"); + SynonymMap updated + = client.createOrUpdateSynonymMapWithResponse(original, ifMatch(original.getETag())).getValue(); // Update and check the eTags were changed HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.createOrUpdateSynonymMapWithResponse(original, true, Context.NONE)); + () -> client.createOrUpdateSynonymMapWithResponse(original, ifMatch(original.getETag()))); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); - StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(original, true)) + StepVerifier.create(asyncClient.createOrUpdateSynonymMapWithResponse(original, ifMatch(original.getETag()))) .verifyErrorSatisfies(throwable -> { HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); @@ -423,16 +431,16 @@ public void createOrUpdateSynonymMapIfNotChangedFailsWhenResourceChangedSyncAndA @Test public void deleteSynonymMapIsIdempotentSync() { SynonymMap synonymMap = createTestSynonymMap(); - Response deleteResponse = client.deleteSynonymMapWithResponse(synonymMap, false, Context.NONE); + Response deleteResponse = client.deleteSynonymMapWithResponse(synonymMap.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); - Response createResponse = client.createSynonymMapWithResponse(synonymMap, Context.NONE); + Response createResponse = client.createSynonymMapWithResponse(BinaryData.fromObject(synonymMap), null); assertEquals(HttpURLConnection.HTTP_CREATED, createResponse.getStatusCode()); - deleteResponse = client.deleteSynonymMapWithResponse(synonymMap, false, Context.NONE); + deleteResponse = client.deleteSynonymMapWithResponse(synonymMap.getName(), null); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, deleteResponse.getStatusCode()); - deleteResponse = client.deleteSynonymMapWithResponse(synonymMap, false, Context.NONE); + deleteResponse = client.deleteSynonymMapWithResponse(synonymMap.getName(), null); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, deleteResponse.getStatusCode()); } @@ -440,19 +448,19 @@ public void deleteSynonymMapIsIdempotentSync() { public void deleteSynonymMapIsIdempotentAsync() { SynonymMap synonymMap = createTestSynonymMap(); - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap, false)) + StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(asyncClient.createSynonymMapWithResponse(synonymMap)) + StepVerifier.create(asyncClient.createSynonymMapWithResponse(BinaryData.fromObject(synonymMap), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_CREATED, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap, false)) + StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NO_CONTENT, response.getStatusCode())) .verifyComplete(); - StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap, false)) + StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(synonymMap.getName(), null)) .assertNext(response -> assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getStatusCode())) .verifyComplete(); } @@ -471,12 +479,15 @@ public void canCreateAndListSynonymMapsSyncAndAsync() { expectedSynonyms.put(synonymMap1.getName(), synonymMap1); expectedSynonyms.put(synonymMap2.getName(), synonymMap2); - Map actualSynonyms - = client.listSynonymMaps().stream().collect(Collectors.toMap(SynonymMap::getName, sm -> sm)); + Map actualSynonyms = client.listSynonymMaps() + .getSynonymMaps() + .stream() + .collect(Collectors.toMap(SynonymMap::getName, sm -> sm)); compareMaps(expectedSynonyms, actualSynonyms, (expected, actual) -> assertObjectEquals(expected, actual, true)); - StepVerifier.create(asyncClient.listSynonymMaps().collectMap(SynonymMap::getName)) + StepVerifier.create(asyncClient.listSynonymMaps() + .map(result -> result.getSynonymMaps().stream().collect(Collectors.toMap(SynonymMap::getName, sm -> sm)))) .assertNext(actualSynonyms2 -> compareMaps(expectedSynonyms, actualSynonyms2, (expected, actual) -> assertObjectEquals(expected, actual, true))) .verifyComplete(); @@ -493,55 +504,53 @@ public void canListSynonymMapsWithSelectedFieldSyncAndAsync() { synonymMapsToDelete.add(synonymMap2.getName()); Set expectedSynonymNames = new HashSet<>(Arrays.asList(synonymMap1.getName(), synonymMap2.getName())); - Set actualSynonymNames = client.listSynonymMapNames().stream().collect(Collectors.toSet()); + Set actualSynonymNames = new HashSet<>(client.listSynonymMapNames()); 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(); + StepVerifier.create(asyncClient.listSynonymMapNames().map(HashSet::new)).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(); + SynonymMap stale = client.createOrUpdateSynonymMapWithResponse(createTestSynonymMap(), null).getValue(); // Update the resource, the eTag will be changed - SynonymMap current = client.createOrUpdateSynonymMapWithResponse(stale, true, Context.NONE).getValue(); + SynonymMap current = client.createOrUpdateSynonymMapWithResponse(stale, ifMatch(stale.getETag())).getValue(); HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSynonymMapWithResponse(stale, true, Context.NONE)); + () -> client.deleteSynonymMapWithResponse(stale.getName(), ifMatch(stale.getETag()))); 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()); - }); + StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(stale.getName(), ifMatch(stale.getETag()))) + .verifyErrorSatisfies(throwable -> { + HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); + }); - client.deleteSynonymMapWithResponse(current, true, Context.NONE); + client.deleteSynonymMapWithResponse(current.getName(), ifMatch(current.getETag())); } @Test public void deleteSynonymMapIfExistsWorksOnlyWhenResourceExistsSyncAndAsync() { - SynonymMap updated - = client.createOrUpdateSynonymMapWithResponse(createTestSynonymMap(), false, Context.NONE).getValue(); + SynonymMap updated = client.createOrUpdateSynonymMapWithResponse(createTestSynonymMap(), null).getValue(); - client.deleteSynonymMapWithResponse(updated, true, Context.NONE); + client.deleteSynonymMapWithResponse(updated.getName(), ifMatch(updated.getETag())); // Try to delete again and expect to fail HttpResponseException ex = assertThrows(HttpResponseException.class, - () -> client.deleteSynonymMapWithResponse(updated, true, Context.NONE)); + () -> client.deleteSynonymMapWithResponse(updated.getName(), ifMatch(updated.getETag()))); 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()); - }); + StepVerifier.create(asyncClient.deleteSynonymMapWithResponse(updated.getName(), ifMatch(updated.getETag()))) + .verifyErrorSatisfies(throwable -> { + HttpResponseException exAsync = assertInstanceOf(HttpResponseException.class, throwable); + assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, exAsync.getResponse().getStatusCode()); + }); } static void assertSynonymMapsEqual(SynonymMap expected, SynonymMap actual) { @@ -552,4 +561,8 @@ static void assertSynonymMapsEqual(SynonymMap expected, SynonymMap actual) { SynonymMap createTestSynonymMap() { return new SynonymMap(testResourceNamer.randomName("test-synonym", 32), "word1,word2"); } + + SynonymMap createTestSynonymMap(String... synonyms) { + return new SynonymMap(testResourceNamer.randomName("test-synonym", 32), synonyms); + } } 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 index 34bc75c03147..6f2cde4af1e0 100644 --- 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 @@ -5,71 +5,72 @@ 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 com.azure.json.JsonWriter; 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.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import static com.azure.search.documents.TestHelpers.convertToMapStringObject; +import static com.azure.search.documents.TestHelpers.createIndexAction; + @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(), createResult("2"))); + IndexDocumentsResult result = createResults(createSucceededResult(), createResult("2")); assertRetryBatchEmpty(result); } @Test public void clientShouldNotRetryBatchWithAllNonRetriableFailures() { - IndexDocumentsResult result = new IndexDocumentsResult( - Arrays.asList(createFailedResult("1", 500), createFailedResult("2", 404), createFailedResult("3", 400))); + IndexDocumentsResult result + = createResults(createFailedResult("1", 500), createFailedResult("2", 404), createFailedResult("3", 400)); assertRetryBatchEmpty(result); } @Test public void clientShouldNotRetryBatchWithSuccessesAndNonRetriableFailures() { - IndexDocumentsResult result - = new IndexDocumentsResult(Arrays.asList(createSucceededResult(), createFailedResult("2", 500), - createFailedResult("3", 404), createResult("4"), createFailedResult("5", 400))); + IndexDocumentsResult result = createResults(createSucceededResult(), 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))); + IndexDocumentsResult result + = createResults(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(), createFailedResult("2", 500), - createFailedResult("3", 422), createFailedResult("4", 404), createFailedResult("5", 409), - createFailedResult("6", 400), createResult("7"), createFailedResult("8", 503))); + IndexDocumentsResult result = createResults(createSucceededResult(), 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(), createFailedResult("2", 502), createFailedResult("3", 503))); + IndexDocumentsResult result + = createResults(createSucceededResult(), createFailedResult("2", 502), createFailedResult("3", 503)); assertRetryBatchContains(result, Collections.singletonList("3")); } @@ -89,13 +90,13 @@ private static void assertRetryBatchContains(IndexDocumentsResult result, List action.getDocument().getHotelId()) + .map(action -> action.getAdditionalProperties().get("HotelId")) .collect(Collectors.toList())); } - public static Object getValueFromDocHelper(IndexAction action) { - if (action.getDocument() != null) { - return action.getDocument().get(KEY_FIELD_NAME); + public static Object getValueFromDocHelper(IndexAction action) { + if (action.getAdditionalProperties() != null) { + return action.getAdditionalProperties().get(KEY_FIELD_NAME); } // else if (action.getParamMap() != null) { // return action.getParamMap().get(KEY_FIELD_NAME); @@ -103,40 +104,70 @@ public static Object getValueFromDocHelper(IndexAction action) { return null; } - private static IndexBatchBase getRetryBatch(IndexDocumentsResult result) { + private static IndexDocumentsBatch 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())); + IndexDocumentsBatch originalBatch = new IndexDocumentsBatch(allKeys.stream() + .map(key -> createIndexAction(IndexActionType.UPLOAD, Collections.singletonMap(KEY_FIELD_NAME, key))) + .collect(Collectors.toList())); return exception.findFailedActionsToRetry(originalBatch, KEY_FIELD_NAME); } - private static IndexBatchBase getTypedRetryBatch(IndexDocumentsResult result) { + private static IndexDocumentsBatch 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); + IndexDocumentsBatch originalBatch = new IndexDocumentsBatch(allKeys.stream() + .map( + key -> createIndexAction(IndexActionType.UPLOAD, convertToMapStringObject(new Hotel().setHotelId(key)))) + .collect(Collectors.toList())); + return exception.findFailedActionsToRetry(originalBatch, "HotelId"); + } + + private static String createSucceededResult() { + return createResult("1", true, 200, null); } - private static IndexingResult createSucceededResult() { - return new IndexingResult("1", true, 200); + private static String createResult(String key) { + return createResult(key, true, 201, null); } - private static IndexingResult createResult(String key) { - return new IndexingResult(key, true, 201); + private String createFailedResult(String key, int statusCode) { + return createResult(key, false, statusCode, "Something went wrong"); + } + + private static IndexDocumentsResult createResults(String... results) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeStartObject() + .writeArrayField("value", results, JsonWriter::writeRawValue) + .writeEndObject(); + } + + try (JsonReader jsonReader = JsonProviders.createReader(outputStream.toByteArray())) { + return IndexDocumentsResult.fromJson(jsonReader); + } + } catch (IOException ex) { + throw new UncheckedIOException(ex); + } } - 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); + private static String createResult(String key, boolean status, int statusCode, String errorMessage) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (JsonWriter jsonWriter = JsonProviders.createWriter(outputStream)) { + jsonWriter.writeStartObject() + .writeStringField("key", key) + .writeBooleanField("status", status) + .writeIntField("statusCode", statusCode) + .writeStringField("errorMessage", errorMessage) + .writeEndObject(); + } + + return new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new UncheckedIOException(ex); } } } 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 index adeef2ed0b68..3d39912799d3 100644 --- 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 @@ -3,29 +3,17 @@ package com.azure.search.documents.models; import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; 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.SearchAlias; -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 com.azure.search.documents.indexes.*; +import com.azure.search.documents.indexes.models.*; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; @@ -39,7 +27,9 @@ import java.util.function.Supplier; import java.util.stream.Stream; +import static com.azure.core.util.BinaryData.fromObject; import static java.util.Collections.emptyList; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @Execution(ExecutionMode.CONCURRENT) @@ -47,282 +37,238 @@ 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); - } + UrlRewriteException urlRewriteException = assertThrows(UrlRewriteException.class, apiCall::call); + 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())); + String endpoint = "https://test.search.windows.net"; + HttpClient urlRewriteHttpClient = new HttpClient() { + @Override + public Mono send(HttpRequest request) { + return Mono.error(new UrlRewriteException("Url rewritten", request.getUrl().toString())); + } + + @Override + public HttpResponse sendSync(HttpRequest request, Context context) { + throw new UrlRewriteException("Url rewritten", request.getUrl().toString()); + } + }; - SearchClientBuilder searchClientBuilder = new SearchClientBuilder().indexName("test") - .endpoint("https://test.search.windows.net") + SearchIndexClientBuilder indexClientBuilder = new SearchIndexClientBuilder().endpoint(endpoint) .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(); + SearchIndexClient indexClient = indexClientBuilder.buildClient(); + SearchIndexAsyncClient indexAsyncClient = indexClientBuilder.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(); + SearchClient searchClient = indexClient.getSearchClient("test"); + SearchAsyncClient searchAsyncClient = indexAsyncClient.getSearchAsyncClient("test"); - 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(); + SearchIndexerClientBuilder indexerClientBuilder = new SearchIndexerClientBuilder().endpoint(endpoint) + .credential(new MockTokenCredential()) + .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))) + .addPolicy(new SearchRequestUrlRewriterPolicy()) + .httpClient(urlRewriteHttpClient); + SearchIndexerClient indexerClient = indexerClientBuilder.buildClient(); + SearchIndexerAsyncClient indexerAsyncClient = indexerClientBuilder.buildAsyncClient(); - String docsUrl = "https://test.search.windows.net/indexes/test/docs"; + String indexesUrl = endpoint + "/indexes"; + String docsUrl = indexesUrl + "/test/docs"; + String indexUrl = indexesUrl + "/index"; + String indexersUrl = endpoint + "/indexers"; SearchIndex index = new SearchIndex("index"); - String indexUrl = "https://test.search.windows.net/indexes/index"; + String synonymMapsUrl = endpoint + "/synonymmaps"; SynonymMap synonymMap = new SynonymMap("synonym"); - String synonymMapUrl = "https://test.search.windows.net/synonymmaps/synonym"; + String synonymUrl = synonymMapsUrl + "/synonym"; + String aliasesUrl = endpoint + "/aliases"; SearchAlias alias = new SearchAlias("alias", emptyList()); - String aliasUrl = "https://test.search.windows.net/aliases/alias"; + String aliasUrl = aliasesUrl + "/alias"; - SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection("datasource"); - String dataSourceUrl = "https://test.search.windows.net/datasources/datasource"; + String dataSourcesUrl = endpoint + "/datasources"; + SearchIndexerDataSourceConnection dataSource + = new SearchIndexerDataSourceConnection("datasource", SearchIndexerDataSourceType.AZURE_BLOB, + new DataSourceCredentials().setConnectionString("fake"), new SearchIndexerDataContainer("fake")); + String dataSourceUrl = dataSourcesUrl + "/datasource"; - SearchIndexer indexer = new SearchIndexer("indexer"); - String indexerUrl = "https://test.search.windows.net/indexers/indexer"; + SearchIndexer indexer = new SearchIndexer("indexer", "dataSourceName", "targetIndexName"); + String indexerUrl = indexersUrl + "/indexer"; + String skillsetsUrl = endpoint + "/skillsets"; SearchIndexerSkillset skillset = new SearchIndexerSkillset("skillset"); - String skillsetUrl = "https://test.search.windows.net/skillsets/skillset"; + String skillsetUrl = skillsetsUrl + "/skillset"; + + String servicestatsUrl = endpoint + "/servicestats"; return Stream.of( - Arguments.of( - toCallable( - () -> searchClient.indexDocumentsWithResponse(new IndexDocumentsBatch<>(), null, Context.NONE)), + Arguments.of(toCallable(() -> searchClient.indexDocuments(new IndexDocumentsBatch())), 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()), + Arguments.of(toCallable(() -> searchClient.getDocumentWithResponse("test", null)), docsUrl + "/test"), + Arguments.of(toCallable(() -> searchClient.getDocumentCountWithResponse(null)), docsUrl + "/$count"), + Arguments.of(toCallable(() -> searchClient.search(null).iterator().hasNext()), docsUrl + "/search.post.search"), + Arguments.of(toCallable(() -> searchClient.suggest(new SuggestOptions("suggest", "suggester"))), + docsUrl + "/search.post.suggest"), 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()), + toCallable(() -> searchClient.autocomplete(new AutocompleteOptions("autocomplete", "suggester"))), docsUrl + "/search.post.autocomplete"), - Arguments.of(toCallable(searchAsyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch<>(), null)), + Arguments.of( + toCallable(searchAsyncClient.indexDocumentsWithResponse(new IndexDocumentsBatch(), null, 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, null)), docsUrl + "/search.post.search"), - Arguments.of(toCallable(searchAsyncClient.suggest("suggest", "suggester", null)), + Arguments.of(toCallable(searchAsyncClient.getDocumentWithResponse("test", null)), docsUrl + "/test"), + Arguments.of(toCallable(searchAsyncClient.getDocumentCountWithResponse(null)), docsUrl + "/$count"), + Arguments.of(toCallable(searchAsyncClient.search(null)), docsUrl + "/search.post.search"), + Arguments.of(toCallable(searchAsyncClient.suggest(new SuggestOptions("suggest", "suggester"))), docsUrl + "/search.post.suggest"), - Arguments.of(toCallable(searchAsyncClient.autocomplete("autocomplete", "suggester", null)), + Arguments.of( + toCallable(searchAsyncClient.autocomplete(new AutocompleteOptions("autocomplete", "suggester"))), 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)), + Arguments.of(toCallable(() -> indexClient.createIndexWithResponse(fromObject(index), null)), indexesUrl), + Arguments.of(toCallable(() -> indexClient.getIndexWithResponse("index", null)), indexUrl), + Arguments.of(toCallable(() -> indexClient.getIndexStatisticsWithResponse("index", null)), 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)), + Arguments.of(toCallable(() -> indexClient.listIndexes().iterator().hasNext()), indexesUrl), + Arguments.of(toCallable(() -> indexClient.listIndexNames().iterator().hasNext()), indexesUrl), + Arguments.of(toCallable(() -> indexClient.createOrUpdateIndexWithResponse(index, null)), indexUrl), + Arguments.of(toCallable(() -> indexClient.deleteIndexWithResponse(index.getName(), null)), indexUrl), + Arguments.of(toCallable(() -> indexClient.analyzeText("index", new AnalyzeTextOptions("text"))), 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(() -> indexClient.createSynonymMapWithResponse(fromObject(synonymMap), null)), + synonymMapsUrl), + Arguments.of(toCallable(() -> indexClient.getSynonymMapWithResponse("synonym", null)), synonymUrl), + Arguments.of(toCallable(indexClient::listSynonymMaps), synonymMapsUrl), + Arguments.of(toCallable(indexClient::listSynonymMapNames), synonymMapsUrl), + Arguments.of(toCallable(() -> indexClient.createOrUpdateSynonymMapWithResponse(synonymMap, null)), + synonymUrl), + Arguments.of(toCallable(() -> indexClient.deleteSynonymMapWithResponse(synonymMap.getName(), null)), + synonymUrl), + Arguments.of(toCallable(() -> indexClient.getServiceStatisticsWithResponse(null)), servicestatsUrl), - Arguments.of(toCallable(() -> searchIndexClient.createAliasWithResponse(alias, Context.NONE)), - "https://test.search.windows.net/aliases"), - Arguments.of( - toCallable(() -> searchIndexClient.createOrUpdateAliasWithResponse(alias, false, Context.NONE)), - aliasUrl), - Arguments.of(toCallable(() -> searchIndexClient.getAliasWithResponse("alias", Context.NONE)), aliasUrl), - Arguments.of(toCallable(() -> searchIndexClient.deleteAliasWithResponse(alias, true, Context.NONE)), - aliasUrl), - Arguments.of(toCallable(() -> searchIndexClient.listAliases(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/aliases"), + Arguments.of(toCallable(() -> indexClient.createAliasWithResponse(fromObject(alias), null)), aliasesUrl), + Arguments.of(toCallable(() -> indexClient.createOrUpdateAliasWithResponse(alias, null)), aliasUrl), + Arguments.of(toCallable(() -> indexClient.getAliasWithResponse("alias", null)), aliasUrl), + Arguments.of(toCallable(() -> indexClient.deleteAliasWithResponse(alias.getName(), null)), aliasUrl), + Arguments.of(toCallable(() -> indexClient.listAliases(null).iterator().hasNext()), aliasesUrl), - 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")), + Arguments.of(toCallable(indexAsyncClient.createIndexWithResponse(fromObject(index), null)), indexesUrl), + Arguments.of(toCallable(indexAsyncClient.getIndexWithResponse("index", null)), indexUrl), + Arguments.of(toCallable(indexAsyncClient.getIndexStatisticsWithResponse("index", null)), 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(() -> searchIndexClient.createAliasWithResponse(alias, Context.NONE)), - "https://test.search.windows.net/aliases"), - Arguments.of( - toCallable(() -> searchIndexClient.createOrUpdateAliasWithResponse(alias, false, Context.NONE)), - aliasUrl), - Arguments.of(toCallable(() -> searchIndexClient.getAliasWithResponse("alias", Context.NONE)), aliasUrl), - Arguments.of(toCallable(() -> searchIndexClient.deleteAliasWithResponse(alias, true, Context.NONE)), - aliasUrl), - Arguments.of(toCallable(() -> searchIndexClient.listAliases(Context.NONE).iterator().hasNext()), - "https://test.search.windows.net/aliases"), - 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(indexAsyncClient.listIndexes()), indexesUrl), + Arguments.of(toCallable(indexAsyncClient.listIndexNames()), indexesUrl), + Arguments.of(toCallable(indexAsyncClient.createOrUpdateIndexWithResponse(index, null)), indexUrl), + Arguments.of(toCallable(indexAsyncClient.deleteIndexWithResponse(index.getName(), null)), indexUrl), + Arguments.of(toCallable(indexAsyncClient.analyzeText("index", new AnalyzeTextOptions("text"))), + indexUrl + "/search.analyze"), + Arguments.of(toCallable(indexAsyncClient.createSynonymMapWithResponse(fromObject(synonymMap), null)), + synonymMapsUrl), + Arguments.of(toCallable(indexAsyncClient.getSynonymMapWithResponse("synonym", null)), synonymUrl), + Arguments.of(toCallable(indexAsyncClient.listSynonymMaps()), synonymMapsUrl), + Arguments.of(toCallable(indexAsyncClient.listSynonymMapNames()), synonymMapsUrl), + Arguments.of(toCallable(indexAsyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, null)), + synonymUrl), + Arguments.of(toCallable(indexAsyncClient.deleteSynonymMapWithResponse(synonymMap.getName(), null)), + synonymUrl), + Arguments.of(toCallable(indexAsyncClient.getServiceStatisticsWithResponse(null)), servicestatsUrl), + Arguments.of(toCallable(() -> indexClient.createAliasWithResponse(fromObject(alias), null)), aliasesUrl), + Arguments.of(toCallable(() -> indexClient.createOrUpdateAliasWithResponse(alias, null)), aliasUrl), + Arguments.of(toCallable(() -> indexClient.getAliasWithResponse("alias", null)), aliasUrl), + Arguments.of(toCallable(() -> indexClient.deleteAliasWithResponse(alias.getName(), null)), aliasUrl), + Arguments.of(toCallable(() -> indexClient.listAliases(null).iterator().hasNext()), aliasesUrl), Arguments.of( - toCallable(() -> searchIndexerClient.getDataSourceConnectionWithResponse("datasource", Context.NONE)), + toCallable(() -> indexerClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, null)), 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)), + toCallable(() -> indexerClient.createDataSourceConnectionWithResponse(fromObject(dataSource), null)), + dataSourcesUrl), + Arguments.of(toCallable(() -> indexerClient.getDataSourceConnectionWithResponse("datasource", null)), dataSourceUrl), - Arguments.of(toCallable(() -> searchIndexerClient.createIndexerWithResponse(indexer, Context.NONE)), - "https://test.search.windows.net/indexers"), + Arguments.of(toCallable(indexerClient::listDataSourceConnections), dataSourcesUrl), + Arguments.of(toCallable(indexerClient::listDataSourceConnectionNames), dataSourcesUrl), 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)), + toCallable(() -> indexerClient.deleteDataSourceConnectionWithResponse(dataSource.getName(), null)), + dataSourceUrl), + Arguments.of(toCallable(() -> indexerClient.createIndexerWithResponse(fromObject(indexer), null)), + indexersUrl), + Arguments.of(toCallable(() -> indexerClient.createOrUpdateIndexerWithResponse(indexer, null)), indexerUrl), + Arguments.of(toCallable(indexerClient::listIndexers), indexersUrl), + Arguments.of(toCallable(indexerClient::listIndexerNames), indexersUrl), + Arguments.of(toCallable(() -> indexerClient.getIndexerWithResponse("indexer", null)), indexerUrl), + Arguments.of(toCallable(() -> indexerClient.deleteIndexerWithResponse(indexer.getName(), null)), indexerUrl), - Arguments.of(toCallable(() -> searchIndexerClient.resetIndexerWithResponse("indexer", Context.NONE)), + Arguments.of(toCallable(() -> indexerClient.resetIndexerWithResponse("indexer", null)), indexerUrl + "/search.reset"), - Arguments.of(toCallable(() -> searchIndexerClient.runIndexerWithResponse("indexer", Context.NONE)), + Arguments.of(toCallable(() -> indexerClient.runIndexerWithResponse("indexer", null)), indexerUrl + "/search.run"), - Arguments.of(toCallable(() -> searchIndexerClient.getIndexerStatusWithResponse("indexer", Context.NONE)), + Arguments.of(toCallable(() -> indexerClient.getIndexerStatusWithResponse("indexer", null)), indexerUrl + "/search.status"), - Arguments.of(toCallable(() -> searchIndexerClient.resetDocumentsWithResponse(indexer, null, emptyList(), - emptyList(), Context.NONE)), indexerUrl + "/search.resetdocs"), - 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)), + Arguments.of(toCallable(() -> indexerClient.resetDocumentsWithResponse(indexer.getName(), null)), + indexerUrl + "/search.resetdocs"), + Arguments.of(toCallable(() -> indexerClient.createSkillsetWithResponse(fromObject(skillset), null)), + skillsetsUrl), + Arguments.of(toCallable(() -> indexerClient.getSkillsetWithResponse("skillset", null)), skillsetUrl), + Arguments.of(toCallable(indexerClient::listSkillsets), skillsetsUrl), + Arguments.of(toCallable(indexerClient::listSkillsetNames), skillsetsUrl), + Arguments.of(toCallable(() -> indexerClient.createOrUpdateSkillsetWithResponse(skillset, null)), skillsetUrl), - Arguments.of(toCallable(() -> searchIndexerClient.deleteSkillsetWithResponse(skillset, true, Context.NONE)), + Arguments.of(toCallable(() -> indexerClient.deleteSkillsetWithResponse(skillset.getName(), null)), skillsetUrl), - Arguments.of( - toCallable(() -> searchIndexerClient.resetSkillsWithResponse(skillset, emptyList(), Context.NONE)), + Arguments.of(toCallable( + () -> indexerClient.resetSkillsWithResponse(skillset.getName(), fromObject(new SkillNames()), null)), skillsetUrl + "/search.resetskills"), Arguments.of( - toCallable(searchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, true)), + toCallable(indexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse(dataSource, null)), dataSourceUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.createDataSourceConnectionWithResponse(dataSource)), - "https://test.search.windows.net/datasources"), - Arguments.of(toCallable(searchIndexerAsyncClient.getDataSourceConnectionWithResponse("datasource")), + Arguments.of( + toCallable(indexerAsyncClient.createDataSourceConnectionWithResponse(fromObject(dataSource), null)), + dataSourcesUrl), + Arguments.of(toCallable(indexerAsyncClient.getDataSourceConnectionWithResponse("datasource", null)), 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)), + Arguments.of(toCallable(indexerAsyncClient.listDataSourceConnections()), dataSourcesUrl), + Arguments.of(toCallable(indexerAsyncClient.listDataSourceConnectionNames()), dataSourcesUrl), + Arguments.of( + toCallable(indexerAsyncClient.deleteDataSourceConnectionWithResponse(dataSource.getName(), null)), 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")), + Arguments.of(toCallable(indexerAsyncClient.createIndexerWithResponse(fromObject(indexer), null)), + indexersUrl), + Arguments.of(toCallable(indexerAsyncClient.createOrUpdateIndexerWithResponse(indexer, null)), indexerUrl), + Arguments.of(toCallable(indexerAsyncClient.listIndexers()), indexersUrl), + Arguments.of(toCallable(indexerAsyncClient.listIndexerNames()), indexersUrl), + Arguments.of(toCallable(indexerAsyncClient.getIndexerWithResponse("indexer", null)), indexerUrl), + Arguments.of(toCallable(indexerAsyncClient.deleteIndexerWithResponse(indexer.getName(), null)), indexerUrl), + Arguments.of(toCallable(indexerAsyncClient.resetIndexerWithResponse("indexer", null)), indexerUrl + "/search.reset"), - Arguments.of(toCallable(searchIndexerAsyncClient.runIndexerWithResponse("indexer")), + Arguments.of(toCallable(indexerAsyncClient.runIndexerWithResponse("indexer", null)), indexerUrl + "/search.run"), - Arguments.of(toCallable(searchIndexerAsyncClient.getIndexerStatusWithResponse("indexer")), + Arguments.of(toCallable(indexerAsyncClient.getIndexerStatusWithResponse("indexer", null)), indexerUrl + "/search.status"), - Arguments.of( - toCallable( - searchIndexerAsyncClient.resetDocumentsWithResponse(indexer, null, emptyList(), emptyList())), + Arguments.of(toCallable(indexerAsyncClient.resetDocumentsWithResponse(indexer.getName(), null)), indexerUrl + "/search.resetdocs"), - 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)), + Arguments.of(toCallable(indexerAsyncClient.createSkillsetWithResponse(fromObject(skillset), null)), + skillsetsUrl), + Arguments.of(toCallable(indexerAsyncClient.getSkillsetWithResponse("skillset", null)), skillsetUrl), + Arguments.of(toCallable(indexerAsyncClient.listSkillsets()), skillsetsUrl), + Arguments.of(toCallable(indexerAsyncClient.listSkillsetNames()), skillsetsUrl), + Arguments.of(toCallable(indexerAsyncClient.createOrUpdateSkillsetWithResponse(skillset, null)), + skillsetUrl), + Arguments.of(toCallable(indexerAsyncClient.deleteSkillsetWithResponse(skillset.getName(), null)), skillsetUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.deleteSkillsetWithResponse(skillset, true)), skillsetUrl), - Arguments.of(toCallable(searchIndexerAsyncClient.resetSkillsWithResponse(skillset, emptyList())), + Arguments.of( + toCallable( + indexerAsyncClient.resetSkillsWithResponse(skillset.getName(), fromObject(new SkillNames()), null)), skillsetUrl + "/search.resetskills")); } private static Callable toCallable(Supplier apiCall) { - return () -> apiCall; + return apiCall::get; } private static Callable toCallable(Mono apiCall) { 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/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/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/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/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/AddressCircularDependencies.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/AddressCircularDependencies.java similarity index 83% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/AddressCircularDependencies.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/AddressCircularDependencies.java index 4aa88cdb7851..4f7ba885ac9a 100644 --- 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/testingmodels/AddressCircularDependencies.java @@ -1,13 +1,16 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; + +import com.azure.search.documents.indexes.ComplexField; /** * The address model class to test circular dependencies. */ public class AddressCircularDependencies { + @ComplexField(name = "Hotel") private HotelCircularDependencies hotel; /** diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Author.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Author.java new file mode 100644 index 000000000000..796a41cbc323 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Author.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +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.BasicField; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; + +public class Author implements JsonSerializable { + @BasicField(name = "FirstName") + @JsonProperty(value = "FirstName") + private String firstName; + + @BasicField(name = "LastName") + @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; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("FirstName", firstName) + .writeStringField("LastName", lastName) + .writeEndObject(); + } + + public static Author fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Author author = new Author(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("FirstName".equals(fieldName)) { + author.firstName = reader.getString(); + } else if ("LastName".equals(fieldName)) { + author.lastName = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return author; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Book.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Book.java new file mode 100644 index 000000000000..8d252e975837 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Book.java @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +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.BasicField; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.Objects; + +public class Book implements JsonSerializable { + @BasicField(name = "ISBN") + @JsonProperty(value = "ISBN") + private String ISBN; + + @BasicField(name = "Title") + @JsonProperty(value = "Title") + private String title; + + @BasicField(name = "Author") + @JsonProperty(value = "Author") + private Author author; + + @BasicField(name = "PublishDate") + @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; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("ISBN", ISBN) + .writeStringField("Title", title) + .writeJsonField("Author", author) + .writeStringField("PublishDate", Objects.toString(publishDate, null)) + .writeEndObject(); + } + + public static Book fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Book book = new Book(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("ISBN".equals(fieldName)) { + book.ISBN = reader.getString(); + } else if ("Title".equals(fieldName)) { + book.title = reader.getString(); + } else if ("Author".equals(fieldName)) { + book.author = Author.fromJson(reader); + } else if ("PublishDate".equals(fieldName)) { + book.publishDate + = reader.getNullable(nonNull -> CoreUtils.parseBestOffsetDateTime(nonNull.getString())); + } else { + reader.skipChildren(); + } + } + + return book; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Bucket.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Bucket.java new file mode 100644 index 000000000000..9c00e05a4cb5 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Bucket.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +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.BasicField; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; + +public class Bucket implements JsonSerializable { + @BasicField(name = "BucketName") + @JsonProperty(value = "BucketName") + private String bucketName; + + @BasicField(name = "Count") + @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; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("BucketName", bucketName) + .writeIntField("Count", count) + .writeEndObject(); + } + + public static Bucket fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + Bucket bucket = new Bucket(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("BucketName".equals(fieldName)) { + bucket.bucketName = reader.getString(); + } else if ("Count".equals(fieldName)) { + bucket.count = reader.getInt(); + } else { + reader.skipChildren(); + } + } + + return bucket; + }); + } +} 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/testingmodels/Car.java similarity index 72% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Car.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Car.java index 98e437b3bde1..4d87ff28afb9 100644 --- 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/testingmodels/Car.java @@ -1,10 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -public class Car { +import com.azure.search.documents.indexes.BasicField; +public class Car { + @BasicField(name = "Color") private String color; + + @BasicField(name = "Type") private String type; public String getColor() { diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Entry.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Entry.java new file mode 100644 index 000000000000..e30c7594884b --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Entry.java @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +import com.azure.search.documents.indexes.BasicField; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.OffsetDateTime; + +@SuppressWarnings("ALL") +public class Entry { + @BasicField(name = "Entry") + @JsonProperty + OffsetDateTime offsetDateTime; + + public OffsetDateTime offsetDateTime() { + return offsetDateTime; + } + + public void offsetDateTime(OffsetDateTime offsetDateTime) { + this.offsetDateTime = offsetDateTime; + } +} 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/testingmodels/Foo.java similarity index 76% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Foo.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Foo.java index a3978236379d..2b34d2b1c342 100644 --- 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/testingmodels/Foo.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.SimpleField; +import com.azure.search.documents.indexes.BasicField; public class Foo { - @SimpleField(isKey = true) + @BasicField(name = "IntValue", isKey = BasicField.BooleanHelper.TRUE) private String intValue; + @BasicField(name = "StringValue") private String stringValue; public Foo() { diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Hotel.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Hotel.java new file mode 100644 index 000000000000..71cb080c0192 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/Hotel.java @@ -0,0 +1,280 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +import com.azure.core.models.GeoPoint; +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.BasicField; +import com.azure.search.documents.indexes.ComplexField; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@SuppressWarnings("UseOfObsoleteDateTimeApi") +@JsonIgnoreProperties(ignoreUnknown = true) +public class Hotel implements JsonSerializable { + @BasicField( + name = "HotelId", + isSearchable = BasicField.BooleanHelper.TRUE, + isKey = BasicField.BooleanHelper.TRUE, + isSortable = BasicField.BooleanHelper.TRUE) + @JsonProperty(value = "HotelId") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String hotelId; + + @BasicField( + name = "HotelName", + isSearchable = BasicField.BooleanHelper.TRUE, + isSortable = BasicField.BooleanHelper.TRUE, + analyzerName = "en.lucene") + @JsonProperty(value = "HotelName") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String hotelName; + + @BasicField(name = "Description") + @JsonProperty(value = "Description") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String description; + + @JsonProperty(value = "Description_fr") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String descriptionFr; + + @BasicField(name = "Category") + @JsonProperty(value = "Category") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String category; + + @BasicField(name = "Tags", isSearchable = BasicField.BooleanHelper.TRUE) + @JsonProperty(value = "Tags") + @JsonInclude(JsonInclude.Include.NON_NULL) + private List tags; + + @BasicField(name = "ParkingIncluded") + @JsonProperty(value = "ParkingIncluded") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Boolean parkingIncluded; + + @BasicField(name = "SmokingAllowed") + @JsonProperty(value = "SmokingAllowed") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Boolean smokingAllowed; + + @BasicField(name = "LastRenovationDate") + @JsonProperty(value = "LastRenovationDate") + @JsonInclude(JsonInclude.Include.NON_NULL) + private OffsetDateTime lastRenovationDate; + + @BasicField(name = "Rating") + @JsonProperty(value = "Rating") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Integer rating; + + @BasicField(name = "Location") + @JsonProperty(value = "Location") + @JsonInclude(JsonInclude.Include.NON_NULL) + private GeoPoint location; + + @ComplexField(name = "Address") + @JsonProperty(value = "Address") + @JsonInclude(JsonInclude.Include.NON_NULL) + private HotelAddress address; + + @ComplexField(name = "Rooms") + @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 OffsetDateTime lastRenovationDate() { + return this.lastRenovationDate; + } + + public Hotel lastRenovationDate(OffsetDateTime lastRenovationDate) { + this.lastRenovationDate = lastRenovationDate; + 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; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("HotelId", hotelId) + .writeStringField("HotelName", hotelName) + .writeStringField("Description", description) + .writeStringField("Description_fr", descriptionFr) + .writeStringField("Category", category) + .writeArrayField("Tags", tags, JsonWriter::writeString) + .writeBooleanField("ParkingIncluded", parkingIncluded) + .writeBooleanField("SmokingAllowed", smokingAllowed) + .writeStringField("LastRenovationDate", Objects.toString(lastRenovationDate, null)) + .writeNumberField("Rating", rating) + .writeJsonField("Location", location) + .writeJsonField("Address", address) + .writeArrayField("Rooms", rooms, JsonWriter::writeJson) + .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 ("Description_fr".equals(fieldName)) { + hotel.descriptionFr = reader.getString(); + } else if ("Category".equals(fieldName)) { + hotel.category = reader.getString(); + } else if ("Tags".equals(fieldName)) { + hotel.tags = reader.readArray(JsonReader::getString); + } else if ("ParkingIncluded".equals(fieldName)) { + hotel.parkingIncluded = reader.getNullable(JsonReader::getBoolean); + } else if ("SmokingAllowed".equals(fieldName)) { + hotel.smokingAllowed = reader.getNullable(JsonReader::getBoolean); + } else if ("LastRenovationDate".equals(fieldName)) { + hotel.lastRenovationDate = reader.getNullable(nonNull -> OffsetDateTime.parse(nonNull.getString())); + } else if ("Rating".equals(fieldName)) { + hotel.rating = reader.getNullable(JsonReader::getInt); + } else if ("Location".equals(fieldName)) { + hotel.location = GeoPoint.fromJson(reader); + } else if ("Address".equals(fieldName)) { + hotel.address = HotelAddress.fromJson(reader); + } else if ("Rooms".equals(fieldName)) { + hotel.rooms = reader.readArray(HotelRoom::fromJson); + } else { + reader.skipChildren(); + } + } + + return hotel; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelAddress.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelAddress.java new file mode 100644 index 000000000000..529c15ddfcb0 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelAddress.java @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +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.BasicField; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; + +public class HotelAddress implements JsonSerializable { + @BasicField(name = "StreetAddress", isFacetable = BasicField.BooleanHelper.TRUE) + @JsonProperty(value = "StreetAddress") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String streetAddress; + + @BasicField( + name = "City", + isSearchable = BasicField.BooleanHelper.TRUE, + isFilterable = BasicField.BooleanHelper.TRUE) + @JsonProperty(value = "City") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String city; + + @BasicField(name = "StateProvince", isSearchable = BasicField.BooleanHelper.TRUE) + @JsonProperty(value = "StateProvince") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String stateProvince; + + @BasicField(name = "Country", isSearchable = BasicField.BooleanHelper.TRUE, synonymMapNames = { "fieldbuilder" }) + @JsonProperty(value = "Country") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String country; + + @BasicField(name = "PostalCode") + @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; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("StreetAddress", streetAddress) + .writeStringField("City", city) + .writeStringField("StateProvince", stateProvince) + .writeStringField("Country", country) + .writeStringField("PostalCode", postalCode) + .writeEndObject(); + } + + public static HotelAddress fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HotelAddress hotelAddress = new HotelAddress(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("StreetAddress".equals(fieldName)) { + hotelAddress.streetAddress = reader.getString(); + } else if ("City".equals(fieldName)) { + hotelAddress.city = reader.getString(); + } else if ("StateProvince".equals(fieldName)) { + hotelAddress.stateProvince = reader.getString(); + } else if ("Country".equals(fieldName)) { + hotelAddress.country = reader.getString(); + } else if ("PostalCode".equals(fieldName)) { + hotelAddress.postalCode = reader.getString(); + } else { + reader.skipChildren(); + } + } + + return hotelAddress; + }); + } +} 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/testingmodels/HotelAnalyzerException.java similarity index 67% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelAnalyzerException.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelAnalyzerException.java index 4a65820f49af..7db6eda9828e 100644 --- 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/testingmodels/HotelAnalyzerException.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.SearchableField; +import com.azure.search.documents.indexes.BasicField; public class HotelAnalyzerException extends RuntimeException { private String tag; @@ -13,7 +13,11 @@ public class HotelAnalyzerException extends RuntimeException { * * @return The tag of hotel. */ - @SearchableField(analyzerName = "en.microsoft", indexAnalyzerName = "whitespce") + @BasicField( + name = "Tag", + isSearchable = BasicField.BooleanHelper.TRUE, + analyzerName = "en.microsoft", + indexAnalyzerName = "whitespce") public String getTag() { return tag; } 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/testingmodels/HotelCircularDependencies.java similarity index 87% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelCircularDependencies.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelCircularDependencies.java index a8f7cb1b884c..c51689f44f9f 100644 --- 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/testingmodels/HotelCircularDependencies.java @@ -1,13 +1,18 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; + +import com.azure.search.documents.indexes.ComplexField; /** * The model class to test the behaviour of circular dependencies */ public class HotelCircularDependencies { + @ComplexField(name = "HomeAddress") private AddressCircularDependencies homeAddress; + + @ComplexField(name = "BillingAddress") private AddressCircularDependencies billingAddress; /** 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/testingmodels/HotelRenameProperty.java similarity index 67% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelRenameProperty.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelRenameProperty.java index bb17db8d1695..006116eabad8 100644 --- 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/testingmodels/HotelRenameProperty.java @@ -1,10 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; +import com.azure.search.documents.indexes.BasicField; import com.fasterxml.jackson.annotation.JsonProperty; public class HotelRenameProperty { @@ -12,7 +11,7 @@ public class HotelRenameProperty { private String hotelName; private String description; - @SimpleField(isKey = true, isSortable = true) + @BasicField(name = "HotelId", isKey = BasicField.BooleanHelper.TRUE, isSortable = BasicField.BooleanHelper.TRUE) @JsonProperty public String getHotelId() { return this.hotelId; @@ -23,7 +22,11 @@ public HotelRenameProperty setHotelId(String hotelId) { return this; } - @SearchableField(isSortable = true, analyzerName = "en.lucene") + @BasicField( + name = "HotelName", + isSearchable = BasicField.BooleanHelper.TRUE, + isSortable = BasicField.BooleanHelper.TRUE, + analyzerName = "en.lucene") @JsonProperty(value = "HotelName") public String getHotelName() { return this.hotelName; @@ -34,7 +37,7 @@ public HotelRenameProperty setHotelName(String hotelName) { return this; } - @SimpleField + @BasicField(name = "Description") public String getDescription() { return this.description; } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelRoom.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelRoom.java new file mode 100644 index 000000000000..3dd0357f02a2 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelRoom.java @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +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.BasicField; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import java.io.IOException; +import java.util.List; + +@JsonPropertyOrder({ "Description", "Description_fr", "Type", "BaseRate", "BedOptions", "BedOptions", "SleepsCount", }) +public class HotelRoom implements JsonSerializable { + @BasicField(name = "Description") + @JsonProperty(value = "Description") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String description; + + @BasicField(name = "Description_fr") + @JsonProperty(value = "Description_fr") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String descriptionFr; + + @BasicField(name = "Type") + @JsonProperty(value = "Type") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String type; + + @BasicField(name = "BaseRate") + @JsonProperty(value = "BaseRate") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Double baseRate; + + @BasicField(name = "BedOptions") + @JsonProperty(value = "BedOptions") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String bedOptions; + + @BasicField(name = "SleepsCount") + @JsonProperty(value = "SleepsCount") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Integer sleepsCount; + + @BasicField(name = "SmokingAllowed") + @JsonProperty(value = "SmokingAllowed") + @JsonInclude(JsonInclude.Include.NON_NULL) + private Boolean smokingAllowed; + + @BasicField(name = "Tags") + @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; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("Description", description) + .writeStringField("Description_fr", descriptionFr) + .writeStringField("Type", type) + .writeNumberField("BaseRate", baseRate) + .writeStringField("BedOptions", bedOptions) + .writeNumberField("SleepsCount", sleepsCount) + .writeBooleanField("SmokingAllowed", smokingAllowed) + .writeArrayField("Tags", tags, JsonWriter::writeString) + .writeEndObject(); + } + + public static HotelRoom fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + HotelRoom hotelRoom = new HotelRoom(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Description".equals(fieldName)) { + hotelRoom.description = reader.getString(); + } else if ("Description_fr".equals(fieldName)) { + hotelRoom.descriptionFr = reader.getString(); + } else if ("Type".equals(fieldName)) { + hotelRoom.type = reader.getString(); + } else if ("BaseRate".equals(fieldName)) { + if (reader.currentToken() == JsonToken.STRING) { + String str = reader.getString(); + if ("INF".equals(str) || "+INF".equals(str)) { + hotelRoom.baseRate = Double.POSITIVE_INFINITY; + } else if ("-INF".equals(str)) { + hotelRoom.baseRate = Double.NEGATIVE_INFINITY; + } else if ("NaN".equals(str)) { + hotelRoom.baseRate = Double.NaN; + } else { + hotelRoom.baseRate = Double.parseDouble(str); + } + } else { + hotelRoom.baseRate = reader.getNullable(JsonReader::getDouble); + } + } else if ("BedOptions".equals(fieldName)) { + hotelRoom.bedOptions = reader.getString(); + } else if ("SleepsCount".equals(fieldName)) { + hotelRoom.sleepsCount = reader.getNullable(JsonReader::getInt); + } else if ("SmokingAllowed".equals(fieldName)) { + hotelRoom.smokingAllowed = reader.getNullable(JsonReader::getBoolean); + } else if ("Tags".equals(fieldName)) { + List tags = reader.readArray(JsonReader::getString); + if (tags != null) { + hotelRoom.tags = tags.toArray(new String[0]); + } + } else { + reader.skipChildren(); + } + } + + return hotelRoom; + }); + } +} 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/testingmodels/HotelSearchException.java similarity index 77% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchException.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelSearchException.java index 189f64a74f14..0f641d7c3193 100644 --- 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/testingmodels/HotelSearchException.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.SearchableField; +import com.azure.search.documents.indexes.BasicField; /** * The data object model is to test exception case. @@ -16,7 +16,7 @@ public class HotelSearchException extends RuntimeException { * * @return Get hotel id */ - @SearchableField + @BasicField(name = "HotelId", isSearchable = BasicField.BooleanHelper.TRUE) public int getHotelId() { return hotelId; } 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/testingmodels/HotelSearchableExceptionOnList.java similarity index 81% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelSearchableExceptionOnList.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelSearchableExceptionOnList.java index 0b3670ec2951..e81ee847471d 100644 --- 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/testingmodels/HotelSearchableExceptionOnList.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.SearchableField; +import com.azure.search.documents.indexes.BasicField; import java.util.ArrayList; import java.util.List; @@ -18,7 +18,7 @@ public class HotelSearchableExceptionOnList { * Gets passcode. * @return the passcode of hotel. */ - @SearchableField + @BasicField(name = "Passcode", isSearchable = BasicField.BooleanHelper.TRUE) public List getPasscode() { return (passcode == null) ? null : new ArrayList<>(passcode); } 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/testingmodels/HotelTwoDimensional.java similarity index 85% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelTwoDimensional.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelTwoDimensional.java index f4a3ad1b18af..220bedec9251 100644 --- 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/testingmodels/HotelTwoDimensional.java @@ -1,7 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; + +import com.azure.search.documents.indexes.BasicField; import java.util.ArrayList; import java.util.List; @@ -10,6 +12,7 @@ * The class is to test unsupported two-dimensional type. */ public class HotelTwoDimensional { + @BasicField(name = "Matrix") private List> matrix; /** 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/testingmodels/HotelWithArray.java similarity index 55% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithArray.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelWithArray.java index e789a5197fcf..92811e4a7416 100644 --- 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/testingmodels/HotelWithArray.java @@ -1,22 +1,21 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; import com.azure.core.util.CoreUtils; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; +import com.azure.search.documents.indexes.BasicField; public class HotelWithArray { private String hotelId; private String[] tags; - @SimpleField(isKey = true, isSortable = true) + @BasicField(name = "HotelId", isKey = BasicField.BooleanHelper.TRUE, isSortable = BasicField.BooleanHelper.TRUE) public String getHotelId() { return hotelId; } - @SearchableField + @BasicField(name = "Tags", isSearchable = BasicField.BooleanHelper.TRUE) 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/testingmodels/HotelWithEmptyInSynonymMaps.java similarity index 75% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithEmptyInSynonymMaps.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelWithEmptyInSynonymMaps.java index a6239d3f1dd0..b4649834d5ce 100644 --- 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/testingmodels/HotelWithEmptyInSynonymMaps.java @@ -1,9 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.SearchableField; +import com.azure.search.documents.indexes.BasicField; import java.util.ArrayList; import java.util.List; @@ -19,7 +19,10 @@ public class HotelWithEmptyInSynonymMaps { * * @return The tags of hotel. */ - @SearchableField(synonymMapNames = { "asynonymMaps", "", " ", "maps" }) + @BasicField( + name = "Tags", + isSearchable = BasicField.BooleanHelper.TRUE, + synonymMapNames = { "asynonymMaps", "", " ", "maps" }) public List getTags() { return (tags == null) ? null : new ArrayList<>(tags); } 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/testingmodels/HotelWithIgnoredFields.java similarity index 67% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithIgnoredFields.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelWithIgnoredFields.java index d30d86d411f9..53b34b94e45f 100644 --- 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/testingmodels/HotelWithIgnoredFields.java @@ -1,26 +1,24 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; -import com.azure.search.documents.indexes.FieldBuilderIgnore; -import com.fasterxml.jackson.annotation.JsonIgnore; +import com.azure.search.documents.indexes.BasicField; public class HotelWithIgnoredFields { private String hotelId; private String hotelName; private String notIgnoredName; - @FieldBuilderIgnore public String getHotelId() { return hotelId; } - @JsonIgnore public String getHotelName() { return hotelName; } + @BasicField(name = "NotIgnoredName") 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/testingmodels/HotelWithUnsupportedField.java similarity index 71% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/HotelWithUnsupportedField.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/HotelWithUnsupportedField.java index fd9bb897e909..1792cbf2f165 100644 --- 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/testingmodels/HotelWithUnsupportedField.java @@ -1,16 +1,21 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; + +import com.azure.search.documents.indexes.BasicField; import java.util.ArrayList; import java.util.List; public class HotelWithUnsupportedField { + @BasicField(name = "HotelId") private String hotelId; + @BasicField(name = "SomeByte") private Byte someByte; + @BasicField(name = "SomeListBytes") private List someListBytes; public String getHotelId() { 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/testingmodels/LoudHotel.java similarity index 50% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/LoudHotel.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/LoudHotel.java index cecbcde46980..1251bb35b15a 100644 --- 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/testingmodels/LoudHotel.java @@ -1,65 +1,86 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; import com.azure.core.models.GeoPoint; +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.BasicField; +import com.azure.search.documents.indexes.ComplexField; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.IOException; +import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Date; import java.util.List; +import java.util.Objects; @SuppressWarnings({ "UseOfObsoleteDateTimeApi", "unused" }) @JsonIgnoreProperties(ignoreUnknown = true) -public class LoudHotel { +public class LoudHotel implements JsonSerializable { + @BasicField(name = "HotelId", isKey = BasicField.BooleanHelper.TRUE) @JsonProperty(value = "HotelId") @JsonInclude(JsonInclude.Include.NON_NULL) private String HOTELID; + @BasicField(name = "HotelName") @JsonProperty(value = "HotelName") @JsonInclude(JsonInclude.Include.NON_NULL) private String HOTELNAME; + @BasicField(name = "Description") @JsonProperty(value = "Description") private String DESCRIPTION; + @BasicField(name = "Description_fr") @JsonProperty(value = "Description_fr") @JsonInclude(JsonInclude.Include.NON_NULL) private String DESCRIPTIONFRENCH; + @BasicField(name = "Category") @JsonProperty(value = "Category") @JsonInclude(JsonInclude.Include.NON_NULL) private String CATEGORY; + @BasicField(name = "Tags") @JsonProperty(value = "Tags") @JsonInclude(JsonInclude.Include.NON_NULL) private List TAGS; + @BasicField(name = "ParkingIncluded") @JsonProperty(value = "ParkingIncluded") @JsonInclude(JsonInclude.Include.NON_NULL) private Boolean PARKINGINCLUDED; + @BasicField(name = "SmokingAllowed") @JsonProperty(value = "SmokingAllowed") @JsonInclude(JsonInclude.Include.NON_NULL) private Boolean SMOKINGALLOWED; + @BasicField(name = "LastRenovationDate") @JsonProperty(value = "LastRenovationDate") @JsonInclude(JsonInclude.Include.NON_NULL) - private Date LASTRENOVATIONDATE; + private OffsetDateTime LASTRENOVATIONDATE; + @BasicField(name = "Rating") @JsonProperty(value = "Rating") @JsonInclude(JsonInclude.Include.NON_NULL) private Integer RATING; + @BasicField(name = "Location") @JsonProperty(value = "Location") private GeoPoint LOCATION; + @ComplexField(name = "Address") @JsonProperty(value = "Address") @JsonInclude(JsonInclude.Include.NON_NULL) private HotelAddress ADDRESS; + @ComplexField(name = "Rooms") @JsonProperty(value = "Rooms") @JsonInclude(JsonInclude.Include.NON_NULL) private List ROOMS; @@ -141,12 +162,12 @@ public LoudHotel SMOKINGALLOWED(Boolean smokingAllowed) { return this; } - public Date LASTRENOVATIONDATE() { - return (this.LASTRENOVATIONDATE == null) ? null : (Date) this.LASTRENOVATIONDATE.clone(); + public OffsetDateTime LASTRENOVATIONDATE() { + return this.LASTRENOVATIONDATE; } - public LoudHotel LASTRENOVATIONDATE(Date lastRenovationDate) { - this.LASTRENOVATIONDATE = (lastRenovationDate == null) ? null : (Date) lastRenovationDate.clone(); + public LoudHotel LASTRENOVATIONDATE(OffsetDateTime lastRenovationDate) { + this.LASTRENOVATIONDATE = lastRenovationDate; return this; } @@ -185,4 +206,67 @@ public LoudHotel ROOMS(List rooms) { this.ROOMS = (rooms == null) ? null : new ArrayList<>(rooms); return this; } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("HotelId", HOTELID) + .writeStringField("HotelName", HOTELNAME) + .writeStringField("Description", DESCRIPTION) + .writeStringField("Description_fr", DESCRIPTIONFRENCH) + .writeStringField("Category", CATEGORY) + .writeArrayField("Tags", TAGS, JsonWriter::writeString) + .writeBooleanField("ParkingIncluded", PARKINGINCLUDED) + .writeBooleanField("SmokingAllowed", SMOKINGALLOWED) + .writeStringField("LastRenovationDate", Objects.toString(LASTRENOVATIONDATE, null)) + .writeNumberField("Rating", RATING) + .writeJsonField("Location", LOCATION) + .writeJsonField("Address", ADDRESS) + .writeArrayField("Rooms", ROOMS, JsonWriter::writeJson) + .writeEndObject(); + } + + @SuppressWarnings("deprecation") + public static LoudHotel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + LoudHotel hotel = new LoudHotel(); + + 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 ("Description_fr".equals(fieldName)) { + hotel.DESCRIPTIONFRENCH = reader.getString(); + } else if ("Category".equals(fieldName)) { + hotel.CATEGORY = reader.getString(); + } else if ("Tags".equals(fieldName)) { + hotel.TAGS = reader.readArray(JsonReader::getString); + } else if ("ParkingIncluded".equals(fieldName)) { + hotel.PARKINGINCLUDED = reader.getNullable(JsonReader::getBoolean); + } else if ("SmokingAllowed".equals(fieldName)) { + hotel.SMOKINGALLOWED = reader.getNullable(JsonReader::getBoolean); + } else if ("LastRenovationDate".equals(fieldName)) { + hotel.LASTRENOVATIONDATE = reader.getNullable(nonNull -> OffsetDateTime.parse(nonNull.getString())); + } else if ("Rating".equals(fieldName)) { + hotel.RATING = reader.getNullable(JsonReader::getInt); + } else if ("Location".equals(fieldName)) { + hotel.LOCATION = GeoPoint.fromJson(reader); + } else if ("Address".equals(fieldName)) { + hotel.ADDRESS = HotelAddress.fromJson(reader); + } else if ("Rooms".equals(fieldName)) { + hotel.ROOMS = reader.readArray(HotelRoom::fromJson); + } else { + reader.skipChildren(); + } + } + + return hotel; + }); + } } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/ModelWithPrimitiveCollections.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/ModelWithPrimitiveCollections.java new file mode 100644 index 000000000000..fe407cd588eb --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/ModelWithPrimitiveCollections.java @@ -0,0 +1,216 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +import com.azure.core.models.GeoPoint; +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.BasicField; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Objects; + +@SuppressWarnings("unused") +@JsonIgnoreProperties(ignoreUnknown = true) +public class ModelWithPrimitiveCollections implements JsonSerializable { + @BasicField(name = "Key", isKey = BasicField.BooleanHelper.TRUE) + @JsonProperty(value = "Key") + private String key; + + @BasicField(name = "Bools") + @JsonProperty(value = "Bools") + private Boolean[] bools; + + @BasicField(name = "Dates") + @JsonProperty(value = "Dates") + private OffsetDateTime[] dates; + + @BasicField(name = "Doubles") + @JsonProperty(value = "Doubles") + private Double[] doubles; + + @BasicField(name = "Ints") + @JsonProperty(value = "Ints") + private int[] ints; + + @BasicField(name = "Longs") + @JsonProperty(value = "Longs") + private Long[] longs; + + @BasicField(name = "Points") + @JsonProperty(value = "Points") + private GeoPoint[] points; + + @BasicField(name = "Strings") + @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); + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + jsonWriter.writeStartObject() + .writeStringField("Key", key) + .writeArrayField("Bools", bools, JsonWriter::writeBoolean) + .writeArrayField("Dates", dates, (writer, date) -> writer.writeString(Objects.toString(date, null))) + .writeArrayField("Doubles", doubles, JsonWriter::writeNumber); + if (ints != null) { + jsonWriter.writeStartArray("Ints"); + for (int i : ints) { + jsonWriter.writeInt(i); + } + jsonWriter.writeEndArray(); + } + return jsonWriter.writeArrayField("Longs", longs, JsonWriter::writeNumber) + .writeArrayField("Points", points, JsonWriter::writeJson) + .writeArrayField("Strings", strings, JsonWriter::writeString) + .writeEndObject(); + } + + public static ModelWithPrimitiveCollections fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + ModelWithPrimitiveCollections model = new ModelWithPrimitiveCollections(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Key".equals(fieldName)) { + model.key = reader.getString(); + } else if ("Bools".equals(fieldName)) { + List bools = reader.readArray(elem -> elem.getNullable(JsonReader::getBoolean)); + if (bools != null) { + model.bools = bools.toArray(new Boolean[0]); + } + } else if ("Dates".equals(fieldName)) { + List dates + = reader.readArray(elem -> CoreUtils.parseBestOffsetDateTime(elem.getString())); + if (dates != null) { + model.dates = dates.toArray(new OffsetDateTime[0]); + } + } else if ("Doubles".equals(fieldName)) { + List doubles = reader.readArray(elem -> elem.getNullable(nonNull -> { + if (nonNull.currentToken() == JsonToken.STRING) { + String str = nonNull.getString(); + if ("INF".equals(str) || "+INF".equals(str)) { + return Double.POSITIVE_INFINITY; + } else if ("-INF".equals(str)) { + return Double.NEGATIVE_INFINITY; + } else if ("NaN".equals(str)) { + return Double.NaN; + } else { + return Double.parseDouble(str); + } + } else { + return nonNull.getDouble(); + } + })); + if (doubles != null) { + model.doubles = doubles.toArray(new Double[0]); + } + } else if ("Ints".equals(fieldName)) { + List ints = reader.readArray(JsonReader::getInt); + if (ints != null) { + model.ints = ints.stream().mapToInt(i -> i).toArray(); + } + } else if ("Longs".equals(fieldName)) { + List longs = reader.readArray(elem -> elem.getNullable(JsonReader::getLong)); + if (longs != null) { + model.longs = longs.toArray(new Long[0]); + } + } else if ("Points".equals(fieldName)) { + List points = reader.readArray(GeoPoint::fromJson); + if (points != null) { + model.points = points.toArray(new GeoPoint[0]); + } + } else if ("Strings".equals(fieldName)) { + List strings = reader.readArray(JsonReader::getString); + if (strings != null) { + model.strings = strings.toArray(new String[0]); + } + } else { + reader.skipChildren(); + } + } + + return model; + }); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/NonNullableModel.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/NonNullableModel.java new file mode 100644 index 000000000000..149b666644b2 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/NonNullableModel.java @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.testingmodels; + +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.fasterxml.jackson.annotation.JsonProperty; + +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Objects; + +@SuppressWarnings("UseOfObsoleteDateTimeApi") +public class NonNullableModel implements JsonSerializable { + + @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 OffsetDateTime startDate; + + @JsonProperty(value = "EndDate") + private OffsetDateTime 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(OffsetDateTime startDate) { + this.startDate = startDate; + return this; + } + + public NonNullableModel endDate(OffsetDateTime endDate) { + this.endDate = endDate; + return this; + } + + public NonNullableModel topLevelBucket(Bucket topLevelBucket) { + this.topLevelBucket = topLevelBucket; + return this; + } + + public NonNullableModel buckets(Bucket[] buckets) { + this.buckets = CoreUtils.clone(buckets); + return this; + } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("Key", key) + .writeIntField("Rating", rating) + .writeLongField("Count", count) + .writeBooleanField("IsEnabled", isEnabled) + .writeDoubleField("Ratio", ratio) + .writeStringField("StartDate", Objects.toString(startDate, null)) + .writeStringField("EndDate", Objects.toString(endDate, null)) + .writeJsonField("TopLevelBucket", topLevelBucket) + .writeArrayField("Buckets", buckets, JsonWriter::writeJson) + .writeEndObject(); + } + + public static NonNullableModel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + NonNullableModel model = new NonNullableModel(); + + while (reader.nextToken() != JsonToken.END_OBJECT) { + String fieldName = reader.getFieldName(); + reader.nextToken(); + + if ("Key".equals(fieldName)) { + model.key = reader.getString(); + } else if ("Rating".equals(fieldName)) { + model.rating = reader.getInt(); + } else if ("Count".equals(fieldName)) { + model.count = reader.getLong(); + } else if ("IsEnabled".equals(fieldName)) { + model.isEnabled = reader.getBoolean(); + } else if ("Ratio".equals(fieldName)) { + model.ratio = reader.getDouble(); + } else if ("StartDate".equals(fieldName)) { + model.startDate = reader.getNullable(nonNull -> OffsetDateTime.parse(nonNull.getString())); + } else if ("EndDate".equals(fieldName)) { + model.endDate = reader.getNullable(nonNull -> OffsetDateTime.parse(nonNull.getString())); + } else if ("TopLevelBucket".equals(fieldName)) { + model.topLevelBucket = Bucket.fromJson(reader); + } else if ("Buckets".equals(fieldName)) { + List buckets = reader.readArray(Bucket::fromJson); + if (buckets != null) { + model.buckets = buckets.toArray(new Bucket[0]); + } + } else { + reader.skipChildren(); + } + } + return model; + }); + } +} 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/testingmodels/VectorHotel.java similarity index 51% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/VectorHotel.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/testingmodels/VectorHotel.java index f4c4547a6a2b..395e7723756f 100644 --- 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/testingmodels/VectorHotel.java @@ -1,55 +1,61 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents.test.environment.models; +package com.azure.search.documents.testingmodels; import com.azure.core.models.GeoPoint; +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.VectorSearchEmbeddings; -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.BasicField; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.io.IOException; +import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Date; import java.util.List; +import java.util.Objects; -@SuppressWarnings("UseOfObsoleteDateTimeApi") @JsonIgnoreProperties(ignoreUnknown = true) -public class VectorHotel { - @SimpleField(isKey = true, isSortable = true) +public class VectorHotel implements JsonSerializable { + @BasicField(name = "HotelId", isKey = BasicField.BooleanHelper.TRUE, isSortable = BasicField.BooleanHelper.TRUE) @JsonProperty(value = "HotelId") @JsonInclude(JsonInclude.Include.NON_NULL) private String hotelId; - @SearchableField(isSortable = true, analyzerName = "en.lucene") + @BasicField( + name = "HotelName", + isSearchable = BasicField.BooleanHelper.TRUE, + isSortable = BasicField.BooleanHelper.TRUE, + analyzerName = "en.lucene") @JsonProperty(value = "HotelName") @JsonInclude(JsonInclude.Include.NON_NULL) private String hotelName; - @SimpleField + @BasicField(name = "Description") @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" + private List descriptionVector = VectorSearchEmbeddings.DEFAULT_VECTORIZE_DESCRIPTION; + // Default DescriptionVector: "Hotel" - @SimpleField + @BasicField(name = "Category") @JsonProperty(value = "Category") @JsonInclude(JsonInclude.Include.NON_NULL) private String category; - @SearchableField + @BasicField(name = "Tags", isSearchable = BasicField.BooleanHelper.TRUE) @JsonProperty(value = "Tags") @JsonInclude(JsonInclude.Include.NON_NULL) private List tags; @@ -64,7 +70,7 @@ public class VectorHotel { @JsonProperty(value = "LastRenovationDate") @JsonInclude(JsonInclude.Include.NON_NULL) - private Date lastRenovationDate; + private OffsetDateTime lastRenovationDate; @JsonProperty(value = "Rating") @JsonInclude(JsonInclude.Include.NON_NULL) @@ -168,12 +174,12 @@ public VectorHotel smokingAllowed(Boolean smokingAllowed) { return this; } - public Date lastRenovationDate() { - return (this.lastRenovationDate == null) ? null : (Date) this.lastRenovationDate.clone(); + public OffsetDateTime lastRenovationDate() { + return this.lastRenovationDate; } - public VectorHotel lastRenovationDate(Date lastRenovationDate) { - this.lastRenovationDate = (lastRenovationDate == null) ? null : (Date) lastRenovationDate.clone(); + public VectorHotel lastRenovationDate(OffsetDateTime lastRenovationDate) { + this.lastRenovationDate = lastRenovationDate; return this; } @@ -212,4 +218,69 @@ public VectorHotel rooms(List rooms) { this.rooms = rooms; return this; } + + @Override + public JsonWriter toJson(JsonWriter jsonWriter) throws IOException { + return jsonWriter.writeStartObject() + .writeStringField("HotelId", hotelId) + .writeStringField("HotelName", hotelName) + .writeStringField("Description", description) + .writeStringField("Description_fr", descriptionFr) + .writeArrayField("DescriptionVector", descriptionVector, JsonWriter::writeFloat) + .writeStringField("Category", category) + .writeArrayField("Tags", tags, JsonWriter::writeString) + .writeBooleanField("ParkingIncluded", parkingIncluded) + .writeBooleanField("SmokingAllowed", smokingAllowed) + .writeStringField("LastRenovationDate", Objects.toString(lastRenovationDate, null)) + .writeNumberField("Rating", rating) + .writeJsonField("Location", location) + .writeJsonField("Address", address) + .writeArrayField("Rooms", rooms, JsonWriter::writeJson) + .writeEndObject(); + } + + @SuppressWarnings("deprecation") + public static VectorHotel fromJson(JsonReader jsonReader) throws IOException { + return jsonReader.readObject(reader -> { + VectorHotel hotel = new VectorHotel(); + + 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 ("Description_fr".equals(fieldName)) { + hotel.descriptionFr = reader.getString(); + } else if ("DescriptionVector".equals(fieldName)) { + hotel.descriptionVector = reader.readArray(JsonReader::getFloat); + } else if ("Category".equals(fieldName)) { + hotel.category = reader.getString(); + } else if ("Tags".equals(fieldName)) { + hotel.tags = reader.readArray(JsonReader::getString); + } else if ("ParkingIncluded".equals(fieldName)) { + hotel.parkingIncluded = reader.getNullable(JsonReader::getBoolean); + } else if ("SmokingAllowed".equals(fieldName)) { + hotel.smokingAllowed = reader.getNullable(JsonReader::getBoolean); + } else if ("LastRenovationDate".equals(fieldName)) { + hotel.lastRenovationDate = reader.getNullable(nonNull -> OffsetDateTime.parse(nonNull.getString())); + } else if ("Rating".equals(fieldName)) { + hotel.rating = reader.getNullable(JsonReader::getInt); + } else if ("Location".equals(fieldName)) { + hotel.location = GeoPoint.fromJson(reader); + } else if ("Address".equals(fieldName)) { + hotel.address = HotelAddress.fromJson(reader); + } else if ("Rooms".equals(fieldName)) { + hotel.rooms = reader.readArray(HotelRoom::fromJson); + } else { + reader.skipChildren(); + } + } + return hotel; + }); + } } 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..3fdf565dc43e --- /dev/null +++ b/sdk/search/azure-search-documents/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/search/data-plane/Search +commit: 718b95fa93eb60c43e72d88de1b31ac11493a822 +repo: Azure/azure-rest-api-specs +cleanup: true diff --git a/sdk/search/azure-search-perf/pom.xml b/sdk/search/azure-search-perf/pom.xml index 6c4d51840480..ac8edaa526bd 100644 --- a/sdk/search/azure-search-perf/pom.xml +++ b/sdk/search/azure-search-perf/pom.xml @@ -29,7 +29,7 @@ com.azure azure-search-documents - 11.9.0-beta.2 + 12.0.0-beta.1 diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/AutocompleteTest.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/AutocompleteTest.java index d8f08d9d81ef..289258677173 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/AutocompleteTest.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/AutocompleteTest.java @@ -3,12 +3,11 @@ package com.azure.search.perf; +import com.azure.search.documents.models.AutocompleteOptions; import com.azure.search.perf.core.SearchPerfStressOptions; import com.azure.search.perf.core.ServiceTest; import reactor.core.publisher.Mono; -import java.util.concurrent.atomic.AtomicInteger; - /** * Performs autocomplete operations. */ @@ -33,19 +32,14 @@ public Mono globalSetupAsync() { @Override public void run() { - AtomicInteger count = new AtomicInteger(); - searchClient.autocomplete("historic", SUGGESTER_NAME) - .iterator() - .forEachRemaining(ignored -> count.incrementAndGet()); - - assert count.get() > 0; + assert !searchClient.autocomplete(new AutocompleteOptions("historic", SUGGESTER_NAME)).getResults().isEmpty(); } @Override public Mono runAsync() { - return searchAsyncClient.autocomplete("historic", SUGGESTER_NAME) - .count() - .flatMap( - count -> count > 0 ? Mono.empty() : Mono.error(new RuntimeException("Expected autocomplete results."))); + return searchAsyncClient.autocomplete(new AutocompleteOptions("historic", SUGGESTER_NAME)) + .flatMap(result -> result.getResults().isEmpty() + ? Mono.error(new RuntimeException("Expected autocomplete results.")) + : Mono.empty()); } } diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/IndexDocumentsTest.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/IndexDocumentsTest.java index 61e475a4efb3..6a4c515d9837 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/IndexDocumentsTest.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/IndexDocumentsTest.java @@ -3,15 +3,17 @@ package com.azure.search.perf; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import com.azure.search.perf.core.DocumentGenerator; import com.azure.search.perf.core.DocumentSize; -import com.azure.search.perf.core.Hotel; import com.azure.search.perf.core.SearchPerfStressOptions; import com.azure.search.perf.core.ServiceTest; import reactor.core.publisher.Mono; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -20,7 +22,7 @@ */ public class IndexDocumentsTest extends ServiceTest { private static volatile AtomicInteger ID_COUNT = new AtomicInteger(); - private final List hotels; + private final List> hotels; /** * Creates the document indexing operations performance test. @@ -37,15 +39,22 @@ public IndexDocumentsTest(SearchPerfStressOptions options) { @Override public void run() { int[] idOffset = new int[] { ID_COUNT.getAndAdd(options.getCount()) }; - searchClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions( - hotels.stream().peek(hotel -> hotel.hotelId = String.valueOf(idOffset[0]++)).collect(Collectors.toList()))); + searchClient.indexDocuments(createBatch(idOffset)); } @Override public Mono runAsync() { int[] idOffset = new int[] { ID_COUNT.getAndAdd(options.getCount()) }; - return searchAsyncClient.indexDocuments(new IndexDocumentsBatch<>().addUploadActions( - hotels.stream().peek(hotel -> hotel.hotelId = String.valueOf(idOffset[0]++)).collect(Collectors.toList()))) - .then(); + return searchAsyncClient.indexDocuments(createBatch(idOffset)).then(); + } + + private IndexDocumentsBatch createBatch(int[] idOffset) { + return new IndexDocumentsBatch(hotels.stream() + .map(hotel -> { + hotel.put("HotelId", idOffset[0]++); + return new IndexAction().setActionType(IndexActionType.UPLOAD) + .setAdditionalProperties(hotel); + }) + .collect(Collectors.toList())); } } diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SearchDocumentsTest.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SearchDocumentsTest.java index 15711b4d44ad..b91af8fe3c08 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SearchDocumentsTest.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SearchDocumentsTest.java @@ -3,13 +3,10 @@ package com.azure.search.perf; -import com.azure.search.perf.core.Hotel; import com.azure.search.perf.core.SearchPerfStressOptions; import com.azure.search.perf.core.ServiceTest; import reactor.core.publisher.Mono; -import java.util.concurrent.atomic.AtomicInteger; - /** * Performs searching operations. */ @@ -34,19 +31,12 @@ public Mono globalSetupAsync() { @Override public void run() { - AtomicInteger count = new AtomicInteger(); - searchClient.search("").iterator().forEachRemaining(result -> { - result.getDocument(Hotel.class); - count.incrementAndGet(); - }); - - assert count.get() > 0; + assert searchClient.search(null).stream().count() > 0; } @Override public Mono runAsync() { - return searchAsyncClient.search("") - .map(result -> result.getDocument(Hotel.class)) + return searchAsyncClient.search(null) .count() .flatMap( count -> count > 0 ? Mono.empty() : Mono.error(new RuntimeException("Expected autocomplete results."))); diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SuggestTest.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SuggestTest.java index 78e5ccc163e1..bb9017b1919e 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SuggestTest.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/SuggestTest.java @@ -3,13 +3,11 @@ package com.azure.search.perf; -import com.azure.search.perf.core.Hotel; +import com.azure.search.documents.models.SuggestOptions; import com.azure.search.perf.core.SearchPerfStressOptions; import com.azure.search.perf.core.ServiceTest; import reactor.core.publisher.Mono; -import java.util.concurrent.atomic.AtomicInteger; - /** * Performs suggestion operations. */ @@ -34,21 +32,14 @@ public Mono globalSetupAsync() { @Override public void run() { - AtomicInteger count = new AtomicInteger(); - searchClient.suggest("historic", SUGGESTER_NAME).iterator().forEachRemaining(result -> { - result.getDocument(Hotel.class); - count.incrementAndGet(); - }); - - assert count.get() > 0; + assert !searchClient.suggest(new SuggestOptions("historic", SUGGESTER_NAME)).getResults().isEmpty(); } @Override public Mono runAsync() { - return searchAsyncClient.suggest("historic", SUGGESTER_NAME) - .map(result -> result.getDocument(Hotel.class)) - .count() - .flatMap( - count -> count > 0 ? Mono.empty() : Mono.error(new RuntimeException("Expected autocomplete results."))); + return searchAsyncClient.suggest(new SuggestOptions("historic", SUGGESTER_NAME)) + .flatMap(result -> result.getResults().isEmpty() + ? Mono.error(new RuntimeException("Expected autocomplete results.")) + : Mono.empty()); } } diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Address.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Address.java index d990bd8c8c24..fccfb70d4900 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Address.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Address.java @@ -3,7 +3,7 @@ package com.azure.search.perf.core; -import com.azure.search.documents.indexes.SearchableField; +import com.azure.search.documents.indexes.BasicField; import com.fasterxml.jackson.annotation.JsonProperty; /** @@ -14,34 +14,34 @@ public class Address { * Street address */ @JsonProperty("StreetAddress") - @SearchableField + @BasicField(name = "StreetAddress") public String streetAddress; /** * City */ @JsonProperty("City") - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "City") public String city; /** * State or province */ @JsonProperty("StateProvince") - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "StateProvince") public String stateProvince; /** * Postal code */ @JsonProperty("PostalCode") - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "PostalCode") public String postalCode; /** * Country */ @JsonProperty("Country") - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "Country") public String country; } diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/DocumentGenerator.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/DocumentGenerator.java index f8d4f1567eac..8cee241c1dae 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/DocumentGenerator.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/DocumentGenerator.java @@ -6,7 +6,9 @@ import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * Generates Search documents. @@ -19,8 +21,8 @@ public final class DocumentGenerator { * @param documentSize Size of the documents. * @return A list of documents. */ - public static List generateHotels(int count, DocumentSize documentSize) { - List hotels = new ArrayList<>(count * 2); + public static List> generateHotels(int count, DocumentSize documentSize) { + List> hotels = new ArrayList<>(count * 2); for (int i = 0; i < count; i++) { hotels.add(createHotel(i, documentSize)); @@ -29,65 +31,64 @@ public static List generateHotels(int count, DocumentSize documentSize) { return hotels; } - private static Hotel createHotel(int id, DocumentSize documentSize) { - Hotel hotel = new Hotel(); - - hotel.hotelId = String.valueOf(id); + private static Map createHotel(int id, DocumentSize documentSize) { + Map hotel = new LinkedHashMap<>(); + hotel.put("HotelId", String.valueOf(id)); if (documentSize == DocumentSize.SMALL) { - hotel.hotelName = "Secret Point Motel"; - hotel.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 " + hotel.put("HotelName", "Secret Point Motel"); + hotel.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."; - hotel.descriptionFr = "L'hôtel est idéalement situé sur la principale artère commerciale de la ville " + + "cities."); + hotel.put("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."; - hotel.category = "Boutique"; - hotel.tags = new String[] { "pool", "air conditioning", "concierge" }; - hotel.parkingIncluded = false; - hotel.lastRenovationDate = OffsetDateTime.of(1970, 1, 18, 0, 0, 0, 0, ZoneOffset.UTC); - hotel.rating = 3.6D; + + "attractives et cosmopolites de l'Amérique."); + hotel.put("Category", "Boutique"); + hotel.put("Tags", new String[] { "pool", "air conditioning", "concierge" }); + hotel.put("ParkingIncluded", false); + hotel.put("LastRenovationDate", OffsetDateTime.of(1970, 1, 18, 0, 0, 0, 0, ZoneOffset.UTC)); + hotel.put("Rating", 3.6D); - Address address = new Address(); - address.streetAddress = "677 5th Ave"; - address.city = "New York"; - address.stateProvince = "NY"; - address.postalCode = "10022"; - address.country = "USA"; + Map address = new LinkedHashMap<>(); + address.put("StreetAddress", "677 5th Ave"); + address.put("City", "New York"); + address.put("StateProvince", "NY"); + address.put("PostalCode", "10022"); + address.put("Country", "USA"); - hotel.address = address; + hotel.put("Address", address); } else { - hotel.hotelName = "Mount Rainier Lodge"; - hotel.description = "Mount Rainier Lodge is a historic lodge located in Ashford, Washington just a couple " - + "of miles outside of Mount Rainier National Park. To complement your trip to the great outdoors, the " - + "lodge offers queen rooms, suites, and standalone cabins with an outdoorsy theme. Amenities include " - + "a continental breakfast, high speed wi-fi, a gift shop, basic cable, an outdoor jacuzzi and free " - + "national park maps. With only a few hundred residents, Ashford has that quintessential outdoorsy " - + "small town feel while offering restaurants, gas stations, and convenience stores to keep you well " - + "supplied for your trip. Located to the east of the park, this lodge is just a few hours from both " - + "Mount St. Helens and Mount Adams so you can explore much of what the pacific northwest has to " - + "offer. If you choose to stay near Rainier, you’ll still get to take advantage of the tremendous " - + "view. Whether you’re looking to summit Mount Rainier, hiking all of Wonderland Trail, hoping to " - + "see a grizzly bear, or just exploring the park, Mount Rainier Lodge can be the perfect resting " - + "place for your adventure. We hope to see you soon!"; - hotel.descriptionFr = "Mount Rainier Lodge est un lodge historique situé à Ashford, Washington à quelques " - + "miles à l’extérieur du parc national du Mont Rainier. Pour compléter votre voyage en plein air, le " - + "lodge propose des chambres reines, des suites et des cabines autonomes avec un thème extérieur. " - + "Les commodités comprennent un petit déjeuner continental, wi-fi haute vitesse, une boutique de " - + "cadeaux, un câble de base, un jacuzzi extérieur et des cartes gratuites du parc national. Avec " - + "seulement quelques centaines de résidents, Ashford a cette quintessence en plein air petite ville " - + "se sentent tout en offrant des restaurants, stations-service, et des dépanneurs pour vous garder " - + "bien fourni pour votre voyage. Situé à l’est du parc, ce lodge est à quelques heures du mont St. " - + "Helens et du mont Adams afin que vous puissiez explorer une grande partie de ce que le nord-ouest " - + "du Pacifique a à offrir. Si vous choisissez de rester près de Rainier, vous aurez toujours la " - + "chance de profiter de la vue imprenable. Que vous cherchiez au sommet du mont Rainier, que vous " - + "randonnées sur l’ensemble du sentier Wonderland, que vous espériez voir un grizzli ou que vous " - + "exploriez simplement le parc, le Mount Rainier Lodge peut être le lieu de repos idéal pour votre " - + "aventure. Nous espérons vous voir bientôt!"; - hotel.category = "Lodge"; - hotel.tags = new String[] { + hotel.put("HotelName", "Mount Rainier Lodge"); + hotel.put("Description", "Mount Rainier Lodge is a historic lodge located in Ashford, Washington just a " + + "couple of miles outside of Mount Rainier National Park. To complement your trip to the great " + + "outdoors, the lodge offers queen rooms, suites, and standalone cabins with an outdoorsy theme. " + + "Amenities include a continental breakfast, high speed wi-fi, a gift shop, basic cable, an outdoor " + + "jacuzzi and free national park maps. With only a few hundred residents, Ashford has that " + + "quintessential outdoorsy small town feel while offering restaurants, gas stations, and convenience " + + "stores to keep you well supplied for your trip. Located to the east of the park, this lodge is just " + + "a few hours from both Mount St. Helens and Mount Adams so you can explore much of what the pacific " + + "northwest has to offer. If you choose to stay near Rainier, you’ll still get to take advantage of " + + "the tremendous view. Whether you’re looking to summit Mount Rainier, hiking all of Wonderland Trail, " + + "hoping to see a grizzly bear, or just exploring the park, Mount Rainier Lodge can be the perfect " + + "resting place for your adventure. We hope to see you soon!"); + hotel.put("DescriptionFr", "Mount Rainier Lodge est un lodge historique situé à Ashford, Washington à " + + "quelques miles à l’extérieur du parc national du Mont Rainier. Pour compléter votre voyage en plein " + + "air, le lodge propose des chambres reines, des suites et des cabines autonomes avec un thème " + + "extérieur. Les commodités comprennent un petit déjeuner continental, wi-fi haute vitesse, une " + + "boutique de cadeaux, un câble de base, un jacuzzi extérieur et des cartes gratuites du parc " + + "national. Avec seulement quelques centaines de résidents, Ashford a cette quintessence en plein air " + + "petite ville se sentent tout en offrant des restaurants, stations-service, et des dépanneurs pour " + + "vous garder bien fourni pour votre voyage. Situé à l’est du parc, ce lodge est à quelques heures du " + + "mont St. Helens et du mont Adams afin que vous puissiez explorer une grande partie de ce que le " + + "nord-ouest du Pacifique a à offrir. Si vous choisissez de rester près de Rainier, vous aurez " + + "toujours la chance de profiter de la vue imprenable. Que vous cherchiez au sommet du mont Rainier, " + + "que vous randonnées sur l’ensemble du sentier Wonderland, que vous espériez voir un grizzli ou que " + + "vous exploriez simplement le parc, le Mount Rainier Lodge peut être le lieu de repos idéal pour " + + "votre aventure. Nous espérons vous voir bientôt!"); + hotel.put("Category", "Lodge"); + hotel.put("Tags", new String[] { "jacuzzi", "air conditioning", "gift shop", @@ -98,19 +99,19 @@ private static Hotel createHotel(int id, DocumentSize documentSize) { "cabin", "outdoors", "pacific northwest", - "mountain" }; - hotel.parkingIncluded = true; - hotel.lastRenovationDate = OffsetDateTime.of(1985, 3, 30, 0, 0, 0, 0, ZoneOffset.UTC); - hotel.rating = 4.2D; + "mountain" }); + hotel.put("ParkingIncluded", true); + hotel.put("LastRenovationDate", OffsetDateTime.of(1985, 3, 30, 0, 0, 0, 0, ZoneOffset.UTC)); + hotel.put("Rating", 4.2D); - Address address = new Address(); - address.streetAddress = "35708 Sr 706 E"; - address.city = "Ashford"; - address.stateProvince = "WA"; - address.postalCode = "98304"; - address.country = "USA"; + Map address = new LinkedHashMap<>(); + address.put("StreetAddress", "35708 Sr 706 E"); + address.put("City", "Ashford"); + address.put("StateProvince", "WA"); + address.put("PostalCode", "98304"); + address.put("Country", "USA"); - hotel.address = address; + hotel.put("Address", address); } return hotel; diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Hotel.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Hotel.java index 230c46259dfc..852f0f91656f 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Hotel.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/Hotel.java @@ -3,8 +3,8 @@ package com.azure.search.perf.core; -import com.azure.search.documents.indexes.SearchableField; -import com.azure.search.documents.indexes.SimpleField; +import com.azure.search.documents.indexes.BasicField; +import com.azure.search.documents.indexes.ComplexField; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; @@ -17,68 +17,69 @@ public class Hotel { * Hotel ID */ @JsonProperty("HotelId") - @SimpleField(isKey = true) + @BasicField(name = "HotelId") public String hotelId; /** * Hotel name */ @JsonProperty("HotelName") - @SearchableField(isSortable = true) + @BasicField(name = "HotelName") public String hotelName; /** * Description */ @JsonProperty("Description") - @SearchableField(analyzerName = "en.microsoft") + @BasicField(name = "Description") public String description; /** * French description */ @JsonProperty("DescriptionFr") - @SearchableField(analyzerName = "fr.lucene") + @BasicField(name = "DescriptionFr") public String descriptionFr; /** * Category */ @JsonProperty("Category") - @SearchableField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "Category") public String category; /** * Tags */ @JsonProperty("Tags") - @SearchableField(isFilterable = true, isFacetable = true) + @BasicField(name = "Tags") public String[] tags; /** * Whether parking is included */ @JsonProperty("ParkingIncluded") - @SimpleField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "ParkingIncluded") public Boolean parkingIncluded; /** * Last renovation time */ @JsonProperty("LastRenovationDate") - @SimpleField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "LastRenovationDate") public OffsetDateTime lastRenovationDate; /** * Rating */ @JsonProperty("Rating") - @SimpleField(isFilterable = true, isSortable = true, isFacetable = true) + @BasicField(name = "Rating") public Double rating; /** * Address */ @JsonProperty("Address") + @ComplexField(name = "Address") public Address address; } diff --git a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/ServiceTest.java b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/ServiceTest.java index 544907cb8103..a55013d298f9 100644 --- a/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/ServiceTest.java +++ b/sdk/search/azure-search-perf/src/main/java/com/azure/search/perf/core/ServiceTest.java @@ -14,17 +14,20 @@ import com.azure.search.documents.SearchClient; import com.azure.search.documents.indexes.SearchIndexAsyncClient; import com.azure.search.documents.indexes.SearchIndexClientBuilder; -import com.azure.search.documents.indexes.models.IndexDocumentsBatch; import com.azure.search.documents.indexes.models.SearchIndex; import com.azure.search.documents.indexes.models.SearchSuggester; +import com.azure.search.documents.models.IndexAction; +import com.azure.search.documents.models.IndexActionType; +import com.azure.search.documents.models.IndexDocumentsBatch; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.net.InetSocketAddress; import java.time.Duration; -import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Random; +import java.util.stream.Collectors; /** * Base class for Azure Search performance tests. @@ -93,8 +96,8 @@ public ServiceTest(TOptions options) { @Override public Mono globalSetupAsync() { return searchIndexAsyncClient - .createIndex(new SearchIndex(indexName, SearchIndexAsyncClient.buildSearchFields(Hotel.class, null)) - .setSuggesters(new SearchSuggester(SUGGESTER_NAME, Arrays.asList("Description", "HotelName")))) + .createIndex(new SearchIndex(indexName, SearchIndexAsyncClient.buildSearchFields(Hotel.class)) + .setSuggesters(new SearchSuggester(SUGGESTER_NAME, "Description", "HotelName"))) .then(); } @@ -117,12 +120,14 @@ protected Mono populateIndex(int documentCount, String documentSize) { * index for its document count until it is equal to the count passed. */ return Mono.defer(() -> { - List hotels = DocumentGenerator.generateHotels(documentCount, DocumentSize.valueOf(documentSize)); + List> hotels = DocumentGenerator.generateHotels(documentCount, DocumentSize.valueOf(documentSize)); return Flux.range(0, (int) Math.ceil(hotels.size() / 100D)) .map(i -> hotels.subList(i * 100, Math.min((i + 1) * 100, hotels.size()))) .flatMap(hotelDocuments -> searchAsyncClient - .indexDocuments(new IndexDocumentsBatch().addUploadActions(hotelDocuments))) + .indexDocuments(new IndexDocumentsBatch(hotelDocuments.stream().map(doc -> new IndexAction() + .setActionType(IndexActionType.UPLOAD).setAdditionalProperties(doc)) + .collect(Collectors.toList())))) .then(); }) .then(Mono.defer(() -> searchAsyncClient.getDocumentCount()