diff --git a/sdk/search/azure-search-documents/CHANGELOG.md b/sdk/search/azure-search-documents/CHANGELOG.md index d0ebefe8c067..37596461dd3d 100644 --- a/sdk/search/azure-search-documents/CHANGELOG.md +++ b/sdk/search/azure-search-documents/CHANGELOG.md @@ -1,7 +1,13 @@ # Release History ## 1.0.0-beta.4 (Unreleased) - +- Split `SearchServiceClient` into two clients `SearchIndexClient`, `SearchIndexerClient`. +- Split `SearchServiceAsyncClient` into two clients `SearchIndexAsyncClient`, `SearchIndexerAsyncClient`. +- Added `SearchIndexClientBuilder` to build sync client `SearchIndexClient` and async client `SearchIndexAsyncClient`. +- Added `SearchIndexerClientBuilder` to build sync client `SearchIndexerClient` and async client `SearchIndexerAsyncClient`. +- Removed `SearchServiceClientBuilder`. +- Renamed `SearchIndexClient` to `SearchClient` and `SearchIndexAsyncClient` to `SearchAsyncClient`. +- Put all models used `SearchIndexClient` and `SearchIndexerClient` (same for async clients) under `com.azure.search.documents.indexes`. ## 1.0.0-beta.3 (2020-05-05) - Replaced `isRetrievable` API with `isHidden`, parameter name changed from `retrievable` to `hidden`. diff --git a/sdk/search/azure-search-documents/README.md b/sdk/search/azure-search-documents/README.md index 41aa64191f9c..c46bf33ef01d 100644 --- a/sdk/search/azure-search-documents/README.md +++ b/sdk/search/azure-search-documents/README.md @@ -44,20 +44,20 @@ and [admin key](https://docs.microsoft.com/en-us/azure/search/search-security-ap ```Java -SearchServiceClient searchServiceClient = new SearchServiceClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(adminKey)) - .buildClient(); +private SearchClient searchClient = new SearchClientBuilder().buildClient(); + +public void createSearchClient() { + SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() ``` or ```Java -SearchServiceAsyncClient searchServiceAsyncClient = new SearchServiceClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(adminKey)) - .buildAsyncClient(); +} + +public void createAsyncSearchClient() { + SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() ``` #### Create a SearchIndexClient @@ -69,22 +69,22 @@ Note that you will need an admin key to index documents (query keys only work fo ```Java -SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(apiKey)) - .indexName(indexName) - .buildClient(); +} + +public void createIndexClient() { + SearchClient searchClient = new SearchClientBuilder() + .endpoint(endpoint) ``` or ```Java -SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() - .endpoint(endpoint) - .credential(new AzureKeyCredential(apiKey)) - .indexName(indexName) - .buildAsyncClient(); +} + +public void createAsyncIndexClient() { + SearchAsyncClient searchAsyncClient = new SearchClientBuilder() + .endpoint(endpoint) ``` ## Key concepts @@ -106,54 +106,54 @@ There are several types of operations that can be executed against the service: ### Create an index -Create Index using `searchIndexClient` instantiated in [Create a SearchServiceClient](#create-a-searchserviceclient) +Create Index using `searchClient` instantiated in [Create a SearchServiceClient](#create-a-searchserviceclient) ```java -SearchIndex newIndex = new SearchIndex() - .setName("index_name") - .setFields( - Arrays.asList(new SearchField() - .setName("Name") - .setType(SearchFieldDataType.STRING) - .setKey(Boolean.TRUE), - new SearchField() - .setName("Cuisine") - .setType(SearchFieldDataType.STRING))); -// Create index. -searchServiceClient.createIndex(newIndex); +} + +public void createIndexWithSyncClient() { + SearchIndex newIndex = new SearchIndex() + .setName("index_name") + .setFields( + Arrays.asList(new SearchField() + .setName("Name") + .setType(SearchFieldDataType.STRING) + .setKey(Boolean.TRUE), + new SearchField() + .setName("Cuisine") ``` ### Upload a Document -Upload hotel document to Search Index using `searchIndexClient` instantiated [Create a SearchIndexClient](#create-a-searchindexclient) +Upload hotel document to Search Index using `searchClient` instantiated [Create a SearchIndexClient](#create-a-searchindexclient) ```java -List hotels = new ArrayList<>(); -hotels.add(new Hotel().setHotelId("100")); -hotels.add(new Hotel().setHotelId("200")); -hotels.add(new Hotel().setHotelId("300")); -// Upload hotel. -searchIndexClient.uploadDocuments(hotels); +} + +public void uploadDocumentWithSyncClient() { + List hotels = new ArrayList<>(); + hotels.add(new Hotel().setHotelId("100")); + hotels.add(new Hotel().setHotelId("200")); ``` ### Search on hotel name -Search hotel using keyword using `searchIndexClient` instantiated in [Create a SearchIndexClient](#create-a-searchindexclient) +Search hotel using keyword using `searchClient` instantiated in [Create a SearchIndexClient](#create-a-searchindexclient) ```java -// Perform a text-based search -for (SearchResult result : searchIndexClient.search("luxury hotel", - new SearchOptions(), new RequestOptions(), Context.NONE)) { - // Each result is a dynamic Map - SearchDocument doc = result.getDocument(); - String hotelName = (String) doc.get("HotelName"); - Double rating = (Double) doc.get("Rating"); - System.out.printf("%s: %s%n", hotelName, rating); -} +oid searchTextWithSyncClient() { +erform a text-based search +(SearchResult result : searchClient.search("luxury hotel", +new SearchOptions(), new RequestOptions(), Context.NONE)) { + +// Each result is a dynamic Map +SearchDocument doc = result.getDocument(); +String hotelName = (String) doc.get("HotelName"); +Double rating = (Double) doc.get("Rating"); ``` - Samples are explained in detail [here][samples_readme]. diff --git a/sdk/search/azure-search-documents/pom.xml b/sdk/search/azure-search-documents/pom.xml index 62d6d1e2012c..9ef1dc2068af 100644 --- a/sdk/search/azure-search-documents/pom.xml +++ b/sdk/search/azure-search-documents/pom.xml @@ -109,6 +109,7 @@ --add-exports com.azure.core/com.azure.core.implementation.http=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 diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java similarity index 99% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexAsyncClient.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java index 3cb3cf7db372..b08c986de9b3 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchAsyncClient.java @@ -58,8 +58,8 @@ /** * Cognitive Search Asynchronous Client to query an index and upload, merge, or delete documents */ -@ServiceClient(builder = SearchIndexClientBuilder.class, isAsync = true) -public final class SearchIndexAsyncClient { +@ServiceClient(builder = SearchClientBuilder.class, isAsync = true) +public final class SearchAsyncClient { /* * Representation of the Multi-Status HTTP response code. */ @@ -88,7 +88,7 @@ public final class SearchIndexAsyncClient { /** * The logger to be used */ - private final ClientLogger logger = new ClientLogger(SearchIndexAsyncClient.class); + private final ClientLogger logger = new ClientLogger(SearchAsyncClient.class); /** * The underlying AutoRest client used to interact with the Azure Cognitive Search service @@ -101,9 +101,9 @@ public final class SearchIndexAsyncClient { private final HttpPipeline httpPipeline; /** - * Package private constructor to be used by {@link SearchIndexClientBuilder} + * Package private constructor to be used by {@link SearchClientBuilder} */ - SearchIndexAsyncClient(String endpoint, String indexName, SearchServiceVersion serviceVersion, + SearchAsyncClient(String endpoint, String indexName, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { this.endpoint = endpoint; diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java similarity index 98% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexClient.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java index 704c7c2c77a8..cb85863eb03b 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClient.java @@ -27,18 +27,18 @@ /** * Cognitive Search Synchronous Client to query an index and upload, merge, or delete documents */ -@ServiceClient(builder = SearchIndexClientBuilder.class) -public final class SearchIndexClient { +@ServiceClient(builder = SearchClientBuilder.class) +public final class SearchClient { - private final SearchIndexAsyncClient asyncClient; + private final SearchAsyncClient asyncClient; /** - * Package private constructor to be used by {@link SearchIndexClientBuilder} + * Package private constructor to be used by {@link SearchClientBuilder} * - * @param searchIndexAsyncClient Async SearchIndex Client + * @param searchAsyncClient Async SearchIndex Client */ - SearchIndexClient(SearchIndexAsyncClient searchIndexAsyncClient) { - this.asyncClient = searchIndexAsyncClient; + SearchClient(SearchAsyncClient searchAsyncClient) { + this.asyncClient = searchAsyncClient; } /** 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 new file mode 100644 index 000000000000..8f8e513a9f59 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchClientBuilder.java @@ -0,0 +1,311 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.search.documents; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.credential.AzureKeyCredential; +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.AddHeadersPolicy; +import com.azure.core.http.policy.AzureKeyCredentialPolicy; +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.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; + +import java.net.MalformedURLException; +import java.net.URL; +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 SearchClient + * SearchClients} and {@link SearchAsyncClient SearchAsyncClients}. Call {@link #buildClient() + * buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively to construct an instance of the desired + * client. + *

+ * The following information must be provided to successfully create a client. + *

+ */ +@ServiceClientBuilder(serviceClients = {SearchClient.class, SearchAsyncClient.class}) +public final class SearchClientBuilder { + private static final String API_KEY = "api-key"; + + /* + * This header tells the service to return the request ID in the HTTP response. This is useful for correlating the + * request sent to the response. + */ + private static final String ECHO_REQUEST_ID_HEADER = "return-client-request-id"; + + private static final String SEARCH_PROPERTIES = "azure-search-documents.properties"; + private static final String NAME = "name"; + private static final String VERSION = "version"; + + private final ClientLogger logger = new ClientLogger(SearchClientBuilder.class); + private final List policies = new ArrayList<>(); + private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); + + private final String clientName; + private final String clientVersion; + + private AzureKeyCredential keyCredential; + private SearchServiceVersion serviceVersion; + private String endpoint; + private HttpClient httpClient; + private HttpPipeline httpPipeline; + private HttpLogOptions httpLogOptions = new HttpLogOptions(); + private Configuration configuration; + private String indexName; + private RetryPolicy retryPolicy; + + + /** + * Creates a builder instance that is able to configure and construct {@link SearchClient SearchClients} + * and {@link SearchAsyncClient SearchAsyncClients}. + */ + public SearchClientBuilder() { + Map properties = CoreUtils.getProperties(SEARCH_PROPERTIES); + clientName = properties.getOrDefault(NAME, "UnknownName"); + clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); + } + + /** + * 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 {@code null}. + */ + public SearchClient buildClient() { + return new SearchClient(buildAsyncClient()); + } + + /** + * 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 {@code null}. + */ + public SearchAsyncClient buildAsyncClient() { + Objects.requireNonNull(indexName, "'indexName' cannot be null."); + Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); + + SearchServiceVersion buildVersion = (serviceVersion == null) + ? SearchServiceVersion.getLatest() + : serviceVersion; + + if (httpPipeline != null) { + return new SearchAsyncClient(endpoint, indexName, buildVersion, httpPipeline); + } + + Configuration buildConfiguration = (configuration == null) + ? Configuration.getGlobalConfiguration() + : configuration; + + // Closest to API goes first, closest to wire goes last. + final List httpPipelinePolicies = new ArrayList<>(); + httpPipelinePolicies.add(new AddHeadersPolicy(headers)); + httpPipelinePolicies.add(new RequestIdPolicy()); + + HttpPolicyProviders.addBeforeRetryPolicies(httpPipelinePolicies); + httpPipelinePolicies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); + + httpPipelinePolicies.add(new AddDatePolicy()); + if (keyCredential != null) { + this.policies.add(new AzureKeyCredentialPolicy(API_KEY, keyCredential)); + } + httpPipelinePolicies.addAll(this.policies); + + HttpPolicyProviders.addAfterRetryPolicies(httpPipelinePolicies); + + httpPipelinePolicies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, + buildConfiguration)); + httpPipelinePolicies.add(new HttpLoggingPolicy(httpLogOptions)); + + HttpPipeline buildPipeline = new HttpPipelineBuilder() + .httpClient(httpClient) + .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) + .build(); + + return new SearchAsyncClient(endpoint, indexName, buildVersion, buildPipeline); + } + + /** + * Sets the service endpoint for the Azure Search instance. + * + * @param endpoint The URL of the Azure Search instance. + * @return The updated SearchClientBuilder object. + * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. + */ + public SearchClientBuilder endpoint(String endpoint) { + try { + new URL(endpoint); + } catch (MalformedURLException ex) { + throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); + } + this.endpoint = endpoint; + return this; + } + + /** + * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. + * + * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. + * @return The updated SearchClientBuilder object. + * @throws NullPointerException If {@code keyCredential} is {@code null}. + * @throws IllegalArgumentException If {@link AzureKeyCredential#getKey()} is {@code null} or empty. + */ + public SearchClientBuilder credential(AzureKeyCredential keyCredential) { + if (keyCredential == null) { + throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); + } + if (CoreUtils.isNullOrEmpty(keyCredential.getKey())) { + throw logger.logExceptionAsError( + new IllegalArgumentException("'keyCredential' cannot have a null or empty API key.")); + } + this.keyCredential = keyCredential; + 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 {@code null} or empty. + */ + public SearchClientBuilder indexName(String indexName) { + if (CoreUtils.isNullOrEmpty(indexName)) { + throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); + } + this.indexName = indexName; + return this; + } + + /** + * Sets the logging configuration for HTTP requests and responses. + *

+ * If logging configurations aren't provided HTTP requests and responses won't be logged. + * + * @param logOptions The logging configuration for HTTP requests and responses. + * @return The updated SearchClientBuilder object. + */ + public SearchClientBuilder httpLogOptions(HttpLogOptions logOptions) { + httpLogOptions = logOptions; + return this; + } + + /** + * Adds a pipeline policy to apply to each request sent. + *

+ * This method may be called multiple times, each time it is called the policy will be added to the end of added + * policy list. All policies will be added after the retry policy. + * + * @param policy The pipeline policies to added to the policy list. + * @return The updated SearchClientBuilder object. + * @throws NullPointerException If {@code policy} is {@code null}. + */ + public SearchClientBuilder addPolicy(HttpPipelinePolicy policy) { + policies.add(Objects.requireNonNull(policy)); + return this; + } + + /** + * Sets the HTTP client to use for sending requests and receiving responses. + * + * @param client The HTTP client that will handle sending requests and receiving responses. + * @return The updated SearchClientBuilder object. + */ + 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; + return this; + } + + /** + * Sets the HTTP pipeline to use for the service client. + *

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

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

+ * A default retry policy will be supplied if one isn't provided. + * + * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. + * @return The updated SearchClientBuilder object. + */ + public SearchClientBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + /** + * Sets the {@link SearchServiceVersion} that is used when making API requests. + *

+ * If a service version is not provided, {@link SearchServiceVersion#getLatest()} will be used as a default. When + * this default is used updating to a newer client library may result in a newer version of the service being used. + * + * @param serviceVersion The version of the service to be used when making requests. + * @return The updated SearchClientBuilder object. + */ + public SearchClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + this.serviceVersion = serviceVersion; + return this; + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/FieldBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/FieldBuilder.java similarity index 98% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/FieldBuilder.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/FieldBuilder.java index 2bdd7f5ac9a3..e741a872772d 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/FieldBuilder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/FieldBuilder.java @@ -1,12 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.indexes.FieldIgnore; -import com.azure.search.documents.indexes.SearchableFieldProperty; -import com.azure.search.documents.indexes.SimpleFieldProperty; import com.azure.search.documents.models.GeoPoint; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; import com.azure.search.documents.indexes.models.SearchField; 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 new file mode 100644 index 000000000000..42f6cc72baf1 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexAsyncClient.java @@ -0,0 +1,642 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.indexes; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedResponse; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.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.converters.RequestOptionsIndexesConverter; +import com.azure.search.documents.implementation.converters.SearchIndexConverter; +import com.azure.search.documents.implementation.converters.SynonymMapConverter; +import com.azure.search.documents.implementation.util.MappingUtils; +import com.azure.search.documents.indexes.implementation.SearchServiceRestClientBuilder; +import com.azure.search.documents.indexes.implementation.SearchServiceRestClientImpl; +import com.azure.search.documents.indexes.models.AnalyzeRequest; +import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; +import com.azure.search.documents.indexes.models.GetIndexStatisticsResult; +import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.indexes.models.ServiceStatistics; +import com.azure.search.documents.indexes.models.SynonymMap; +import com.azure.search.documents.models.RequestOptions; +import reactor.core.publisher.Mono; + +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; + +/** + * Asynchronous Client to manage and query indexes, as well as Synonym Map, on a Cognitive Search service + */ +@ServiceClient(builder = SearchIndexClientBuilder.class, isAsync = true) +public final class SearchIndexAsyncClient { + + /** + * Search REST API Version + */ + private final SearchServiceVersion serviceVersion; + + /** + * The endpoint for the Azure Cognitive Search service. + */ + private final String endpoint; + + /** + * The logger to be used + */ + private final ClientLogger logger = new ClientLogger(SearchIndexAsyncClient.class); + + /** + * The underlying AutoRest client used to interact with the Search service + */ + private final SearchServiceRestClientImpl restClient; + + /** + * The pipeline that powers this client. + */ + private final HttpPipeline httpPipeline; + + SearchIndexAsyncClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { + this.endpoint = endpoint; + this.serviceVersion = serviceVersion; + this.httpPipeline = httpPipeline; + + this.restClient = new SearchServiceRestClientBuilder() + .endpoint(endpoint) + .apiVersion(serviceVersion.getVersion()) + .pipeline(httpPipeline) + .build(); + } + + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return the pipeline. + */ + HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * Gets search service version. + * + * @return the search service version value. + */ + public SearchServiceVersion getServiceVersion() { + return this.serviceVersion; + } + + /** + * Gets the endpoint for the Azure Cognitive Search service. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Initializes a new {@link SearchAsyncClient} using the given Index name and the same configuration as the + * SearchServiceAsyncClient. + * + * @param indexName the name of the Index for the client + * @return a {@link SearchAsyncClient} created from the service client configuration + */ + public SearchAsyncClient getSearchAsyncClient(String indexName) { + return getSearchClientBuilder(indexName).buildAsyncClient(); + } + + SearchClientBuilder getSearchClientBuilder(String indexName) { + return new SearchClientBuilder() + .endpoint(endpoint) + .indexName(indexName) + .serviceVersion(serviceVersion) + .pipeline(httpPipeline); + } + + /** + * Creates a new Azure Cognitive Search index. + * + * @param index definition of the index to create. + * @return the created Index. + */ + public Mono createIndex(SearchIndex index) { + return createIndexWithResponse(index, null).map(Response::getValue); + } + + /** + * Creates a new Azure Cognitive Search index. + * + * @param index definition of the index to create + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the created Index. + */ + public Mono> createIndexWithResponse(SearchIndex index, RequestOptions requestOptions) { + return withContext(context -> createIndexWithResponse(index, requestOptions, context)); + } + + Mono> createIndexWithResponse(SearchIndex index, RequestOptions requestOptions, + Context context) { + Objects.requireNonNull(index, "'Index' cannot be null"); + try { + return restClient.indexes() + .createWithRestResponseAsync(SearchIndexConverter.map(index), + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalSearchIndex); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Retrieves an index definition from the Azure Cognitive Search. + * + * @param indexName The name of the index to retrieve + * @return the Index. + */ + public Mono getIndex(String indexName) { + return getIndexWithResponse(indexName, null).map(Response::getValue); + } + + /** + * Retrieves an index definition from the Azure Cognitive Search. + * + * @param indexName the name of the index to retrieve + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the Index. + */ + public Mono> getIndexWithResponse(String indexName, RequestOptions requestOptions) { + return withContext(context -> getIndexWithResponse(indexName, requestOptions, context)); + } + + Mono> getIndexWithResponse(String indexName, RequestOptions requestOptions, Context context) { + try { + return restClient.indexes() + .getWithRestResponseAsync(indexName, RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalSearchIndex); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * 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 + * @return the index statistics result. + */ + public Mono getIndexStatistics(String indexName) { + return getIndexStatisticsWithResponse(indexName, null).map(Response::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 additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the index statistics result. + */ + public Mono> getIndexStatisticsWithResponse(String indexName, + RequestOptions requestOptions) { + return withContext(context -> getIndexStatisticsWithResponse(indexName, requestOptions, context)); + } + + Mono> getIndexStatisticsWithResponse(String indexName, + RequestOptions requestOptions, Context context) { + try { + return restClient.indexes() + .getStatisticsWithRestResponseAsync(indexName, RequestOptionsIndexesConverter.map(requestOptions), + context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingGetIndexStatistics); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Lists all indexes available for an Azure Cognitive Search service. + * + * @return a reactive response emitting the list of indexes. + */ + public PagedFlux listIndexes() { + return listIndexes(null, null); + } + + /** + * Lists all indexes available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a reactive response emitting the list of indexes. + */ + public PagedFlux listIndexes(String select, RequestOptions requestOptions) { + try { + return new PagedFlux<>(() -> + withContext(context -> this.listIndexesWithResponse(select, requestOptions, context))); + } catch (RuntimeException ex) { + return pagedFluxError(logger, ex); + } + } + + PagedFlux listIndexes(String select, RequestOptions requestOptions, Context context) { + try { + return new PagedFlux<>(() -> this.listIndexesWithResponse(select, requestOptions, context)); + } catch (RuntimeException ex) { + return pagedFluxError(logger, ex); + } + } + + private Mono> listIndexesWithResponse(String select, RequestOptions requestOptions, + Context context) { + return restClient.indexes() + .listWithRestResponseAsync(select, RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingPagingSearchIndex); + } + + /** + * Creates a new Azure Cognitive Search index or updates an index if it already exists. + * + * @param index the definition of the {@link SearchIndex} to create or update. + * @return the index that was created or updated. + */ + public Mono createOrUpdateIndex(SearchIndex index) { + return createOrUpdateIndexWithResponse(index, false, false, null).map(Response::getValue); + } + + /** + * Creates a new Azure Cognitive Search index or updates an index if it already exists. + * + * @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. + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the index that was created or updated + */ + public Mono> createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, + boolean onlyIfUnchanged, RequestOptions requestOptions) { + return withContext(context -> + createOrUpdateIndexWithResponse(index, allowIndexDowntime, onlyIfUnchanged, requestOptions, context)); + } + + Mono> createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, + boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { + try { + Objects.requireNonNull(index, "'Index' cannot null."); + String ifMatch = onlyIfUnchanged ? index.getETag() : null; + return restClient.indexes() + .createOrUpdateWithRestResponseAsync(index.getName(), SearchIndexConverter.map(index), + allowIndexDowntime, ifMatch, null, + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalSearchIndex); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Deletes an Azure Cognitive Search index and all the documents it contains. + * + * @param indexName the name of the index to delete + * @return a response signalling completion. + */ + public Mono deleteIndex(String indexName) { + return withContext(context -> deleteIndexWithResponse(indexName, null, null, null).flatMap(FluxUtil::toMono)); + } + + /** + * Deletes an Azure Cognitive Search index and all the documents it contains. + * + * @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. + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response signalling completion. + */ + public Mono> deleteIndexWithResponse(SearchIndex index, boolean onlyIfUnchanged, + RequestOptions requestOptions) { + Objects.requireNonNull(index, "'Index' cannot be null."); + String etag = onlyIfUnchanged ? index.getETag() : null; + return withContext(context -> deleteIndexWithResponse(index.getName(), etag, requestOptions, context)); + } + + Mono> deleteIndexWithResponse(String indexName, String etag, RequestOptions requestOptions, + Context context) { + try { + return restClient.indexes() + .deleteWithRestResponseAsync(indexName, etag, null, + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(Function.identity()); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Shows how an analyzer breaks text into tokens. + * + * @param indexName the name of the index for which to test an analyzer + * @param analyzeRequest the text and analyzer or analysis components to test + * @return analyze result. + */ + public PagedFlux analyzeText(String indexName, AnalyzeRequest analyzeRequest) { + return analyzeText(indexName, analyzeRequest, null); + } + + /** + * Shows how an analyzer breaks text into tokens. + * + * @param indexName the name of the index for which to test an analyzer + * @param analyzeRequest the text and analyzer or analysis components to test + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing analyze result. + */ + public PagedFlux analyzeText(String indexName, AnalyzeRequest analyzeRequest, + RequestOptions requestOptions) { + try { + return new PagedFlux<>(() -> + withContext(context -> analyzeTextWithResponse(indexName, analyzeRequest, requestOptions, context))); + } catch (RuntimeException ex) { + return pagedFluxError(logger, ex); + } + } + + PagedFlux analyzeText(String indexName, AnalyzeRequest analyzeRequest, + RequestOptions requestOptions, Context context) { + try { + return new PagedFlux<>(() -> analyzeTextWithResponse(indexName, analyzeRequest, requestOptions, context)); + } catch (RuntimeException ex) { + return pagedFluxError(logger, ex); + } + } + + private Mono> analyzeTextWithResponse(String indexName, + AnalyzeRequest analyzeRequest, RequestOptions requestOptions, Context context) { + return restClient.indexes() + .analyzeWithRestResponseAsync(indexName, AnalyzeRequestConverter.map(analyzeRequest), + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingTokenInfo); + } + + /** + * Creates a new Azure Cognitive Search synonym map. + * + * @param synonymMap the definition of the synonym map to create + * @return the created {@link SynonymMap}. + */ + public Mono createSynonymMap(SynonymMap synonymMap) { + return createSynonymMapWithResponse(synonymMap, null).map(Response::getValue); + } + + /** + * Creates a new Azure Cognitive Search synonym map. + * + * @param synonymMap the definition of the {@link SynonymMap} to create + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the created SynonymMap. + */ + public Mono> createSynonymMapWithResponse(SynonymMap synonymMap, + RequestOptions requestOptions) { + return withContext(context -> createSynonymMapWithResponse(synonymMap, requestOptions, context)); + } + + Mono> createSynonymMapWithResponse(SynonymMap synonymMap, RequestOptions requestOptions, + Context context) { + Objects.requireNonNull(synonymMap, "'SynonymMap' cannot be null."); + try { + return restClient.synonymMaps() + .createWithRestResponseAsync(SynonymMapConverter.map(synonymMap), + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalSynonymMap); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Retrieves a synonym map definition. + * + * @param synonymMapName name of the synonym map to retrieve + * @return the {@link SynonymMap} definition + */ + public Mono getSynonymMap(String synonymMapName) { + return getSynonymMapWithResponse(synonymMapName, null).map(Response::getValue); + } + + /** + * Retrieves a synonym map definition. + * + * @param synonymMapName name of the synonym map to retrieve + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the SynonymMap. + */ + public Mono> getSynonymMapWithResponse(String synonymMapName, RequestOptions requestOptions) { + return withContext(context -> getSynonymMapWithResponse(synonymMapName, requestOptions, context)); + } + + Mono> getSynonymMapWithResponse(String synonymMapName, RequestOptions requestOptions, + Context context) { + try { + return restClient.synonymMaps() + .getWithRestResponseAsync(synonymMapName, RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalSynonymMap); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Lists all synonym maps available for an Azure Cognitive Search service. + * + * @return a reactive response emitting the list of synonym maps. + */ + public PagedFlux listSynonymMaps() { + return listSynonymMaps(null, null); + } + + /** + * Lists all synonym maps available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a reactive response emitting the list of synonym maps. + */ + public PagedFlux listSynonymMaps(String select, RequestOptions requestOptions) { + try { + return new PagedFlux<>(() -> + withContext(context -> listSynonymMapsWithResponse(select, requestOptions, context))); + } catch (RuntimeException ex) { + return pagedFluxError(logger, ex); + } + } + + PagedFlux listSynonymMaps(String select, RequestOptions requestOptions, Context context) { + try { + return new PagedFlux<>(() -> listSynonymMapsWithResponse(select, requestOptions, context)); + } catch (RuntimeException ex) { + return pagedFluxError(logger, ex); + } + } + + private Mono> listSynonymMapsWithResponse(String select, RequestOptions requestOptions, + Context context) { + return restClient.synonymMaps() + .listWithRestResponseAsync(select, RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingPagingSynonymMap); + } + + /** + * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. + * + * @param synonymMap the definition of the {@link SynonymMap} to create or update + * @return the synonym map that was created or updated. + */ + public Mono createOrUpdateSynonymMap(SynonymMap synonymMap) { + return createOrUpdateSynonymMapWithResponse(synonymMap, false, null).map(Response::getValue); + } + + /** + * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. + * + * @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. + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response containing the synonym map that was created or updated. + */ + public Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, + boolean onlyIfUnchanged, RequestOptions requestOptions) { + return withContext(context -> + createOrUpdateSynonymMapWithResponse(synonymMap, onlyIfUnchanged, requestOptions, context)); + } + + Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, + boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { + Objects.requireNonNull(synonymMap, "'SynonymMap' cannot be null."); + String ifMatch = onlyIfUnchanged ? synonymMap.getETag() : null; + try { + return restClient.synonymMaps() + .createOrUpdateWithRestResponseAsync(synonymMap.getName(), SynonymMapConverter.map(synonymMap), + ifMatch, null, + RequestOptionsIndexesConverter.map(requestOptions), + context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalSynonymMap); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Deletes an Azure Cognitive Search synonym map. + * + * @param synonymMapName the name of the {@link SynonymMap} to delete + * @return a response signalling completion. + */ + public Mono deleteSynonymMap(String synonymMapName) { + return withContext(context -> deleteSynonymMapWithResponse(synonymMapName, null, null, context) + .flatMap(FluxUtil::toMono)); + } + + /** + * Deletes an Azure Cognitive Search synonym map. + * + * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return a response signalling completion. + */ + public Mono> deleteSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, + RequestOptions requestOptions) { + Objects.requireNonNull(synonymMap, "'SynonymMap' cannot be null"); + String etag = onlyIfUnchanged ? synonymMap.getETag() : null; + return withContext(context -> + deleteSynonymMapWithResponse(synonymMap.getName(), etag, requestOptions, context)); + } + + Mono> deleteSynonymMapWithResponse(String synonymMapName, String etag, + RequestOptions requestOptions, Context context) { + try { + return restClient.synonymMaps() + .deleteWithRestResponseAsync(synonymMapName, etag, null, + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(Function.identity()); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns service level statistics for a search service, including service counters and limits. + *

+ * Contains the tracking ID sent with the request to help with debugging + * + * @return the search service statistics result. + */ + public Mono getServiceStatistics() { + return getServiceStatisticsWithResponse(null).map(Response::getValue); + } + + + /** + * Returns service level statistics for a search service, including service counters and limits. + * + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @return the search service statistics result. + */ + public Mono> getServiceStatisticsWithResponse(RequestOptions requestOptions) { + return withContext(context -> getServiceStatisticsWithResponse(requestOptions, context)); + } + + Mono> getServiceStatisticsWithResponse(RequestOptions requestOptions, Context context) { + try { + return restClient.getServiceStatisticsWithRestResponseAsync( + RequestOptionsIndexesConverter.map(requestOptions), context) + .onErrorMap(MappingUtils::exceptionMapper) + .map(MappingUtils::mappingExternalServiceStatistics); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java new file mode 100644 index 000000000000..f14aa32a3ba9 --- /dev/null +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClient.java @@ -0,0 +1,393 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.indexes; + +import com.azure.core.annotation.ServiceClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.search.documents.SearchClient; +import com.azure.search.documents.SearchServiceVersion; +import com.azure.search.documents.indexes.models.AnalyzeRequest; +import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; +import com.azure.search.documents.indexes.models.GetIndexStatisticsResult; +import com.azure.search.documents.models.RequestOptions; +import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.indexes.models.ServiceStatistics; +import com.azure.search.documents.indexes.models.SynonymMap; + +/** + * Synchronous Client to manage and query indexes, as well as manage Synonym Map, on a Cognitive Search service + */ +@ServiceClient(builder = SearchIndexClientBuilder.class) +public final class SearchIndexClient { + private final SearchIndexAsyncClient asyncClient; + + SearchIndexClient(SearchIndexAsyncClient searchIndexAsyncClient) { + this.asyncClient = searchIndexAsyncClient; + } + + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return the pipeline. + */ + HttpPipeline getHttpPipeline() { + return this.asyncClient.getHttpPipeline(); + } + + /** + * Gets search service version. + * + * @return the search service version value. + */ + public SearchServiceVersion getServiceVersion() { + return this.asyncClient.getServiceVersion(); + } + + /** + * Gets the endpoint for the Azure Cognitive Search service. + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.asyncClient.getEndpoint(); + } + + /** + * Initializes a new {@link SearchClient} using the given Index name and the same configuration as the + * SearchServiceClient. + * + * @param indexName the name of the Index for the client + * @return a {@link SearchClient} created from the service client configuration + */ + public SearchClient getSearchClient(String indexName) { + return asyncClient.getSearchClientBuilder(indexName).buildClient(); + } + + /** + * Creates a new Azure Cognitive Search index + * + * @param index definition of the index to create + * @return the created Index. + */ + public SearchIndex createIndex(SearchIndex index) { + return createIndexWithResponse(index, null, Context.NONE).getValue(); + } + + /** + * Creates a new Azure Cognitive Search index + * + * @param index definition of the index to create + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return a response containing the created Index. + */ + public Response createIndexWithResponse(SearchIndex index, RequestOptions requestOptions, + Context context) { + return asyncClient.createIndexWithResponse(index, requestOptions, context).block(); + } + + /** + * Retrieves an index definition from the Azure Cognitive Search. + * + * @param indexName the name of the index to retrieve + * @return the Index. + */ + public SearchIndex getIndex(String indexName) { + return getIndexWithResponse(indexName, null, Context.NONE).getValue(); + } + + /** + * Retrieves an index definition from the Azure Cognitive Search. + * + * @param indexName the name of the index to retrieve + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return a response containing the Index. + */ + public Response getIndexWithResponse(String indexName, RequestOptions requestOptions, + Context context) { + return asyncClient.getIndexWithResponse(indexName, requestOptions, context).block(); + } + + /** + * 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 + * @return the index statistics result. + */ + public GetIndexStatisticsResult getIndexStatistics(String indexName) { + return getIndexStatisticsWithResponse(indexName, null, 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 additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return a response containing the index statistics result. + */ + public Response getIndexStatisticsWithResponse(String indexName, + RequestOptions requestOptions, Context context) { + return asyncClient.getIndexStatisticsWithResponse(indexName, requestOptions, context).block(); + } + + /** + * Lists all indexes available for an Azure Cognitive Search service. + * + * @return the list of indexes. + */ + public PagedIterable listIndexes() { + return listIndexes(null, null, Context.NONE); + } + + /** + * Lists all indexes available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return the list of indexes. + */ + public PagedIterable listIndexes(String select, RequestOptions requestOptions, Context context) { + return new PagedIterable<>(asyncClient.listIndexes(select, requestOptions, context)); + } + + /** + * Creates a new Azure Cognitive Search index or updates an index if it already exists. + * + * @param index the definition of the index to create or update + * @return the index that was created or updated. + */ + public SearchIndex createOrUpdateIndex(SearchIndex index) { + return createOrUpdateIndexWithResponse(index, false, false, null, Context.NONE).getValue(); + } + + /** + * Creates a new Azure Cognitive Search index or updates an index if it already exists. + * + * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @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. + */ + public Response createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, + boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { + return asyncClient.createOrUpdateIndexWithResponse(index, allowIndexDowntime, onlyIfUnchanged, requestOptions, + context).block(); + } + + /** + * Deletes an Azure Cognitive Search index and all the documents it contains. + * + * @param indexName the name of the index to delete + */ + public void deleteIndex(String indexName) { + deleteIndexWithResponse(new SearchIndex().setName(indexName), false, null, Context.NONE); + } + + /** + * Deletes an Azure Cognitive Search index and all the documents it contains. + * + * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the Http pipeline during the service call + * @return a response signalling completion. + */ + public Response deleteIndexWithResponse(SearchIndex index, boolean onlyIfUnchanged, + RequestOptions requestOptions, Context context) { + String etag = onlyIfUnchanged ? index.getETag() : null; + return asyncClient.deleteIndexWithResponse(index.getName(), etag, requestOptions, context).block(); + } + + /** + * Shows how an analyzer breaks text into tokens. + * + * @param indexName the name of the index for which to test an analyzer + * @param analyzeRequest the text and analyzer or analysis components to test + * @return analyze result. + */ + public PagedIterable analyzeText(String indexName, AnalyzeRequest analyzeRequest) { + return analyzeText(indexName, analyzeRequest, null, Context.NONE); + } + + /** + * Shows how an analyzer breaks text into tokens. + * + * @param indexName the name of the index for which to test an analyzer + * @param analyzeRequest the text and analyzer or analysis components to test + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return analyze result. + */ + public PagedIterable analyzeText(String indexName, AnalyzeRequest analyzeRequest, + RequestOptions requestOptions, Context context) { + return new PagedIterable<>(asyncClient.analyzeText(indexName, analyzeRequest, requestOptions, context)); + } + + /** + * Creates a new Azure Cognitive Search synonym map. + * + * @param synonymMap the definition of the synonym map to create + * @return the created {@link SynonymMap}. + */ + public SynonymMap createSynonymMap(SynonymMap synonymMap) { + return createSynonymMapWithResponse(synonymMap, null, Context.NONE).getValue(); + } + + /** + * Creates a new Azure Cognitive Search synonym map. + * + * @param synonymMap the definition of the synonym map to create + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return a response containing the created SynonymMap. + */ + public Response createSynonymMapWithResponse(SynonymMap synonymMap, RequestOptions requestOptions, + Context context) { + return asyncClient.createSynonymMapWithResponse(synonymMap, requestOptions, context).block(); + } + + /** + * Retrieves a synonym map definition. + * + * @param synonymMapName name of the synonym map to retrieve + * @return the {@link SynonymMap} definition + */ + public SynonymMap getSynonymMap(String synonymMapName) { + return getSynonymMapWithResponse(synonymMapName, null, Context.NONE).getValue(); + } + + /** + * Retrieves a synonym map definition. + * + * @param synonymMapName name of the synonym map to retrieve + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context a context that is passed through the HTTP pipeline during the service call + * @return a response containing the SynonymMap. + */ + public Response getSynonymMapWithResponse(String synonymMapName, RequestOptions requestOptions, + Context context) { + return asyncClient.getSynonymMapWithResponse(synonymMapName, requestOptions, context).block(); + } + + /** + * Lists all synonym maps available for an Azure Cognitive Search service. + * + * @return the list of synonym maps. + */ + public PagedIterable listSynonymMaps() { + return listSynonymMaps(null, null, Context.NONE); + } + + /** + * Lists all synonym maps available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return the list of synonym maps. + */ + public PagedIterable listSynonymMaps(String select, RequestOptions requestOptions, Context context) { + return new PagedIterable<>(asyncClient.listSynonymMaps(select, requestOptions, context)); + } + + /** + * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. + * + * @param synonymMap the definition of the synonym map to create or update + * @return the synonym map that was created or updated. + */ + public SynonymMap createOrUpdateSynonymMap(SynonymMap synonymMap) { + return createOrUpdateSynonymMapWithResponse(synonymMap, false, null, Context.NONE).getValue(); + } + + /** + * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. + * + * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @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. + */ + public Response createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, + boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { + return asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, onlyIfUnchanged, requestOptions, context) + .block(); + } + + /** + * Deletes an Azure Cognitive Search synonym map. + * + * @param synonymMapName the name of the synonym map to delete + */ + public void deleteSynonymMap(String synonymMapName) { + deleteSynonymMapWithResponse(new SynonymMap().setName(synonymMapName), false, null, Context.NONE); + } + + /** + * Deletes an Azure Cognitive Search synonym map. + * + * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the Http pipeline during the service call + * @return a response signalling completion. + */ + public Response deleteSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, + RequestOptions requestOptions, Context context) { + String etag = onlyIfUnchanged ? synonymMap.getETag() : null; + return asyncClient.deleteSynonymMapWithResponse(synonymMap.getName(), etag, requestOptions, context) + .block(); + } + + /** + * Returns service level statistics for a search service, including service counters and limits. + * + * @return the search service statistics result. + */ + public ServiceStatistics getServiceStatistics() { + return getServiceStatisticsWithResponse(null, Context.NONE).getValue(); + } + + /** + * Returns service level statistics for a search service, including service counters and limits. + * + * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to + * help with debugging + * @param context additional context that is passed through the HTTP pipeline during the service call + * @return the search service statistics result. + */ + public Response getServiceStatisticsWithResponse(RequestOptions requestOptions, + Context context) { + return asyncClient.getServiceStatisticsWithResponse(requestOptions, context).block(); + } +} diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java similarity index 82% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexClientBuilder.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java index b90fdc13f445..3b8feccd9f41 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexClientBuilder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexClientBuilder.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. - -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.annotation.ServiceClientBuilder; import com.azure.core.credential.AzureKeyCredential; @@ -22,6 +21,7 @@ import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; +import com.azure.search.documents.SearchServiceVersion; import java.net.MalformedURLException; import java.net.URL; @@ -31,15 +31,14 @@ 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}. Call {@link #buildClient() - * buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively to construct an instance of the desired - * client. + * This class provides a fluent builder API to help aid the configuration and instantiation of {@link + * SearchIndexClient SearchIndexClients} and {@link SearchIndexAsyncClient SearchIndexAsyncClients}. Call {@link + * #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively to construct an instance of + * the desired client. *

* The following information must be provided to successfully create a client. *

    *
  • {@link #endpoint(String)}
  • - *
  • {@link #indexName(String)}
  • *
  • {@link #credential(AzureKeyCredential)} or {@link #pipeline(HttpPipeline)}
  • *
*/ @@ -71,13 +70,11 @@ public final class SearchIndexClientBuilder { private HttpPipeline httpPipeline; private HttpLogOptions httpLogOptions = new HttpLogOptions(); private Configuration configuration; - private String indexName; private RetryPolicy retryPolicy; - /** - * Creates a builder instance that is able to configure and construct {@link SearchIndexClient SearchIndexClients} - * and {@link SearchIndexAsyncClient SearchIndexAsyncClients}. + * Creates a builder instance that is able to configure and construct {@link SearchIndexClient + * SearchIndexClients} and {@link SearchIndexAsyncClient SearchIndexAsyncClients}. */ public SearchIndexClientBuilder() { Map properties = CoreUtils.getProperties(SEARCH_PROPERTIES); @@ -89,30 +86,28 @@ public SearchIndexClientBuilder() { * Creates a {@link SearchIndexClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link SearchIndexClient} is created. *

- * If {@link #pipeline(HttpPipeline) pipeline} is set, then only the {@code pipeline}, {@link #endpoint(String) - * endpoint}, and {@link #indexName(String) indexName} are used to create the {@link SearchIndexClient client}. - * All other builder settings are ignored. + * 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 indexName} or {@code endpoint} are {@code null}. + * @throws NullPointerException If {@code endpoint} are {@code null}. */ public SearchIndexClient buildClient() { return new SearchIndexClient(buildAsyncClient()); } /** - * 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. + * 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}, {@link #endpoint(String) - * endpoint}, and {@link #indexName(String) indexName} are used to create the {@link SearchIndexAsyncClient client}. - * All other builder settings are ignored. + * 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 SearchIndexClient with the options set from the builder. - * @throws NullPointerException If {@code indexName} or {@code endpoint} are {@code null}. + * @return A SearchIndexAsyncClient with the options set from the builder. + * @throws NullPointerException If {@code endpoint} are {@code null}. */ public SearchIndexAsyncClient buildAsyncClient() { - Objects.requireNonNull(indexName, "'indexName' cannot be null."); Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) @@ -120,14 +115,12 @@ public SearchIndexAsyncClient buildAsyncClient() { : serviceVersion; if (httpPipeline != null) { - return new SearchIndexAsyncClient(endpoint, indexName, buildVersion, httpPipeline); + return new SearchIndexAsyncClient(endpoint, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration() : configuration; - - // Closest to API goes first, closest to wire goes last. final List httpPipelinePolicies = new ArrayList<>(); httpPipelinePolicies.add(new AddHeadersPolicy(headers)); httpPipelinePolicies.add(new RequestIdPolicy()); @@ -152,7 +145,7 @@ public SearchIndexAsyncClient buildAsyncClient() { .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); - return new SearchIndexAsyncClient(endpoint, indexName, buildVersion, buildPipeline); + return new SearchIndexAsyncClient(endpoint, buildVersion, buildPipeline); } /** @@ -192,21 +185,6 @@ public SearchIndexClientBuilder credential(AzureKeyCredential keyCredential) { return this; } - /** - * Sets the name of the index. - * - * @param indexName Name of the index. - * @return The updated SearchIndexClientBuilder object. - * @throws IllegalArgumentException If {@code indexName} is {@code null} or empty. - */ - public SearchIndexClientBuilder indexName(String indexName) { - if (CoreUtils.isNullOrEmpty(indexName)) { - throw logger.logExceptionAsError(new IllegalArgumentException("'indexName' cannot be null or empty.")); - } - this.indexName = indexName; - return this; - } - /** * Sets the logging configuration for HTTP requests and responses. *

@@ -253,8 +231,8 @@ public SearchIndexClientBuilder httpClient(HttpClient client) { /** * Sets the HTTP pipeline to use for the service client. *

- * 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 SearchIndexClient} or {@link SearchIndexAsyncClient}. + * If {@code pipeline} is set, all other settings are ignored, aside from {@link #endpoint(String) endpoint} when + * building a {@link SearchIndexClient} or {@link SearchIndexAsyncClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated SearchIndexClientBuilder object. diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceAsyncClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java similarity index 58% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceAsyncClient.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java index 41bc03712ce3..e64e17e5f7a8 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceAsyncClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerAsyncClient.java @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; -import com.azure.core.annotation.ServiceClient; +package com.azure.search.documents.indexes; + import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedResponse; @@ -10,26 +10,18 @@ import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; -import com.azure.search.documents.implementation.converters.AnalyzeRequestConverter; +import com.azure.search.documents.SearchServiceVersion; import com.azure.search.documents.implementation.converters.RequestOptionsIndexesConverter; -import com.azure.search.documents.implementation.converters.SearchIndexConverter; import com.azure.search.documents.implementation.converters.SearchIndexerConverter; import com.azure.search.documents.implementation.converters.SearchIndexerDataSourceConverter; import com.azure.search.documents.implementation.converters.SearchIndexerSkillsetConverter; -import com.azure.search.documents.implementation.converters.SynonymMapConverter; import com.azure.search.documents.implementation.util.MappingUtils; import com.azure.search.documents.indexes.implementation.SearchServiceRestClientBuilder; import com.azure.search.documents.indexes.implementation.SearchServiceRestClientImpl; -import com.azure.search.documents.indexes.models.AnalyzeRequest; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.GetIndexStatisticsResult; -import com.azure.search.documents.indexes.models.SearchIndex; import com.azure.search.documents.indexes.models.SearchIndexer; import com.azure.search.documents.indexes.models.SearchIndexerDataSource; import com.azure.search.documents.indexes.models.SearchIndexerSkillset; import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import com.azure.search.documents.indexes.models.ServiceStatistics; -import com.azure.search.documents.indexes.models.SynonymMap; import com.azure.search.documents.models.RequestOptions; import reactor.core.publisher.Mono; @@ -41,11 +33,9 @@ import static com.azure.core.util.FluxUtil.withContext; /** - * Asynchronous Client to manage and query indexes, as well as manage other resources, on a Cognitive Search service + * Asynchronous Client to manage and query indexers, as well as manage other resources, on a Cognitive Search service */ -@ServiceClient(builder = SearchServiceClientBuilder.class, isAsync = true) -public final class SearchServiceAsyncClient { - +public class SearchIndexerAsyncClient { /** * Search REST API Version */ @@ -59,7 +49,7 @@ public final class SearchServiceAsyncClient { /** * The logger to be used */ - private final ClientLogger logger = new ClientLogger(SearchServiceAsyncClient.class); + private final ClientLogger logger = new ClientLogger(SearchIndexerAsyncClient.class); /** * The underlying AutoRest client used to interact with the Search service @@ -71,7 +61,7 @@ public final class SearchServiceAsyncClient { */ private final HttpPipeline httpPipeline; - SearchServiceAsyncClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { + SearchIndexerAsyncClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { this.endpoint = endpoint; this.serviceVersion = serviceVersion; this.httpPipeline = httpPipeline; @@ -92,17 +82,6 @@ HttpPipeline getHttpPipeline() { return this.httpPipeline; } - /** - * Initializes a new {@link SearchIndexAsyncClient} using the given Index name and the same configuration as the - * SearchServiceAsyncClient. - * - * @param indexName the name of the Index for the client - * @return a {@link SearchIndexAsyncClient} created from the service client configuration - */ - public SearchIndexAsyncClient getIndexClient(String indexName) { - return new SearchIndexAsyncClient(endpoint, indexName, serviceVersion, httpPipeline); - } - /** * Gets search service version. * @@ -628,289 +607,6 @@ Mono> getIndexerStatusWithResponse(String indexerN return monoError(logger, ex); } } - - /** - * Creates a new Azure Cognitive Search index. - * - * @param index definition of the index to create. - * @return the created Index. - */ - public Mono createIndex(SearchIndex index) { - return createIndexWithResponse(index, null).map(Response::getValue); - } - - /** - * Creates a new Azure Cognitive Search index. - * - * @param index definition of the index to create - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the created Index. - */ - public Mono> createIndexWithResponse(SearchIndex index, RequestOptions requestOptions) { - return withContext(context -> createIndexWithResponse(index, requestOptions, context)); - } - - Mono> createIndexWithResponse(SearchIndex index, RequestOptions requestOptions, - Context context) { - Objects.requireNonNull(index, "'Index' cannot be null"); - try { - return restClient.indexes() - .createWithRestResponseAsync(SearchIndexConverter.map(index), - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalSearchIndex); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Retrieves an index definition from the Azure Cognitive Search. - * - * @param indexName The name of the index to retrieve - * @return the Index. - */ - public Mono getIndex(String indexName) { - return getIndexWithResponse(indexName, null).map(Response::getValue); - } - - /** - * Retrieves an index definition from the Azure Cognitive Search. - * - * @param indexName the name of the index to retrieve - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the Index. - */ - public Mono> getIndexWithResponse(String indexName, RequestOptions requestOptions) { - return withContext(context -> getIndexWithResponse(indexName, requestOptions, context)); - } - - Mono> getIndexWithResponse(String indexName, RequestOptions requestOptions, Context context) { - try { - return restClient.indexes() - .getWithRestResponseAsync(indexName, RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalSearchIndex); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * 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 - * @return the index statistics result. - */ - public Mono getIndexStatistics(String indexName) { - return getIndexStatisticsWithResponse(indexName, null).map(Response::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 additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the index statistics result. - */ - public Mono> getIndexStatisticsWithResponse(String indexName, - RequestOptions requestOptions) { - return withContext(context -> getIndexStatisticsWithResponse(indexName, requestOptions, context)); - } - - Mono> getIndexStatisticsWithResponse(String indexName, - RequestOptions requestOptions, Context context) { - try { - return restClient.indexes() - .getStatisticsWithRestResponseAsync(indexName, RequestOptionsIndexesConverter.map(requestOptions), - context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingGetIndexStatistics); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Lists all indexes available for an Azure Cognitive Search service. - * - * @return a reactive response emitting the list of indexes. - */ - public PagedFlux listIndexes() { - return listIndexes(null, null); - } - - /** - * Lists all indexes available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a reactive response emitting the list of indexes. - */ - public PagedFlux listIndexes(String select, RequestOptions requestOptions) { - try { - return new PagedFlux<>(() -> - withContext(context -> this.listIndexesWithResponse(select, requestOptions, context))); - } catch (RuntimeException ex) { - return pagedFluxError(logger, ex); - } - } - - PagedFlux listIndexes(String select, RequestOptions requestOptions, Context context) { - try { - return new PagedFlux<>(() -> this.listIndexesWithResponse(select, requestOptions, context)); - } catch (RuntimeException ex) { - return pagedFluxError(logger, ex); - } - } - - private Mono> listIndexesWithResponse(String select, RequestOptions requestOptions, - Context context) { - return restClient.indexes() - .listWithRestResponseAsync(select, RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingPagingSearchIndex); - } - - /** - * Creates a new Azure Cognitive Search index or updates an index if it already exists. - * - * @param index the definition of the {@link SearchIndex} to create or update. - * @return the index that was created or updated. - */ - public Mono createOrUpdateIndex(SearchIndex index) { - return createOrUpdateIndexWithResponse(index, false, false, null).map(Response::getValue); - } - - /** - * Creates a new Azure Cognitive Search index or updates an index if it already exists. - * - * @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. - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the index that was created or updated - */ - public Mono> createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, - boolean onlyIfUnchanged, RequestOptions requestOptions) { - return withContext(context -> - createOrUpdateIndexWithResponse(index, allowIndexDowntime, onlyIfUnchanged, requestOptions, context)); - } - - Mono> createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, - boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { - try { - Objects.requireNonNull(index, "'Index' cannot null."); - String ifMatch = onlyIfUnchanged ? index.getETag() : null; - return restClient.indexes() - .createOrUpdateWithRestResponseAsync(index.getName(), SearchIndexConverter.map(index), - allowIndexDowntime, ifMatch, null, - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalSearchIndex); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Deletes an Azure Cognitive Search index and all the documents it contains. - * - * @param indexName the name of the index to delete - * @return a response signalling completion. - */ - public Mono deleteIndex(String indexName) { - return withContext(context -> deleteIndexWithResponse(indexName, null, null, null).flatMap(FluxUtil::toMono)); - } - - /** - * Deletes an Azure Cognitive Search index and all the documents it contains. - * - * @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. - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response signalling completion. - */ - public Mono> deleteIndexWithResponse(SearchIndex index, boolean onlyIfUnchanged, - RequestOptions requestOptions) { - Objects.requireNonNull(index, "'Index' cannot be null."); - String etag = onlyIfUnchanged ? index.getETag() : null; - return withContext(context -> deleteIndexWithResponse(index.getName(), etag, requestOptions, context)); - } - - Mono> deleteIndexWithResponse(String indexName, String etag, RequestOptions requestOptions, - Context context) { - try { - return restClient.indexes() - .deleteWithRestResponseAsync(indexName, etag, null, - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeRequest the text and analyzer or analysis components to test - * @return analyze result. - */ - public PagedFlux analyzeText(String indexName, AnalyzeRequest analyzeRequest) { - return analyzeText(indexName, analyzeRequest, null); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeRequest the text and analyzer or analysis components to test - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing analyze result. - */ - public PagedFlux analyzeText(String indexName, AnalyzeRequest analyzeRequest, - RequestOptions requestOptions) { - try { - return new PagedFlux<>(() -> - withContext(context -> analyzeTextWithResponse(indexName, analyzeRequest, requestOptions, context))); - } catch (RuntimeException ex) { - return pagedFluxError(logger, ex); - } - } - - PagedFlux analyzeText(String indexName, AnalyzeRequest analyzeRequest, - RequestOptions requestOptions, Context context) { - try { - return new PagedFlux<>(() -> analyzeTextWithResponse(indexName, analyzeRequest, requestOptions, context)); - } catch (RuntimeException ex) { - return pagedFluxError(logger, ex); - } - } - - private Mono> analyzeTextWithResponse(String indexName, - AnalyzeRequest analyzeRequest, RequestOptions requestOptions, Context context) { - return restClient.indexes() - .analyzeWithRestResponseAsync(indexName, AnalyzeRequestConverter.map(analyzeRequest), - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingTokenInfo); - } - /** * Creates a new skillset in an Azure Cognitive Search service. * @@ -1113,236 +809,4 @@ Mono> deleteSkillsetWithResponse(String skillsetName, String etag } } - /** - * Creates a new Azure Cognitive Search synonym map. - * - * @param synonymMap the definition of the synonym map to create - * @return the created {@link SynonymMap}. - */ - public Mono createSynonymMap(SynonymMap synonymMap) { - return createSynonymMapWithResponse(synonymMap, null).map(Response::getValue); - } - - /** - * Creates a new Azure Cognitive Search synonym map. - * - * @param synonymMap the definition of the {@link SynonymMap} to create - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the created SynonymMap. - */ - public Mono> createSynonymMapWithResponse(SynonymMap synonymMap, - RequestOptions requestOptions) { - return withContext(context -> createSynonymMapWithResponse(synonymMap, requestOptions, context)); - } - - Mono> createSynonymMapWithResponse(SynonymMap synonymMap, RequestOptions requestOptions, - Context context) { - Objects.requireNonNull(synonymMap, "'SynonymMap' cannot be null."); - try { - return restClient.synonymMaps() - .createWithRestResponseAsync(SynonymMapConverter.map(synonymMap), - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalSynonymMap); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName name of the synonym map to retrieve - * @return the {@link SynonymMap} definition - */ - public Mono getSynonymMap(String synonymMapName) { - return getSynonymMapWithResponse(synonymMapName, null).map(Response::getValue); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName name of the synonym map to retrieve - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the SynonymMap. - */ - public Mono> getSynonymMapWithResponse(String synonymMapName, RequestOptions requestOptions) { - return withContext(context -> getSynonymMapWithResponse(synonymMapName, requestOptions, context)); - } - - Mono> getSynonymMapWithResponse(String synonymMapName, RequestOptions requestOptions, - Context context) { - try { - return restClient.synonymMaps() - .getWithRestResponseAsync(synonymMapName, RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalSynonymMap); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Lists all synonym maps available for an Azure Cognitive Search service. - * - * @return a reactive response emitting the list of synonym maps. - */ - public PagedFlux listSynonymMaps() { - return listSynonymMaps(null, null); - } - - /** - * Lists all synonym maps available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a reactive response emitting the list of synonym maps. - */ - public PagedFlux listSynonymMaps(String select, RequestOptions requestOptions) { - try { - return new PagedFlux<>(() -> - withContext(context -> listSynonymMapsWithResponse(select, requestOptions, context))); - } catch (RuntimeException ex) { - return pagedFluxError(logger, ex); - } - } - - PagedFlux listSynonymMaps(String select, RequestOptions requestOptions, Context context) { - try { - return new PagedFlux<>(() -> listSynonymMapsWithResponse(select, requestOptions, context)); - } catch (RuntimeException ex) { - return pagedFluxError(logger, ex); - } - } - - private Mono> listSynonymMapsWithResponse(String select, RequestOptions requestOptions, - Context context) { - return restClient.synonymMaps() - .listWithRestResponseAsync(select, RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingPagingSynonymMap); - } - - /** - * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. - * - * @param synonymMap the definition of the {@link SynonymMap} to create or update - * @return the synonym map that was created or updated. - */ - public Mono createOrUpdateSynonymMap(SynonymMap synonymMap) { - return createOrUpdateSynonymMapWithResponse(synonymMap, false, null).map(Response::getValue); - } - - /** - * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. - * - * @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. - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response containing the synonym map that was created or updated. - */ - public Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, - boolean onlyIfUnchanged, RequestOptions requestOptions) { - return withContext(context -> - createOrUpdateSynonymMapWithResponse(synonymMap, onlyIfUnchanged, requestOptions, context)); - } - - Mono> createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, - boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { - Objects.requireNonNull(synonymMap, "'SynonymMap' cannot be null."); - String ifMatch = onlyIfUnchanged ? synonymMap.getETag() : null; - try { - return restClient.synonymMaps() - .createOrUpdateWithRestResponseAsync(synonymMap.getName(), SynonymMapConverter.map(synonymMap), - ifMatch, null, - RequestOptionsIndexesConverter.map(requestOptions), - context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalSynonymMap); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Deletes an Azure Cognitive Search synonym map. - * - * @param synonymMapName the name of the {@link SynonymMap} to delete - * @return a response signalling completion. - */ - public Mono deleteSynonymMap(String synonymMapName) { - return withContext(context -> deleteSynonymMapWithResponse(synonymMapName, null, null, context) - .flatMap(FluxUtil::toMono)); - } - - /** - * Deletes an Azure Cognitive Search synonym map. - * - * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return a response signalling completion. - */ - public Mono> deleteSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, - RequestOptions requestOptions) { - Objects.requireNonNull(synonymMap, "'SynonymMap' cannot be null"); - String etag = onlyIfUnchanged ? synonymMap.getETag() : null; - return withContext(context -> - deleteSynonymMapWithResponse(synonymMap.getName(), etag, requestOptions, context)); - } - - Mono> deleteSynonymMapWithResponse(String synonymMapName, String etag, - RequestOptions requestOptions, Context context) { - try { - return restClient.synonymMaps() - .deleteWithRestResponseAsync(synonymMapName, etag, null, - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(Function.identity()); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - *

- * Contains the tracking ID sent with the request to help with debugging - * - * @return the search service statistics result. - */ - public Mono getServiceStatistics() { - return getServiceStatisticsWithResponse(null).map(Response::getValue); - } - - - /** - * Returns service level statistics for a search service, including service counters and limits. - * - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @return the search service statistics result. - */ - public Mono> getServiceStatisticsWithResponse(RequestOptions requestOptions) { - return withContext(context -> getServiceStatisticsWithResponse(requestOptions, context)); - } - - Mono> getServiceStatisticsWithResponse(RequestOptions requestOptions, Context context) { - try { - return restClient.getServiceStatisticsWithRestResponseAsync( - RequestOptionsIndexesConverter.map(requestOptions), context) - .onErrorMap(MappingUtils::exceptionMapper) - .map(MappingUtils::mappingExternalServiceStatistics); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceClient.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java similarity index 56% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceClient.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java index fec0b5d96f45..a01487064407 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceClient.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClient.java @@ -1,33 +1,27 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; -import com.azure.core.annotation.ServiceClient; +package com.azure.search.documents.indexes; + import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; -import com.azure.search.documents.indexes.models.AnalyzeRequest; -import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; -import com.azure.search.documents.indexes.models.GetIndexStatisticsResult; -import com.azure.search.documents.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchIndex; +import com.azure.search.documents.SearchServiceVersion; import com.azure.search.documents.indexes.models.SearchIndexer; import com.azure.search.documents.indexes.models.SearchIndexerDataSource; import com.azure.search.documents.indexes.models.SearchIndexerSkillset; import com.azure.search.documents.indexes.models.SearchIndexerStatus; -import com.azure.search.documents.indexes.models.ServiceStatistics; -import com.azure.search.documents.indexes.models.SynonymMap; +import com.azure.search.documents.models.RequestOptions; /** - * Synchronous Client to manage and query indexes, as well as manage other resources, on a Cognitive Search service + * Synchronous Client to manage and query indexers, as well as manage other resources, on a Cognitive Search service */ -@ServiceClient(builder = SearchServiceClientBuilder.class) -public final class SearchServiceClient { - private final SearchServiceAsyncClient asyncClient; +public class SearchIndexerClient { + private final SearchIndexerAsyncClient asyncClient; - SearchServiceClient(SearchServiceAsyncClient searchServiceAsyncClient) { - this.asyncClient = searchServiceAsyncClient; + SearchIndexerClient(SearchIndexerAsyncClient searchIndexerAsyncClient) { + this.asyncClient = searchIndexerAsyncClient; } /** @@ -39,17 +33,6 @@ HttpPipeline getHttpPipeline() { return this.asyncClient.getHttpPipeline(); } - /** - * Initializes a new {@link SearchIndexClient} using the given Index name and the same configuration as the - * SearchServiceClient. - * - * @param indexName the name of the Index for the client - * @return a {@link SearchIndexClient} created from the service client configuration - */ - public SearchIndexClient getIndexClient(String indexName) { - return new SearchIndexClient(asyncClient.getIndexClient(indexName)); - } - /** * Gets search service version. * @@ -383,183 +366,6 @@ public Response getIndexerStatusWithResponse(String indexer return asyncClient.getIndexerStatusWithResponse(indexerName, requestOptions, context).block(); } - /** - * Creates a new Azure Cognitive Search index - * - * @param index definition of the index to create - * @return the created Index. - */ - public SearchIndex createIndex(SearchIndex index) { - return createIndexWithResponse(index, null, Context.NONE).getValue(); - } - - /** - * Creates a new Azure Cognitive Search index - * - * @param index definition of the index to create - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the created Index. - */ - public Response createIndexWithResponse(SearchIndex index, RequestOptions requestOptions, - Context context) { - return asyncClient.createIndexWithResponse(index, requestOptions, context).block(); - } - - /** - * Retrieves an index definition from the Azure Cognitive Search. - * - * @param indexName the name of the index to retrieve - * @return the Index. - */ - public SearchIndex getIndex(String indexName) { - return getIndexWithResponse(indexName, null, Context.NONE).getValue(); - } - - /** - * Retrieves an index definition from the Azure Cognitive Search. - * - * @param indexName the name of the index to retrieve - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the Index. - */ - public Response getIndexWithResponse(String indexName, RequestOptions requestOptions, - Context context) { - return asyncClient.getIndexWithResponse(indexName, requestOptions, context).block(); - } - - /** - * 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 - * @return the index statistics result. - */ - public GetIndexStatisticsResult getIndexStatistics(String indexName) { - return getIndexStatisticsWithResponse(indexName, null, 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 additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the index statistics result. - */ - public Response getIndexStatisticsWithResponse(String indexName, - RequestOptions requestOptions, Context context) { - return asyncClient.getIndexStatisticsWithResponse(indexName, requestOptions, context).block(); - } - - /** - * Lists all indexes available for an Azure Cognitive Search service. - * - * @return the list of indexes. - */ - public PagedIterable listIndexes() { - return listIndexes(null, null, Context.NONE); - } - - /** - * Lists all indexes available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of indexes. - */ - public PagedIterable listIndexes(String select, RequestOptions requestOptions, Context context) { - return new PagedIterable<>(asyncClient.listIndexes(select, requestOptions, context)); - } - - /** - * Creates a new Azure Cognitive Search index or updates an index if it already exists. - * - * @param index the definition of the index to create or update - * @return the index that was created or updated. - */ - public SearchIndex createOrUpdateIndex(SearchIndex index) { - return createOrUpdateIndexWithResponse(index, false, false, null, Context.NONE).getValue(); - } - - /** - * Creates a new Azure Cognitive Search index or updates an index if it already exists. - * - * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @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. - */ - public Response createOrUpdateIndexWithResponse(SearchIndex index, boolean allowIndexDowntime, - boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { - return asyncClient.createOrUpdateIndexWithResponse(index, allowIndexDowntime, onlyIfUnchanged, requestOptions, - context).block(); - } - - /** - * Deletes an Azure Cognitive Search index and all the documents it contains. - * - * @param indexName the name of the index to delete - */ - public void deleteIndex(String indexName) { - deleteIndexWithResponse(new SearchIndex().setName(indexName), false, null, Context.NONE); - } - - /** - * Deletes an Azure Cognitive Search index and all the documents it contains. - * - * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the Http pipeline during the service call - * @return a response signalling completion. - */ - public Response deleteIndexWithResponse(SearchIndex index, boolean onlyIfUnchanged, - RequestOptions requestOptions, Context context) { - String etag = onlyIfUnchanged ? index.getETag() : null; - return asyncClient.deleteIndexWithResponse(index.getName(), etag, requestOptions, context).block(); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeRequest the text and analyzer or analysis components to test - * @return analyze result. - */ - public PagedIterable analyzeText(String indexName, AnalyzeRequest analyzeRequest) { - return analyzeText(indexName, analyzeRequest, null, Context.NONE); - } - - /** - * Shows how an analyzer breaks text into tokens. - * - * @param indexName the name of the index for which to test an analyzer - * @param analyzeRequest the text and analyzer or analysis components to test - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return analyze result. - */ - public PagedIterable analyzeText(String indexName, AnalyzeRequest analyzeRequest, - RequestOptions requestOptions, Context context) { - return new PagedIterable<>(asyncClient.analyzeText(indexName, analyzeRequest, requestOptions, context)); - } /** * Creates a new skillset in an Azure Cognitive Search service. @@ -687,150 +493,4 @@ public Response deleteSkillsetWithResponse(SearchIndexerSkillset skillset, return asyncClient.deleteSkillsetWithResponse(skillset.getName(), etag, requestOptions, context).block(); } - /** - * Creates a new Azure Cognitive Search synonym map. - * - * @param synonymMap the definition of the synonym map to create - * @return the created {@link SynonymMap}. - */ - public SynonymMap createSynonymMap(SynonymMap synonymMap) { - return createSynonymMapWithResponse(synonymMap, null, Context.NONE).getValue(); - } - - /** - * Creates a new Azure Cognitive Search synonym map. - * - * @param synonymMap the definition of the synonym map to create - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return a response containing the created SynonymMap. - */ - public Response createSynonymMapWithResponse(SynonymMap synonymMap, RequestOptions requestOptions, - Context context) { - return asyncClient.createSynonymMapWithResponse(synonymMap, requestOptions, context).block(); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName name of the synonym map to retrieve - * @return the {@link SynonymMap} definition - */ - public SynonymMap getSynonymMap(String synonymMapName) { - return getSynonymMapWithResponse(synonymMapName, null, Context.NONE).getValue(); - } - - /** - * Retrieves a synonym map definition. - * - * @param synonymMapName name of the synonym map to retrieve - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context a context that is passed through the HTTP pipeline during the service call - * @return a response containing the SynonymMap. - */ - public Response getSynonymMapWithResponse(String synonymMapName, RequestOptions requestOptions, - Context context) { - return asyncClient.getSynonymMapWithResponse(synonymMapName, requestOptions, context).block(); - } - - /** - * Lists all synonym maps available for an Azure Cognitive Search service. - * - * @return the list of synonym maps. - */ - public PagedIterable listSynonymMaps() { - return listSynonymMaps(null, null, Context.NONE); - } - - /** - * Lists all synonym maps available for an Azure Cognitive 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 additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the list of synonym maps. - */ - public PagedIterable listSynonymMaps(String select, RequestOptions requestOptions, Context context) { - return new PagedIterable<>(asyncClient.listSynonymMaps(select, requestOptions, context)); - } - - /** - * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. - * - * @param synonymMap the definition of the synonym map to create or update - * @return the synonym map that was created or updated. - */ - public SynonymMap createOrUpdateSynonymMap(SynonymMap synonymMap) { - return createOrUpdateSynonymMapWithResponse(synonymMap, false, null, Context.NONE).getValue(); - } - - /** - * Creates a new Azure Cognitive Search synonym map or updates a synonym map if it already exists. - * - * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @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. - */ - public Response createOrUpdateSynonymMapWithResponse(SynonymMap synonymMap, - boolean onlyIfUnchanged, RequestOptions requestOptions, Context context) { - return asyncClient.createOrUpdateSynonymMapWithResponse(synonymMap, onlyIfUnchanged, requestOptions, context) - .block(); - } - - /** - * Deletes an Azure Cognitive Search synonym map. - * - * @param synonymMapName the name of the synonym map to delete - */ - public void deleteSynonymMap(String synonymMapName) { - deleteSynonymMapWithResponse(new SynonymMap().setName(synonymMapName), false, null, Context.NONE); - } - - /** - * Deletes an Azure Cognitive Search synonym map. - * - * @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 requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the Http pipeline during the service call - * @return a response signalling completion. - */ - public Response deleteSynonymMapWithResponse(SynonymMap synonymMap, boolean onlyIfUnchanged, - RequestOptions requestOptions, Context context) { - String etag = onlyIfUnchanged ? synonymMap.getETag() : null; - return asyncClient.deleteSynonymMapWithResponse(synonymMap.getName(), etag, requestOptions, context) - .block(); - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - * - * @return the search service statistics result. - */ - public ServiceStatistics getServiceStatistics() { - return getServiceStatisticsWithResponse(null, Context.NONE).getValue(); - } - - /** - * Returns service level statistics for a search service, including service counters and limits. - * - * @param requestOptions additional parameters for the operation. Contains the tracking ID sent with the request to - * help with debugging - * @param context additional context that is passed through the HTTP pipeline during the service call - * @return the search service statistics result. - */ - public Response getServiceStatisticsWithResponse(RequestOptions requestOptions, - Context context) { - return asyncClient.getServiceStatisticsWithResponse(requestOptions, context).block(); - } } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceClientBuilder.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java similarity index 79% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceClientBuilder.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java index 7540a182b9d5..b365ff5724c1 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchServiceClientBuilder.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerClientBuilder.java @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; + +package com.azure.search.documents.indexes; import com.azure.core.annotation.ServiceClientBuilder; import com.azure.core.credential.AzureKeyCredential; @@ -21,6 +22,7 @@ import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; +import com.azure.search.documents.SearchServiceVersion; import java.net.MalformedURLException; import java.net.URL; @@ -31,7 +33,7 @@ /** * This class provides a fluent builder API to help aid the configuration and instantiation of {@link - * SearchServiceClient SearchServiceClients} and {@link SearchServiceAsyncClient SearchServiceAsyncClients}. Call {@link + * SearchIndexerClient SearchIndexerClients} and {@link SearchIndexerAsyncClient SearchIndexerAsyncClients}. Call {@link * #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively to construct an instance of * the desired client. *

@@ -41,8 +43,8 @@ *

  • {@link #credential(AzureKeyCredential)} or {@link #pipeline(HttpPipeline)}
  • * */ -@ServiceClientBuilder(serviceClients = {SearchServiceClient.class, SearchServiceAsyncClient.class}) -public final class SearchServiceClientBuilder { +@ServiceClientBuilder(serviceClients = {SearchIndexerClient.class, SearchIndexerAsyncClient.class}) +public class SearchIndexerClientBuilder { private static final String API_KEY = "api-key"; /* @@ -55,7 +57,7 @@ public final class SearchServiceClientBuilder { private static final String NAME = "name"; private static final String VERSION = "version"; - private final ClientLogger logger = new ClientLogger(SearchServiceClientBuilder.class); + private final ClientLogger logger = new ClientLogger(SearchIndexerClientBuilder.class); private final List policies = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders().put(ECHO_REQUEST_ID_HEADER, "true"); @@ -72,41 +74,41 @@ public final class SearchServiceClientBuilder { private RetryPolicy retryPolicy; /** - * Creates a builder instance that is able to configure and construct {@link SearchServiceClient - * SearchServiceClients} and {@link SearchServiceAsyncClient SearchServiceAsyncClients}. + * Creates a builder instance that is able to configure and construct {@link SearchIndexerClient + * SearchIndexerClients} and {@link SearchIndexerAsyncClient SearchIndexerAsyncClients}. */ - public SearchServiceClientBuilder() { + public SearchIndexerClientBuilder() { Map properties = CoreUtils.getProperties(SEARCH_PROPERTIES); clientName = properties.getOrDefault(NAME, "UnknownName"); clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); } /** - * Creates a {@link SearchServiceClient} based on options set in the Builder. Every time {@code buildClient()} is - * called a new instance of {@link SearchServiceClient} is created. + * 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 SearchServiceClient client}. All other builder settings are ignored. + * endpoint} are used to create the {@link SearchIndexerClient client}. All other builder settings are ignored. * - * @return A SearchServiceClient with the options set from the builder. + * @return A SearchIndexerClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} are {@code null}. */ - public SearchServiceClient buildClient() { - return new SearchServiceClient(buildAsyncClient()); + public SearchIndexerClient buildClient() { + return new SearchIndexerClient(buildAsyncClient()); } /** - * Creates a {@link SearchServiceAsyncClient} based on options set in the Builder. Every time {@code - * buildAsyncClient()} is called a new instance of {@link SearchServiceAsyncClient} is created. + * 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 SearchServiceAsyncClient client}. All other builder settings are + * endpoint} are used to create the {@link SearchIndexerAsyncClient client}. All other builder settings are * ignored. * - * @return A SearchServiceAsyncClient with the options set from the builder. + * @return A SearchIndexerAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} are {@code null}. */ - public SearchServiceAsyncClient buildAsyncClient() { + public SearchIndexerAsyncClient buildAsyncClient() { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); SearchServiceVersion buildVersion = (serviceVersion == null) @@ -114,7 +116,7 @@ public SearchServiceAsyncClient buildAsyncClient() { : serviceVersion; if (httpPipeline != null) { - return new SearchServiceAsyncClient(endpoint, buildVersion, httpPipeline); + return new SearchIndexerAsyncClient(endpoint, buildVersion, httpPipeline); } Configuration buildConfiguration = (configuration == null) @@ -144,17 +146,17 @@ public SearchServiceAsyncClient buildAsyncClient() { .policies(httpPipelinePolicies.toArray(new HttpPipelinePolicy[0])) .build(); - return new SearchServiceAsyncClient(endpoint, buildVersion, buildPipeline); + return new SearchIndexerAsyncClient(endpoint, buildVersion, buildPipeline); } /** * Sets the service endpoint for the Azure Search instance. * * @param endpoint The URL of the Azure Search instance. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. * @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL. */ - public SearchServiceClientBuilder endpoint(String endpoint) { + public SearchIndexerClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { @@ -168,11 +170,11 @@ public SearchServiceClientBuilder endpoint(String endpoint) { * Sets the {@link AzureKeyCredential} used to authenticate HTTP requests. * * @param keyCredential The {@link AzureKeyCredential} used to authenticate HTTP requests. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. * @throws NullPointerException If {@code keyCredential} is {@code null}. * @throws IllegalArgumentException If {@link AzureKeyCredential#getKey()} is {@code null} or empty. */ - public SearchServiceClientBuilder credential(AzureKeyCredential keyCredential) { + public SearchIndexerClientBuilder credential(AzureKeyCredential keyCredential) { if (keyCredential == null) { throw logger.logExceptionAsError(new NullPointerException("'keyCredential' cannot be null.")); } @@ -190,9 +192,9 @@ public SearchServiceClientBuilder credential(AzureKeyCredential keyCredential) { * If logging configurations aren't provided HTTP requests and responses won't be logged. * * @param logOptions The logging configuration for HTTP requests and responses. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. */ - public SearchServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) { + public SearchIndexerClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; } @@ -204,10 +206,10 @@ public SearchServiceClientBuilder httpLogOptions(HttpLogOptions logOptions) { * policy list. All policies will be added after the retry policy. * * @param policy The pipeline policies to added to the policy list. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ - public SearchServiceClientBuilder addPolicy(HttpPipelinePolicy policy) { + public SearchIndexerClientBuilder addPolicy(HttpPipelinePolicy policy) { policies.add(Objects.requireNonNull(policy)); return this; } @@ -216,9 +218,9 @@ public SearchServiceClientBuilder addPolicy(HttpPipelinePolicy policy) { * Sets the HTTP client to use for sending requests and receiving responses. * * @param client The HTTP client that will handle sending requests and receiving responses. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. */ - public SearchServiceClientBuilder httpClient(HttpClient client) { + public SearchIndexerClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } @@ -231,12 +233,12 @@ public SearchServiceClientBuilder httpClient(HttpClient client) { * Sets the HTTP pipeline to use for the service client. *

    * If {@code pipeline} is set, all other settings are ignored, aside from {@link #endpoint(String) endpoint} when - * building a {@link SearchServiceClient} or {@link SearchServiceAsyncClient}. + * building a {@link SearchIndexerClient} or {@link SearchIndexerAsyncClient}. * * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. */ - public SearchServiceClientBuilder pipeline(HttpPipeline httpPipeline) { + public SearchIndexerClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } @@ -252,9 +254,9 @@ public SearchServiceClientBuilder pipeline(HttpPipeline httpPipeline) { * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. * * @param configuration The configuration store that will be used. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. */ - public SearchServiceClientBuilder configuration(Configuration configuration) { + public SearchIndexerClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } @@ -265,9 +267,9 @@ public SearchServiceClientBuilder configuration(Configuration configuration) { * A default retry policy will be supplied if one isn't provided. * * @param retryPolicy The {@link RetryPolicy} that will attempt to retry requests when needed. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. */ - public SearchServiceClientBuilder retryPolicy(RetryPolicy retryPolicy) { + public SearchIndexerClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } @@ -279,9 +281,9 @@ public SearchServiceClientBuilder retryPolicy(RetryPolicy retryPolicy) { * this default is used updating to a newer client library may result in a newer version of the service being used. * * @param serviceVersion The version of the service to be used when making requests. - * @return The updated SearchServiceClientBuilder object. + * @return The updated SearchIndexerClientBuilder object. */ - public SearchServiceClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { + public SearchIndexerClientBuilder serviceVersion(SearchServiceVersion serviceVersion) { this.serviceVersion = serviceVersion; return this; } diff --git a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexerDataSources.java b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerDataSources.java similarity index 99% rename from sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexerDataSources.java rename to sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerDataSources.java index 5a24be672a8e..743fb2cc453e 100644 --- a/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/SearchIndexerDataSources.java +++ b/sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/SearchIndexerDataSources.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.util.CoreUtils; import com.azure.search.documents.indexes.models.DataChangeDetectionPolicy; 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 e007b5fa993e..d02889222eb5 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 @@ -30,7 +30,7 @@ public class AutoCompleteExample { public static void main(String[] args) { - SearchIndexClient searchClient = new SearchIndexClientBuilder() + SearchClient searchClient = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName("hotels-sample-index") @@ -41,7 +41,7 @@ public static void main(String[] args) { autoCompleteWithFilterAndFuzzy(searchClient); } - private static void autoCompleteWithOneTermContext(SearchIndexClient searchClient) { + private static void autoCompleteWithOneTermContext(SearchClient searchClient) { AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode( AutocompleteMode.ONE_TERM_WITH_CONTEXT); @@ -61,7 +61,7 @@ private static void autoCompleteWithOneTermContext(SearchIndexClient searchClien */ } - private static void autoCompleteWithHighlighting(SearchIndexClient searchClient) { + private static void autoCompleteWithHighlighting(SearchClient searchClient) { AutocompleteOptions params = new AutocompleteOptions() .setAutocompleteMode(AutocompleteMode.ONE_TERM) .setFilter("Address/City eq 'San Diego' or Address/City eq 'Hartford'") @@ -83,7 +83,7 @@ private static void autoCompleteWithHighlighting(SearchIndexClient searchClient) */ } - private static void autoCompleteWithFilterAndFuzzy(SearchIndexClient searchClient) { + private static void autoCompleteWithFilterAndFuzzy(SearchClient searchClient) { AutocompleteOptions params = new AutocompleteOptions() .setAutocompleteMode(AutocompleteMode.ONE_TERM) .setUseFuzzyMatching(true) 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 a7f69f88cbdb..7792feadc0c9 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 @@ -22,7 +22,7 @@ public class GetSingleDocumentExample { private static final String INDEX_NAME = "hotels-sample-index"; public static void main(String[] args) { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) 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 f87845c01b53..dbdc5097e956 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 @@ -40,7 +40,7 @@ public static void main(String[] args) { * With the sync client, HttpResponseExceptions are raised on failure */ private static void handleErrorsWithSyncClient() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) @@ -71,7 +71,7 @@ private static void handleErrorsWithSyncClient() { * With the async client, errors need to be handled when subscribing to the stream */ private static void handleErrorsWithAsyncClient() { - SearchIndexAsyncClient client = new SearchIndexClientBuilder() + SearchAsyncClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) 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 776db309d746..6909acc871d6 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,6 +4,8 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; import com.azure.search.documents.indexes.models.CorsOptions; import com.azure.search.documents.indexes.models.DistanceScoringFunction; import com.azure.search.documents.indexes.models.DistanceScoringParameters; @@ -46,12 +48,12 @@ public class IndexAndServiceStatisticsExample { private static final String ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); public static void main(String[] args) { - SearchServiceClient client = createClient(); + SearchIndexClient client = createClient(); getIndexStatistics(client); getServiceStatistics(client); } - private static void getServiceStatistics(SearchServiceClient client) { + private static void getServiceStatistics(SearchIndexClient client) { ServiceStatistics serviceStatistics = client.getServiceStatistics(); System.out.println(":" + serviceStatistics); @@ -101,7 +103,7 @@ private static void getServiceStatistics(SearchServiceClient client) { */ } - private static void getIndexStatistics(SearchServiceClient client) { + private static void getIndexStatistics(SearchIndexClient client) { SearchIndex testIndex = createTestIndex(); SearchIndex index = client.createOrUpdateIndex(testIndex); GetIndexStatisticsResult result = client.getIndexStatistics(index.getName()); @@ -416,13 +418,13 @@ private static SearchIndex createTestIndex() { } /** - * Builds a {@link SearchServiceClient} + * Builds a {@link SearchIndexClient} * * @return async service client */ - private static SearchServiceClient createClient() { + private static SearchIndexClient createClient() { AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential(ADMIN_KEY); - return new SearchServiceClientBuilder() + return new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(searchApiKeyCredential) .buildClient(); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexClientConfigurationExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/IndexClientConfigurationExample.java index c33f9d5ebaf1..afd856b3d502 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 @@ -8,7 +8,7 @@ import com.azure.core.util.Configuration; /** - * This example shows how to use the {@link SearchIndexClientBuilder} to create an index client + * This example shows how to use the {@link SearchClientBuilder} to create an index client *

    * This sample is based on the hotels-sample index available to install from the portal. * See instructions here](https://docs.microsoft.com/en-us/azure/search/search-get-started-portal @@ -23,17 +23,17 @@ public class IndexClientConfigurationExample { private static final String API_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_API_KEY"); public static void main(String[] args) { - SearchIndexClient minimalClient = createMinimalClient(); - SearchIndexAsyncClient advancedClient = createAdvancedClient(); + SearchClient minimalClient = createMinimalClient(); + SearchAsyncClient advancedClient = createAdvancedClient(); } /** - * Builds a {@link SearchIndexClient} with the minimum required configuration + * Builds a {@link SearchClient} with the minimum required configuration * * @return an index client with all defaults */ - private static SearchIndexClient createMinimalClient() { - return new SearchIndexClientBuilder() + private static SearchClient createMinimalClient() { + return new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName("hotels") @@ -41,12 +41,12 @@ private static SearchIndexClient createMinimalClient() { } /** - * Builds a {@link SearchIndexAsyncClient} with additional configuration + * Builds a {@link SearchAsyncClient} with additional configuration * * @return a customized async index client */ - private static SearchIndexAsyncClient createAdvancedClient() { - return new SearchIndexClientBuilder() + private static SearchAsyncClient createAdvancedClient() { + return new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName("hotels") 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 eb78cd2519c8..f8d8a9983c71 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 @@ -39,7 +39,7 @@ public static void main(String[] args) { * type directly from the index client */ private static void basicIndexing() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .indexName(INDEX_NAME) @@ -59,7 +59,7 @@ private static void basicIndexing() { * Advanced usage that includes different types of operations in a single batch */ private static void advancedIndexing() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .indexName(INDEX_NAME) diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ReadmeSamples.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ReadmeSamples.java index 25bb058a8755..0c58610ef9a7 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 @@ -8,6 +8,9 @@ import com.azure.core.http.HttpResponse; import com.azure.core.http.policy.AddHeadersFromContextPolicy; import com.azure.core.util.Context; +import com.azure.search.documents.indexes.SearchIndexAsyncClient; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; import com.azure.search.documents.models.Hotel; import com.azure.search.documents.models.RequestOptions; import com.azure.search.documents.indexes.models.SearchField; @@ -33,25 +36,25 @@ public class ReadmeSamples { private String adminKey = "admin key"; private String apiKey = "api key"; private String indexName = "index name"; - private SearchServiceClient searchServiceClient = new SearchServiceClientBuilder().buildClient(); private SearchIndexClient searchIndexClient = new SearchIndexClientBuilder().buildClient(); + private SearchClient searchClient = new SearchClientBuilder().buildClient(); public void createSearchClient() { - SearchServiceClient searchServiceClient = new SearchServiceClientBuilder() + SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(adminKey)) .buildClient(); } public void createAsyncSearchClient() { - SearchServiceAsyncClient searchServiceAsyncClient = new SearchServiceClientBuilder() + SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(adminKey)) .buildAsyncClient(); } public void createIndexClient() { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() + SearchClient searchClient = new SearchClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(apiKey)) .indexName(indexName) @@ -59,7 +62,7 @@ public void createIndexClient() { } public void createAsyncIndexClient() { - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() + SearchAsyncClient searchAsyncClient = new SearchClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(apiKey)) .indexName(indexName) @@ -73,7 +76,7 @@ public void customHeaders() { headers.put("my-header3", "my-header3-value"); // Call API by passing headers in Context. SearchIndex index = new SearchIndex().setName(indexName); - searchServiceClient.createIndexWithResponse( + searchIndexClient.createIndexWithResponse( index, new RequestOptions(), new Context(AddHeadersFromContextPolicy.AZURE_REQUEST_HTTP_HEADERS_KEY, headers)); @@ -82,7 +85,7 @@ public void customHeaders() { public void handleErrorsWithSyncClient() { try { - Iterable results = searchIndexClient.search("hotel"); + Iterable results = searchClient.search("hotel"); } catch (HttpResponseException ex) { // The exception contains the HTTP status code and the detailed message // returned from the search service @@ -104,7 +107,7 @@ public void createIndexWithSyncClient() { .setName("Cuisine") .setType(SearchFieldDataType.STRING))); // Create index. - searchServiceClient.createIndex(newIndex); + searchIndexClient.createIndex(newIndex); } public void uploadDocumentWithSyncClient() { @@ -113,12 +116,12 @@ public void uploadDocumentWithSyncClient() { hotels.add(new Hotel().setHotelId("200")); hotels.add(new Hotel().setHotelId("300")); // Upload hotel. - searchIndexClient.uploadDocuments(hotels); + searchClient.uploadDocuments(hotels); } public void searchTextWithSyncClient() { // Perform a text-based search - for (SearchResult result : searchIndexClient.search("luxury hotel", + for (SearchResult result : searchClient.search("luxury hotel", new SearchOptions(), new RequestOptions(), Context.NONE)) { // Each result is a dynamic Map 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 045ce3e7fd67..00e25815ee19 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 @@ -5,8 +5,10 @@ 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.IndexDocumentsResult; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; +import com.azure.search.documents.indexes.SearchIndexerClient; +import com.azure.search.documents.indexes.SearchIndexerClientBuilder; import com.azure.search.documents.indexes.models.InputFieldMappingEntry; import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; import com.azure.search.documents.indexes.models.SearchField; @@ -19,6 +21,8 @@ import com.azure.search.documents.indexes.models.ServiceStatistics; import com.azure.search.documents.indexes.models.SynonymMap; import com.azure.search.documents.indexes.models.WebApiSkill; +import com.azure.search.documents.models.Hotel; +import com.azure.search.documents.models.IndexDocumentsResult; import java.util.ArrayList; import java.util.Collections; @@ -43,23 +47,24 @@ public class RefineSearchCapabilitiesExample { private static final String INDEXER_NAME = "hotels-sample-indexer"; public static void main(String[] args) { - SearchServiceClient serviceClient = createServiceClient(); - SearchIndexClient indexClient = createIndexClient(); + SearchIndexClient searchIndexClient = createIndexClient(); + SearchIndexerClient searchIndexerClient = createIndexerClient(); + SearchClient indexClient = createSearchClient(); // Add a synonym map to an index field - addSynonymMapToIndex(serviceClient); + addSynonymMapToIndex(searchIndexClient); // Add a custom web based skillset to the indexer - addCustomWebSkillset(serviceClient); + addCustomWebSkillset(searchIndexerClient); // Manually add a set of documents to the index uploadDocumentsToIndex(indexClient); // Retrieve service statistics - getServiceStatistics(serviceClient); + getServiceStatistics(searchIndexClient); } - private static void addCustomWebSkillset(SearchServiceClient client) { + private static void addCustomWebSkillset(SearchIndexerClient client) { String skillsetName = "custom-web-skillset"; List inputs = Collections.singletonList( new InputFieldMappingEntry() @@ -98,7 +103,7 @@ private static void addCustomWebSkillset(SearchServiceClient client) { System.out.printf("Updated Indexer %s with Skillset %s%n", INDEXER_NAME, skillsetName); } - private static void getServiceStatistics(SearchServiceClient client) { + private static void getServiceStatistics(SearchIndexClient client) { ServiceStatistics statistics = client.getServiceStatistics(); ServiceCounters counters = statistics.getCounters(); ServiceLimits limits = statistics.getLimits(); @@ -109,7 +114,7 @@ private static void getServiceStatistics(SearchServiceClient client) { } - private static void uploadDocumentsToIndex(SearchIndexClient client) { + private static void uploadDocumentsToIndex(SearchClient client) { List hotels = new ArrayList<>(); hotels.add(new Hotel().setHotelId("100")); @@ -121,7 +126,7 @@ private static void uploadDocumentsToIndex(SearchIndexClient client) { System.out.printf("Indexed %s documents%n", result.getResults().size()); } - private static void addSynonymMapToIndex(SearchServiceClient client) { + private static void addSynonymMapToIndex(SearchIndexClient client) { String synonymMapName = "hotel-synonym-sample"; SynonymMap synonymMap = new SynonymMap() .setName(synonymMapName) @@ -138,15 +143,22 @@ private static void addSynonymMapToIndex(SearchServiceClient client) { System.out.printf("Updated index %s with synonym map %s on field %s%n", INDEX_NAME, synonymMapName, "HotelName"); } - private static SearchServiceClient createServiceClient() { - return new SearchServiceClientBuilder() + private static SearchIndexClient createIndexClient() { + return new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildClient(); } - private static SearchIndexClient createIndexClient() { - return new SearchIndexClientBuilder() + private static SearchIndexerClient createIndexerClient() { + return new SearchIndexerClientBuilder() + .endpoint(ENDPOINT) + .credential(new AzureKeyCredential(ADMIN_KEY)) + .buildClient(); + } + + private static SearchClient createSearchClient() { + return new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .indexName(INDEX_NAME) 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 fbb8b419a1b2..fe21a1cd65dd 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 @@ -7,12 +7,16 @@ 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.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.indexes.models.GetIndexStatisticsResult; import com.azure.search.documents.models.RequestOptions; -import com.azure.search.documents.indexes.models.SearchIndexerStatus; import com.azure.search.documents.models.SearchOptions; import com.azure.search.documents.models.SuggestOptions; import com.azure.search.documents.models.SuggestResult; @@ -41,18 +45,19 @@ public class RunningSearchSolutionExample { private static final String SUGGESTER_NAME = "sg"; public static void main(String[] args) { - SearchServiceClient serviceClient = createServiceClient(); - SearchIndexClient indexClient = createIndexClient(); + SearchIndexClient searchIndexClient = createIndexClient(); + SearchIndexerClient searchIndexerClient = createIndexerClient(); + SearchClient indexClient = createSearchClient(); // get index statistics - GetIndexStatisticsResult indexStatistics = serviceClient.getIndexStatistics(INDEX_NAME); + 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 - serviceClient.runIndexer(INDEXER_NAME); + searchIndexerClient.runIndexer(INDEXER_NAME); // get indexer status - SearchIndexerStatus indexerStatus = serviceClient.getIndexerStatus(INDEXER_NAME); + SearchIndexerStatus indexerStatus = searchIndexerClient.getIndexerStatus(INDEXER_NAME); System.out.printf("Indexer %s status = %s%n", INDEXER_NAME, indexerStatus.getStatus()); // run a search query @@ -66,7 +71,7 @@ public static void main(String[] args) { } - private static void suggestQuery(SearchIndexClient client) { + private static void suggestQuery(SearchClient client) { SuggestOptions suggestOptions = new SuggestOptions() .setUseFuzzyMatching(true); @@ -83,7 +88,7 @@ private static void suggestQuery(SearchIndexClient client) { ); } - private static void autocompleteQuery(SearchIndexClient client) { + private static void autocompleteQuery(SearchClient client) { AutocompleteOptions params = new AutocompleteOptions().setAutocompleteMode( AutocompleteMode.ONE_TERM_WITH_CONTEXT); @@ -95,7 +100,7 @@ private static void autocompleteQuery(SearchIndexClient client) { results.forEach(result -> System.out.println(result.getText())); } - private static void searchQuery(SearchIndexClient client) { + private static void searchQuery(SearchClient client) { // search=Resort&searchfields=HotelName&$count=true SearchOptions searchOptions = new SearchOptions() @@ -111,16 +116,23 @@ private static void searchQuery(SearchIndexClient client) { }); } + private static SearchClient createSearchClient() { + return new SearchClientBuilder() + .endpoint(ENDPOINT) + .credential(new AzureKeyCredential(ADMIN_KEY)) + .indexName(INDEX_NAME) + .buildClient(); + } + private static SearchIndexClient createIndexClient() { return new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) - .indexName(INDEX_NAME) .buildClient(); } - private static SearchServiceClient createServiceClient() { - return new SearchServiceClientBuilder() + private static SearchIndexerClient createIndexerClient() { + return new SearchIndexerClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildClient(); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchAsyncWithFullyTypedDocumentsExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SearchAsyncWithFullyTypedDocumentsExample.java index 57eda4513dba..ec4af8798e16 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 @@ -34,7 +34,7 @@ public class SearchAsyncWithFullyTypedDocumentsExample { private static final String INDEX_NAME = "hotels-sample-index"; public static void main(String[] args) { - SearchIndexAsyncClient searchClient = new SearchIndexClientBuilder() + SearchAsyncClient searchClient = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) 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 e55d6c3b5f04..2fec25e5a930 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 @@ -34,11 +34,11 @@ public static void main(String[] args) { } /** - * Minimal search with {@link SearchIndexClient} + * Minimal search with {@link SearchClient} * Search for luxury hotels print all results to the console */ private static void searchWithSyncClient() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) @@ -58,11 +58,11 @@ private static void searchWithSyncClient() { } /** - * Additional search options and results processing using {@link SearchIndexAsyncClient} + * Additional search options and results processing using {@link SearchAsyncClient} * Search for the top 5 rated luxury hotels near Redmond and print all results to the console */ private static void searchWithAsyncClient() { - SearchIndexAsyncClient client = new SearchIndexClientBuilder() + SearchAsyncClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) 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 8a8278497c89..e0ecfdd4f81c 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 @@ -36,7 +36,7 @@ public class SearchOptionsAsyncExample { private static final String INDEX_NAME = "hotels-sample-index"; public static void main(String[] args) { - SearchIndexAsyncClient searchClient = new SearchIndexClientBuilder() + SearchAsyncClient searchClient = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) @@ -52,7 +52,7 @@ public static void main(String[] args) { searchResultsFacetsFromPage(searchClient); } - private static void searchResultsFacetsFromPage(SearchIndexAsyncClient searchClient) { + private static void searchResultsFacetsFromPage(SearchAsyncClient searchClient) { // Each page in the response of the search query holds the facets value // Get Facets property from the first page in the response SearchPagedFlux results = searchClient.search("*", @@ -73,7 +73,7 @@ private static void searchResultsFacetsFromPage(SearchIndexAsyncClient searchCli }); } - private static void searchResultsFacetsFromStream(SearchIndexAsyncClient searchClient) { + private static void searchResultsFacetsFromStream(SearchAsyncClient searchClient) { // Each page in the response of the search query holds the facets value // Accessing Facets property with stream SearchPagedFlux results = searchClient.search("*", @@ -96,7 +96,7 @@ private static void searchResultsFacetsFromStream(SearchIndexAsyncClient searchC ); } - private static void searchResultsCoverageFromPage(SearchIndexAsyncClient searchClient) { + 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("*", @@ -109,7 +109,7 @@ private static void searchResultsCoverageFromPage(SearchIndexAsyncClient searchC .map(SearchPagedResponse::getCoverage).blockLast()); } - private static void searchResultsCoverage(SearchIndexAsyncClient searchClient) { + private static void searchResultsCoverage(SearchAsyncClient searchClient) { // Each page in the response of the search query holds the coverage value // Accessing Coverage property when iterating by page SearchPagedFlux results = searchClient.search("*", @@ -121,7 +121,7 @@ private static void searchResultsCoverage(SearchIndexAsyncClient searchClient) { .map(SearchPagedResponse::getCoverage).blockLast()); } - private static void searchResultsCountFromPage(SearchIndexAsyncClient searchClient) { + private static void searchResultsCountFromPage(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 @@ -134,7 +134,7 @@ private static void searchResultsCountFromPage(SearchIndexAsyncClient searchClie .map(SearchPagedResponse::getCount).blockLast()); } - private static void searchResultsCountFromStream(SearchIndexAsyncClient searchClient) { + private static void searchResultsCountFromStream(SearchAsyncClient searchClient) { // Each page in the response of the search query holds the count value // Get total search results count by accessing the SearchPagedResponse // Access Count property when iterating by page @@ -147,7 +147,7 @@ private static void searchResultsCountFromStream(SearchIndexAsyncClient searchCl } - private static void searchResultAsStreamOfPagedResponse(SearchIndexAsyncClient searchClient) { + private static void searchResultAsStreamOfPagedResponse(SearchAsyncClient searchClient) { // Converting search results to stream Stream streamResponse = searchClient.search("*") .byPage().toStream(); @@ -159,7 +159,7 @@ private static void searchResultAsStreamOfPagedResponse(SearchIndexAsyncClient s }); } - private static void searchResultsAsList(SearchIndexAsyncClient searchClient) { + private static void searchResultsAsList(SearchAsyncClient searchClient) { // Converting search results to list List searchResults = searchClient.search("*") .log() 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 2ec7c219dfe0..061c6ecb4441 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 @@ -33,7 +33,7 @@ public class SearchOptionsExample { private static final String INDEX_NAME = "hotels-sample-index"; public static void main(String[] args) { - SearchIndexClient searchClient = new SearchIndexClientBuilder() + SearchClient searchClient = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) @@ -49,7 +49,7 @@ public static void main(String[] args) { searchResultsFacets(searchClient); } - private static void searchResultsFacets(SearchIndexClient searchClient) { + private static void searchResultsFacets(SearchClient searchClient) { // Each page in the response of the search query holds the facets value // Get Facets property from the first page in the response SearchPagedIterable results = searchClient.search("*", @@ -68,7 +68,7 @@ private static void searchResultsFacets(SearchIndexClient searchClient) { ); } - private static void searchResultsFacetsFromStream(SearchIndexClient searchClient) { + private static void searchResultsFacetsFromStream(SearchClient searchClient) { // Each page in the response of the search query holds the facets value // Accessing Facets property with stream SearchPagedIterable results = searchClient.search("*", @@ -88,7 +88,7 @@ private static void searchResultsFacetsFromStream(SearchIndexClient searchClient ); } - private static void searchResultsCoverageFromStream(SearchIndexClient searchClient) { + private static void searchResultsCoverageFromStream(SearchClient searchClient) { // Each page in the response of the search query holds the coverage value // Get Coverage property from the first page in the response SearchPagedIterable results = searchClient.search("*", @@ -99,7 +99,7 @@ private static void searchResultsCoverageFromStream(SearchIndexClient searchClie ); } - private static void searchResultsCoverage(SearchIndexClient searchClient) { + private static void searchResultsCoverage(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("*", @@ -110,7 +110,7 @@ private static void searchResultsCoverage(SearchIndexClient searchClient) { ); } - private static void searchResultsCountFromPage(SearchIndexClient searchClient) { + 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 @@ -123,7 +123,7 @@ private static void searchResultsCountFromPage(SearchIndexClient searchClient) { ); } - private static void searchResultsCountFromStream(SearchIndexClient searchClient) { + private static void searchResultsCountFromStream(SearchClient searchClient) { // Each page in the response of the search query holds the count value // Get total search results count by accessing the SearchPagedResponse // Access Count property when iterating by page @@ -137,7 +137,7 @@ private static void searchResultsCountFromStream(SearchIndexClient searchClient) } - private static void searchResultAsStream(SearchIndexClient searchClient) { + private static void searchResultAsStream(SearchClient searchClient) { // Converting search results to stream SearchPagedIterable results = searchClient.search("*"); Stream resultStream = results.stream(); @@ -146,7 +146,7 @@ private static void searchResultAsStream(SearchIndexClient searchClient) { ); } - private static void searchResultsAsPagedIterable(SearchIndexClient searchClient) { + private static void searchResultsAsPagedIterable(SearchClient searchClient) { searchClient.search("*").forEach(result -> result.getDocument().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 d81a600d8eda..7b7a81ef186d 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 @@ -33,7 +33,7 @@ public class SearchSuggestionExample { private static final String INDEX_NAME = "hotels-sample-index"; public static void main(String[] args) { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_KEY)) .indexName(INDEX_NAME) @@ -43,7 +43,7 @@ public static void main(String[] args) { suggestWithFuzzySearch(client); } - private static void suggestWithHighlights(SearchIndexClient searchClient) { + private static void suggestWithHighlights(SearchClient searchClient) { SuggestOptions suggestOptions = new SuggestOptions() .setHighlightPreTag("") .setHighlightPostTag("") @@ -66,7 +66,7 @@ private static void suggestWithHighlights(SearchIndexClient searchClient) { */ } - private static void suggestWithFuzzySearch(SearchIndexClient searchClient) { + private static void suggestWithFuzzySearch(SearchClient searchClient) { SuggestOptions suggestOptions = new SuggestOptions() .setUseFuzzyMatching(true); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java index 84ca1d8ec899..3cc6616cda82 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/SynonymMapsCreateExample.java @@ -5,6 +5,8 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SearchFieldDataType; import com.azure.search.documents.indexes.models.SearchIndex; @@ -27,7 +29,7 @@ public class SynonymMapsCreateExample { private static final String API_ADMIN_KEY = Configuration.getGlobalConfiguration().get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); public static void main(String[] args) { - SearchServiceClient serviceClient = new SearchServiceClientBuilder() + SearchIndexClient serviceClient = new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(API_ADMIN_KEY)) .buildClient(); @@ -46,7 +48,7 @@ public static void main(String[] args) { serviceClient.deleteSynonymMap(synonymMapName); } - private static void createSynonymMap(SearchServiceClient serviceClient, String synonymMapName) { + private static void createSynonymMap(SearchIndexClient serviceClient, String synonymMapName) { SynonymMap synonymMap = new SynonymMap() .setName(synonymMapName) .setSynonyms("hotel, motel\ninternet,wifi\nfive star=>luxury\neconomy,inexpensive=>budget"); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateIndexExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java similarity index 94% rename from sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateIndexExample.java rename to sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java index d52299df0d36..25f58f738b9f 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateIndexExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexExample.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; @@ -23,7 +23,7 @@ public class CreateIndexExample { public static void main(String[] args) { AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential(ADMIN_KEY); - SearchServiceClient client = new SearchServiceClientBuilder() + SearchIndexClient client = new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(searchApiKeyCredential) .buildClient(); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateIndexerExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java similarity index 88% rename from sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateIndexerExample.java rename to sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java index c4d2f069c94c..aa9a79786e35 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateIndexerExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateIndexerExample.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.http.rest.Response; @@ -9,8 +9,8 @@ import com.azure.search.documents.indexes.models.FieldMapping; import com.azure.search.documents.indexes.models.IndexingParameters; import com.azure.search.documents.indexes.models.IndexingSchedule; -import com.azure.search.documents.models.RequestOptions; import com.azure.search.documents.indexes.models.SearchIndexer; +import com.azure.search.documents.models.RequestOptions; import java.time.Duration; import java.util.Collections; @@ -33,15 +33,15 @@ public class CreateIndexerExample { private static final String INDEXER_NAME = "hotels-indexer-test"; public static void main(String[] args) { - SearchServiceAsyncClient searchServiceClient = new SearchServiceClientBuilder() + SearchIndexerAsyncClient indexerAsyncClient = new SearchIndexerClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildAsyncClient(); - createOrUpdateIndexer(searchServiceClient); + createOrUpdateIndexer(indexerAsyncClient); } - private static void createOrUpdateIndexer(SearchServiceAsyncClient searchServiceClient) { + private static void createOrUpdateIndexer(SearchIndexerAsyncClient searchIndexerAsyncClient) { // Create indexer parameters IndexingParameters indexingParameters = new IndexingParameters() .setBatchSize(50) @@ -67,7 +67,7 @@ private static void createOrUpdateIndexer(SearchServiceAsyncClient searchService .setSchedule(indexingSchedule); System.out.println(String.format("Creating Indexer: %s", indexer.getName())); - Response response = searchServiceClient.createOrUpdateIndexerWithResponse( + Response response = searchIndexerAsyncClient.createOrUpdateIndexerWithResponse( indexer, false, new RequestOptions() ).block(); diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateSkillsetExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java similarity index 85% rename from sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateSkillsetExample.java rename to sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java index 539010cab3f5..6eaea18707e9 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/CreateSkillsetExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/CreateSkillsetExample.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; @@ -29,17 +29,17 @@ public class CreateSkillsetExample { private static final String CUSTOME_SKILLSET_NAME = "custom-skillset"; public static void main(String[] args) { - SearchServiceClient searchServiceClient = new SearchServiceClientBuilder() + SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildClient(); - createOcrSkillset(searchServiceClient); - createCustomSkillset(searchServiceClient); - cleanupSkillset(searchServiceClient); + createOcrSkillset(searchIndexerClient); + createCustomSkillset(searchIndexerClient); + cleanupSkillset(searchIndexerClient); } - private static void createOcrSkillset(SearchServiceClient searchServiceClient) { + private static void createOcrSkillset(SearchIndexerClient searchIndexerClient) { // Sample OCR definition // https://docs.microsoft.com/en-us/azure/search/cognitive-search-skill-ocr#sample-definition @@ -76,7 +76,7 @@ private static void createOcrSkillset(SearchServiceClient searchServiceClient) { System.out.println(String.format("Creating OCR skillset '%s'", skillset.getName())); - SearchIndexerSkillset createdSkillset = searchServiceClient.createSkillset(skillset); + SearchIndexerSkillset createdSkillset = searchIndexerClient.createSkillset(skillset); System.out.println("Created OCR skillset"); System.out.println(String.format("Name: %s", createdSkillset.getName())); @@ -85,7 +85,7 @@ private static void createOcrSkillset(SearchServiceClient searchServiceClient) { System.out.println("\n"); } - private static void createCustomSkillset(SearchServiceClient searchServiceClient) { + private static void createCustomSkillset(SearchIndexerClient searchIndexerClient) { HashMap headers = new HashMap<>(); headers.put("Ocp-Apim-Subscription-Key", "foobar"); @@ -117,15 +117,15 @@ private static void createCustomSkillset(SearchServiceClient searchServiceClient System.out.println(String.format("Creating custom skillset '%s'", skillset.getName())); - SearchIndexerSkillset createdSkillset = searchServiceClient.createSkillset(skillset); + SearchIndexerSkillset createdSkillset = searchIndexerClient.createSkillset(skillset); System.out.println("Created custom skillset"); System.out.println(String.format("Name: %s", createdSkillset.getName())); System.out.println(String.format("ETag: %s", createdSkillset.getETag())); } - private static void cleanupSkillset(SearchServiceClient searchServiceClient) { - searchServiceClient.deleteSkillset(OCR_SKILLSET_NAME); - searchServiceClient.deleteSkillset(CUSTOME_SKILLSET_NAME); + private static void cleanupSkillset(SearchIndexerClient searchIndexerClient) { + searchIndexerClient.deleteSkillset(OCR_SKILLSET_NAME); + searchIndexerClient.deleteSkillset(CUSTOME_SKILLSET_NAME); } } diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/DataSourceExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java similarity index 92% rename from sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/DataSourceExample.java rename to sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java index 2bfcbd154802..2e34c997d033 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/DataSourceExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/DataSourceExample.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.http.rest.PagedIterable; @@ -35,7 +35,7 @@ public class DataSourceExample { private static final String SQL_CONNECTION_STRING = ""; public static void main(String[] args) { - SearchServiceClient client = new SearchServiceClientBuilder() + SearchIndexerClient client = new SearchIndexerClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildClient(); @@ -70,7 +70,7 @@ public static void main(String[] args) { } } - private static void deleteDataSource(SearchServiceClient client, String dataSourceName) { + private static void deleteDataSource(SearchIndexerClient client, String dataSourceName) { try { client.deleteDataSource(dataSourceName); } catch (Exception ex) { @@ -91,7 +91,7 @@ private static SearchIndexerDataSource createSampleDatasource(SearchIndexerDataS } private static String createDataSource( - SearchServiceClient client, + SearchIndexerClient client, SearchIndexerDataSourceType type, String connectionString, SearchIndexerDataContainer container, @@ -107,7 +107,7 @@ private static String createDataSource( return dataSource.getName(); } - private static String createTableStorageDataSource(SearchServiceClient client) { + private static String createTableStorageDataSource(SearchIndexerClient client) { return createDataSource( client, SearchIndexerDataSourceType.AZURE_TABLE, @@ -119,7 +119,7 @@ private static String createTableStorageDataSource(SearchServiceClient client) { ); } - private static String createCosmosDataSource(SearchServiceClient client) { + private static String createCosmosDataSource(SearchIndexerClient client) { return createDataSource( client, SearchIndexerDataSourceType.COSMOS_DB, @@ -131,7 +131,7 @@ private static String createCosmosDataSource(SearchServiceClient client) { ); } - private static String createBlobDataSource(SearchServiceClient client) { + private static String createBlobDataSource(SearchIndexerClient client) { return createDataSource( client, SearchIndexerDataSourceType.AZURE_BLOB, @@ -143,7 +143,7 @@ private static String createBlobDataSource(SearchServiceClient client) { ); } - private static String createSqlDataSource(SearchServiceClient client) { + private static String createSqlDataSource(SearchIndexerClient client) { return createDataSource( client, SearchIndexerDataSourceType.AZURE_SQL, diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/LifecycleSetupExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java similarity index 87% rename from sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/LifecycleSetupExample.java rename to sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java index 09c5bf0ed840..1fb4baf70a75 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/LifecycleSetupExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/LifecycleSetupExample.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.util.Configuration; @@ -53,40 +53,48 @@ public class LifecycleSetupExample { private static final String SUGGESTER_NAME = "sg"; public static void main(String[] args) { - SearchServiceClient client = createServiceClient(); + SearchIndexClient indexClient = createIndexClient(); + SearchIndexerClient indexerClient = createIndexerClient(); // Create a data source for a Cosmos DB database - SearchIndexerDataSource dataSource = createCosmosDataSource(client); + SearchIndexerDataSource dataSource = createCosmosDataSource(indexerClient); System.out.println("Created DataSource " + dataSource.getName()); // Create an index - SearchIndex index = createIndex(client); + SearchIndex index = createIndex(indexClient); System.out.println("Created Index " + index.getName()); // Create a skillset for Cognitive Services - SearchIndexerSkillset skillset = createSkillset(client); + SearchIndexerSkillset skillset = createSkillset(indexerClient); System.out.println("Created Skillset " + skillset.getName()); // Create an indexer that uses the skillset and data source and loads the index - SearchIndexer indexer = createIndexer(client, dataSource, skillset, index); + SearchIndexer indexer = createIndexer(indexerClient, dataSource, skillset, index); System.out.println("Created Indexer " + indexer.getName()); // Update indexer schedule - updateIndexerSchedule(client, indexer); + updateIndexerSchedule(indexerClient, indexer); System.out.println("Updated Indexer Schedule " + indexer.getName()); // Clean up resources. - client.deleteIndex(INDEX_NAME); - client.deleteIndexer(INDEXER_NAME); + indexClient.deleteIndex(INDEX_NAME); + indexerClient.deleteIndexer(INDEXER_NAME); } - private static SearchServiceClient createServiceClient() { - return new SearchServiceClientBuilder() + private static SearchIndexClient createIndexClient() { + return new SearchIndexClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildClient(); } - private static void updateIndexerSchedule(SearchServiceClient client, SearchIndexer indexer) { + private static SearchIndexerClient createIndexerClient() { + return new SearchIndexerClientBuilder() + .endpoint(ENDPOINT) + .credential(new AzureKeyCredential(ADMIN_KEY)) + .buildClient(); + } + + private static void updateIndexerSchedule(SearchIndexerClient client, SearchIndexer indexer) { IndexingSchedule indexingSchedule = new IndexingSchedule() .setInterval(Duration.ofMinutes(10)); indexer.setSchedule(indexingSchedule); @@ -94,7 +102,7 @@ private static void updateIndexerSchedule(SearchServiceClient client, SearchInde client.createOrUpdateIndexer(indexer); } - private static SearchIndexer createIndexer(SearchServiceClient client, SearchIndexerDataSource dataSource, + private static SearchIndexer createIndexer(SearchIndexerClient client, SearchIndexerDataSource dataSource, SearchIndexerSkillset skillset, SearchIndex index) { SearchIndexer indexer = new SearchIndexer() .setName(INDEXER_NAME) @@ -105,7 +113,7 @@ private static SearchIndexer createIndexer(SearchServiceClient client, SearchInd return client.createOrUpdateIndexer(indexer); } - private static SearchIndexerSkillset createSkillset(SearchServiceClient client) { + private static SearchIndexerSkillset createSkillset(SearchIndexerClient client) { List inputs = Collections.singletonList( new InputFieldMappingEntry() .setName("text") @@ -135,7 +143,7 @@ private static SearchIndexerSkillset createSkillset(SearchServiceClient client) return client.createOrUpdateSkillset(skillset); } - private static SearchIndex createIndex(SearchServiceClient client) { + private static SearchIndex createIndex(SearchIndexClient client) { // Index definition SearchIndex index = new SearchIndex() @@ -186,7 +194,7 @@ private static SearchIndex createIndex(SearchServiceClient client) { return client.createOrUpdateIndex(index); } - private static SearchIndexerDataSource createCosmosDataSource(SearchServiceClient client) { + private static SearchIndexerDataSource createCosmosDataSource(SearchIndexerClient client) { SearchIndexerDataContainer dataContainer = new SearchIndexerDataContainer().setName(COSMOS_COLLECTION_NAME); HighWaterMarkChangeDetectionPolicy highWaterMarkChangeDetectionPolicy = diff --git a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ListIndexersExample.java b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java similarity index 82% rename from sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ListIndexersExample.java rename to sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java index f68ce3de5281..6553f3b2f7f9 100644 --- a/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/ListIndexersExample.java +++ b/sdk/search/azure-search-documents/src/samples/java/com/azure/search/documents/indexes/ListIndexersExample.java @@ -1,13 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +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.models.RequestOptions; import com.azure.search.documents.indexes.models.SearchIndexer; +import com.azure.search.documents.models.RequestOptions; import java.util.List; @@ -26,16 +26,16 @@ public class ListIndexersExample { .get("AZURE_COGNITIVE_SEARCH_ADMIN_KEY"); public static void main(String[] args) { - SearchServiceAsyncClient searchServiceClient = new SearchServiceClientBuilder() + SearchIndexerAsyncClient indexerAsyncClient = new SearchIndexerClientBuilder() .endpoint(ENDPOINT) .credential(new AzureKeyCredential(ADMIN_KEY)) .buildAsyncClient(); - listIndexers(searchServiceClient); + listIndexers(indexerAsyncClient); } - private static void listIndexers(SearchServiceAsyncClient searchServiceClient) { - PagedResponse response = searchServiceClient.listIndexers("*", + private static void listIndexers(SearchIndexerAsyncClient indexerAsyncClient) { + PagedResponse response = indexerAsyncClient.listIndexers("*", new RequestOptions()).byPage().blockFirst(); if (response != null) { diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteSyncTests.java index 24025d0a5f93..80b7bbae71ad 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/AutocompleteSyncTests.java @@ -25,7 +25,7 @@ public class AutocompleteSyncTests extends SearchTestBase { private static final String HOTELS_DATA_JSON = "HotelsDataArray.json"; - private SearchIndexClient client; + private SearchClient client; @Override protected void beforeTest() { @@ -37,7 +37,7 @@ protected void beforeTest() { @Override protected void afterTest() { - getSearchServiceClientBuilder().buildClient().deleteIndex(client.getIndexName()); + getSearchIndexClientBuilder().buildClient().deleteIndex(client.getIndexName()); } @Test diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingSyncTests.java index 244a5663b3ed..d05c6d5ff919 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexingSyncTests.java @@ -4,6 +4,7 @@ import com.azure.core.http.rest.Response; import com.azure.core.util.Context; +import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.models.GeoPoint; import com.azure.search.documents.models.IndexBatchException; import com.azure.search.documents.indexes.models.IndexDocumentsBatch; @@ -53,19 +54,19 @@ public class IndexingSyncTests extends SearchTestBase { private static final String BOOKS_INDEX_JSON = "BooksIndexData.json"; private final List indexesToDelete = new ArrayList<>(); - private SearchIndexClient client; + private SearchClient client; @Override protected void afterTest() { super.afterTest(); - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); for (String index : indexesToDelete) { serviceClient.deleteIndex(index); } } - private SearchIndexClient setupClient(Supplier indexSupplier) { + private SearchClient setupClient(Supplier indexSupplier) { String indexName = indexSupplier.get(); indexesToDelete.add(indexName); @@ -296,8 +297,8 @@ public void canUseIndexWithReservedName() { .setKey(Boolean.TRUE) )); - SearchServiceClient searchServiceClient = getSearchServiceClientBuilder().buildClient(); - searchServiceClient.createOrUpdateIndex(indexWithReservedName); + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder().buildClient(); + searchIndexClient.createOrUpdateIndex(indexWithReservedName); indexesToDelete.add(indexWithReservedName.getName()); client = getSearchIndexClientBuilder(indexName).buildClient(); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupSyncTests.java index 36d0ceaa04c4..c3cca8f51c54 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/LookupSyncTests.java @@ -4,6 +4,7 @@ import com.azure.core.http.rest.Response; import com.azure.core.util.Context; +import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.models.GeoPoint; import com.azure.search.documents.indexes.models.IndexDocumentsBatch; import com.azure.search.documents.indexes.models.SearchField; @@ -37,19 +38,19 @@ public class LookupSyncTests extends SearchTestBase { private final List indexesToDelete = new ArrayList<>(); - private SearchIndexClient client; + private SearchClient client; @Override protected void afterTest() { super.afterTest(); - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); for (String index : indexesToDelete) { serviceClient.deleteIndex(index); } } - private SearchIndexClient setupClient(Supplier indexSupplier) { + private SearchClient setupClient(Supplier indexSupplier) { String indexName = indexSupplier.get(); indexesToDelete.add(indexName); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexAsyncClientImplTest.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAsyncClientImplTest.java similarity index 97% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexAsyncClientImplTest.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAsyncClientImplTest.java index 18671909b39f..5a1ee2de1c3a 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexAsyncClientImplTest.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchAsyncClientImplTest.java @@ -28,8 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; -public class SearchIndexAsyncClientImplTest extends SearchTestBase { - private SearchIndexAsyncClient asyncClient; +public class SearchAsyncClientImplTest extends SearchTestBase { + private SearchAsyncClient asyncClient; @Override protected void beforeTest() { @@ -41,7 +41,7 @@ protected void beforeTest() { protected void afterTest() { super.afterTest(); - getSearchServiceClientBuilder().buildClient().deleteIndex(asyncClient.getIndexName()); + getSearchIndexClientBuilder().buildClient().deleteIndex(asyncClient.getIndexName()); } @Test diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexClientBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchClientBuilderTests.java similarity index 74% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexClientBuilderTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchClientBuilderTests.java index a521b7d8baf6..e5a48d063272 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchIndexClientBuilderTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchClientBuilderTests.java @@ -4,18 +4,19 @@ package com.azure.search.documents; import com.azure.core.credential.AzureKeyCredential; +import com.azure.search.documents.indexes.SearchIndexClientBuilderTests; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; import java.net.MalformedURLException; import java.security.SecureRandom; -import static com.azure.search.documents.SearchServiceClientBuilderTests.request; +import static com.azure.search.documents.indexes.SearchIndexClientBuilderTests.request; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -public class SearchIndexClientBuilderTests { +public class SearchClientBuilderTests { private final AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential("0123"); private final String searchEndpoint = "https://test.search.windows.net"; private final String indexName = "myindex"; @@ -23,7 +24,7 @@ public class SearchIndexClientBuilderTests { @Test public void buildSyncClientTest() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -31,24 +32,24 @@ public void buildSyncClientTest() { .buildClient(); assertNotNull(client); - assertEquals(SearchIndexClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void buildSyncClientUsingDefaultApiVersionTest() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) .buildClient(); assertNotNull(client); - assertEquals(SearchIndexClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void buildAsyncClientTest() { - SearchIndexAsyncClient client = new SearchIndexClientBuilder() + SearchAsyncClient client = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -56,35 +57,35 @@ public void buildAsyncClientTest() { .buildAsyncClient(); assertNotNull(client); - assertEquals(SearchIndexAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void buildAsyncClientUsingDefaultApiVersionTest() { - SearchIndexAsyncClient client = new SearchIndexClientBuilder() + SearchAsyncClient client = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) .buildAsyncClient(); assertNotNull(client); - assertEquals(SearchIndexAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void whenApiVersionSpecifiedThenSpecifiedValueExists() { SearchServiceVersion expectedVersion = SearchServiceVersion.V2019_05_06_Preview; - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() + SearchClient searchClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) .serviceVersion(expectedVersion) .buildClient(); - assertEquals(expectedVersion, searchIndexClient.getServiceVersion()); + assertEquals(expectedVersion, searchClient.getServiceVersion()); - SearchIndexAsyncClient asyncClient = new SearchIndexClientBuilder() + SearchAsyncClient asyncClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -95,7 +96,7 @@ public void whenApiVersionSpecifiedThenSpecifiedValueExists() { @Test public void whenBuildAsyncClientUsingDefaultApiVersionThenSuccess() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -103,7 +104,7 @@ public void whenBuildAsyncClientUsingDefaultApiVersionThenSuccess() { assertEquals(apiVersion, client.getServiceVersion()); - SearchIndexAsyncClient asyncClient = new SearchIndexClientBuilder() + SearchAsyncClient asyncClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -114,7 +115,7 @@ public void whenBuildAsyncClientUsingDefaultApiVersionThenSuccess() { @Test public void whenBuildClientAndVerifyPropertiesThenSuccess() { - SearchIndexClient client = new SearchIndexClientBuilder() + SearchClient client = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -124,7 +125,7 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { assertEquals(indexName, client.getIndexName()); assertEquals(apiVersion, client.getServiceVersion()); - SearchIndexAsyncClient asyncClient = new SearchIndexClientBuilder() + SearchAsyncClient asyncClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -137,33 +138,33 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { @Test public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder().endpoint("")); + assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder().endpoint("")); } @Test public void nullIndexNameThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder().indexName(null)); + assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder().indexName(null)); } @Test public void emptyIndexNameThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder().indexName("")); + assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder().indexName("")); } @Test public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new SearchIndexClientBuilder().credential(null)); + assertThrows(NullPointerException.class, () -> new SearchClientBuilder().credential(null)); } @Test public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder() + assertThrows(IllegalArgumentException.class, () -> new SearchClientBuilder() .credential(new AzureKeyCredential(""))); } @Test public void nullApiVersionUsesLatest() { - SearchIndexClientBuilder builder = new SearchIndexClientBuilder() + SearchClientBuilder builder = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName(indexName) @@ -175,41 +176,41 @@ public void nullApiVersionUsesLatest() { @Test public void verifyNewBuilderSetsLatestVersion() { - SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() + SearchClient searchClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName("indexName") .buildClient(); assertEquals(SearchServiceVersion.getLatest().getVersion(), - searchIndexClient.getServiceVersion().getVersion()); + searchClient.getServiceVersion().getVersion()); } @Test public void verifyNewBuilderSetsLatestVersionAsync() { - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() + SearchAsyncClient searchAsyncClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName("indexName") .buildAsyncClient(); assertEquals(SearchServiceVersion.getLatest().getVersion(), - searchIndexAsyncClient.getServiceVersion().getVersion()); + searchAsyncClient.getServiceVersion().getVersion()); } @Test public void indexClientFreshDateOnRetry() throws MalformedURLException { byte[] randomData = new byte[256]; new SecureRandom().nextBytes(randomData); - SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() + SearchAsyncClient searchAsyncClient = new SearchClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .indexName("test_builder") - .httpClient(new SearchServiceClientBuilderTests.FreshDateTestClient()) + .httpClient(new SearchIndexClientBuilderTests.FreshDateTestClient()) .buildAsyncClient(); - StepVerifier.create(searchIndexAsyncClient.getHttpPipeline().send( - request(searchIndexAsyncClient.getEndpoint()))) + StepVerifier.create(searchAsyncClient.getHttpPipeline().send( + request(searchAsyncClient.getEndpoint()))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } 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 c5cb30f2a845..6e4846dcac37 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 @@ -5,6 +5,10 @@ import com.azure.core.credential.AzureKeyCredential; import com.azure.core.http.HttpPipeline; import com.azure.core.test.TestBase; +import com.azure.search.documents.indexes.IndexesTestHelpers; +import com.azure.search.documents.indexes.SearchIndexAsyncClient; +import com.azure.search.documents.indexes.SearchIndexClient; +import com.azure.search.documents.indexes.SearchIndexClientBuilder; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -12,56 +16,55 @@ public class SearchServiceSubClientTests extends TestBase { - @Test public void canGetIndexClientFromSearchClient() { - SearchServiceClient serviceClient = getSearchService(); + SearchIndexClient serviceClient = getSearchIndexClient(); - SearchIndexClient indexClient = serviceClient.getIndexClient("hotels"); + SearchClient searchClient = serviceClient.getSearchClient("hotels"); // Validate the client was created - assertNotNull(indexClient); + assertNotNull(searchClient); // Validate the client points to the same instance - assertEquals(serviceClient.getEndpoint(), indexClient.getEndpoint()); - assertEquals(serviceClient.getServiceVersion(), indexClient.getServiceVersion()); + assertEquals(serviceClient.getEndpoint(), searchClient.getEndpoint()); + assertEquals(serviceClient.getServiceVersion(), searchClient.getServiceVersion()); // Validate that the client uses the same HTTP pipeline for authentication, retries, etc - HttpPipeline servicePipeline = serviceClient.getHttpPipeline(); - HttpPipeline indexPipeline = indexClient.getHttpPipeline(); + HttpPipeline servicePipeline = IndexesTestHelpers.getHttpPipeline(serviceClient); + HttpPipeline searchPipeline = TestHelpers.getHttpPipeline(searchClient); - assertEquals(servicePipeline, indexPipeline); + assertEquals(servicePipeline, searchPipeline); // Validate that the client uses the specified index - assertEquals("hotels", indexClient.getIndexName()); + assertEquals("hotels", searchClient.getIndexName()); } @Test public void canGetIndexAsyncClientFromSearchClient() { - SearchServiceAsyncClient serviceClient = getAsyncSearchService(); + SearchIndexAsyncClient indexAsyncClient = getSearchIndexAsyncClient(); - SearchIndexAsyncClient indexClient = serviceClient.getIndexClient("hotels"); + SearchAsyncClient searchAsyncClient = indexAsyncClient.getSearchAsyncClient("hotels"); // Validate the client was created - assertNotNull(indexClient); + assertNotNull(searchAsyncClient); // Validate the client points to the same instance - assertEquals(serviceClient.getEndpoint(), indexClient.getEndpoint()); - assertEquals(serviceClient.getServiceVersion(), indexClient.getServiceVersion()); + assertEquals(indexAsyncClient.getEndpoint(), searchAsyncClient.getEndpoint()); + assertEquals(indexAsyncClient.getServiceVersion(), searchAsyncClient.getServiceVersion()); // Validate that the client uses the same HTTP pipeline for authentication, retries, etc - HttpPipeline servicePipeline = serviceClient.getHttpPipeline(); - HttpPipeline indexPipeline = indexClient.getHttpPipeline(); + HttpPipeline servicePipeline = IndexesTestHelpers.getHttpPipeline(indexAsyncClient); + HttpPipeline searchPipeline = TestHelpers.getHttpPipeline(searchAsyncClient); - assertEquals(servicePipeline, indexPipeline); + assertEquals(servicePipeline, searchPipeline); // Validate that the client uses the specified index - assertEquals("hotels", indexClient.getIndexName()); + assertEquals("hotels", searchAsyncClient.getIndexName()); } @Test public void canGetIndexClientAfterUsingServiceClient() { - SearchServiceClient serviceClient = getSearchService(); + SearchIndexClient serviceClient = getSearchIndexClient(); try { // this is expected to fail serviceClient.deleteIndex("thisindexdoesnotexist"); @@ -70,13 +73,13 @@ public void canGetIndexClientAfterUsingServiceClient() { } // This should not fail - SearchIndexClient indexClient = serviceClient.getIndexClient("hotels"); + SearchClient indexClient = serviceClient.getSearchClient("hotels"); assertEquals("hotels", indexClient.getIndexName()); } @Test public void canGetIndexAsyncClientAfterUsingServiceClient() { - SearchServiceAsyncClient serviceClient = getAsyncSearchService(); + SearchIndexAsyncClient serviceClient = getSearchIndexAsyncClient(); try { // this is expected to fail serviceClient.deleteIndex("thisindexdoesnotexist"); @@ -85,19 +88,19 @@ public void canGetIndexAsyncClientAfterUsingServiceClient() { } // This should not fail - SearchIndexAsyncClient indexClient = serviceClient.getIndexClient("hotels"); + SearchAsyncClient indexClient = serviceClient.getSearchAsyncClient("hotels"); assertEquals("hotels", indexClient.getIndexName()); } - private SearchServiceClient getSearchService() { - return new SearchServiceClientBuilder() + private SearchIndexClient getSearchIndexClient() { + return new SearchIndexClientBuilder() .endpoint("https://test1.search.windows.net") .credential(new AzureKeyCredential("api-key")) .buildClient(); } - private SearchServiceAsyncClient getAsyncSearchService() { - return new SearchServiceClientBuilder() + private SearchIndexAsyncClient getSearchIndexAsyncClient() { + return new SearchIndexClientBuilder() .endpoint("https://test1.search.windows.net") .credential(new AzureKeyCredential("api-key")) .buildAsyncClient(); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchSyncTests.java index 9359114040aa..6685ab0a53c0 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchSyncTests.java @@ -5,6 +5,7 @@ import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.models.CoordinateSystem; import com.azure.search.documents.models.FacetResult; import com.azure.search.documents.models.GeoPoint; @@ -66,13 +67,13 @@ public class SearchSyncTests extends SearchTestBase { private final List indexesToDelete = new ArrayList<>(); private String synonymMapToDelete = ""; - private SearchIndexClient client; + private SearchClient client; @Override protected void afterTest() { super.afterTest(); - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); for (String index : indexesToDelete) { serviceClient.deleteIndex(index); } @@ -83,7 +84,7 @@ protected void afterTest() { } } - private SearchIndexClient setupClient(Supplier indexSupplier) { + private SearchClient setupClient(Supplier indexSupplier) { String indexName = indexSupplier.get(); indexesToDelete.add(indexName); @@ -751,21 +752,21 @@ public void canSearchWithSynonyms() { uploadDocumentsJson(client, HOTELS_DATA_JSON); String fieldName = "HotelName"; - SearchServiceClient searchServiceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient searchIndexClient = getSearchIndexClientBuilder().buildClient(); // Create a new SynonymMap - synonymMapToDelete = searchServiceClient.createSynonymMap(new SynonymMap() + synonymMapToDelete = searchIndexClient.createSynonymMap(new SynonymMap() .setName(testResourceNamer.randomName("names", 32)) .setSynonyms("luxury,fancy")).getName(); // Attach index field to SynonymMap - SearchIndex hotelsIndex = searchServiceClient.getIndex(client.getIndexName()); + SearchIndex hotelsIndex = searchIndexClient.getIndex(client.getIndexName()); hotelsIndex.getFields().stream() .filter(f -> fieldName.equals(f.getName())) .findFirst().get().setSynonymMaps(Collections.singletonList(synonymMapToDelete)); // Update the index with the SynonymMap - searchServiceClient.createOrUpdateIndex(hotelsIndex); + searchIndexClient.createOrUpdateIndex(hotelsIndex); sleepIfRunningAgainstService(10000); 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 4df2cfdb78ee..96c67ab3028d 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 @@ -9,6 +9,9 @@ import com.azure.core.http.policy.RetryPolicy; import com.azure.core.test.TestBase; import com.azure.core.util.Configuration; +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; @@ -90,13 +93,13 @@ protected String setupIndexFromJsonFile(String jsonFile) { protected String setupIndex(SearchIndex index) { index.setName(testResourceNamer.randomName(index.getName(), 64)); - getSearchServiceClientBuilder().buildClient().createOrUpdateIndex(index); + getSearchIndexClientBuilder().buildClient().createOrUpdateIndex(index); return index.getName(); } - protected SearchServiceClientBuilder getSearchServiceClientBuilder(HttpPipelinePolicy... policies) { - SearchServiceClientBuilder builder = new SearchServiceClientBuilder() + protected SearchIndexClientBuilder getSearchIndexClientBuilder(HttpPipelinePolicy... policies) { + SearchIndexClientBuilder builder = new SearchIndexClientBuilder() .endpoint(ENDPOINT); if (interceptorManager.isPlaybackMode()) { @@ -117,7 +120,29 @@ protected SearchServiceClientBuilder getSearchServiceClientBuilder(HttpPipelineP } - private static void addPolicies(SearchServiceClientBuilder builder, HttpPipelinePolicy... policies) { + protected SearchIndexerClientBuilder getSearchIndexerClientBuilder(HttpPipelinePolicy... policies) { + SearchIndexerClientBuilder builder = new SearchIndexerClientBuilder() + .endpoint(ENDPOINT); + + if (interceptorManager.isPlaybackMode()) { + builder.httpClient(interceptorManager.getPlaybackClient()); + addPolicies(builder, policies); + return builder; + } + + addPolicies(builder, policies); + builder.credential(new AzureKeyCredential(API_KEY)) + .retryPolicy(new RetryPolicy(new ExponentialBackoff(3, Duration.ofSeconds(10), Duration.ofSeconds(30)))); + + if (!interceptorManager.isLiveMode()) { + builder.addPolicy(interceptorManager.getRecordPolicy()); + } + + return builder; + + } + + private static void addPolicies(SearchIndexClientBuilder builder, HttpPipelinePolicy... policies) { if (policies == null) { return; } @@ -127,8 +152,18 @@ private static void addPolicies(SearchServiceClientBuilder builder, HttpPipeline } } - protected SearchIndexClientBuilder getSearchIndexClientBuilder(String indexName) { - SearchIndexClientBuilder builder = new SearchIndexClientBuilder() + private static void addPolicies(SearchIndexerClientBuilder builder, HttpPipelinePolicy... policies) { + if (policies == null) { + return; + } + + for (HttpPipelinePolicy policy : policies) { + builder.addPolicy(policy); + } + } + + protected SearchClientBuilder getSearchIndexClientBuilder(String indexName) { + SearchClientBuilder builder = new SearchClientBuilder() .endpoint(ENDPOINT) .indexName(indexName); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestSyncTests.java index 3006d8c0e452..cceb5cda313b 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SuggestSyncTests.java @@ -5,6 +5,7 @@ import com.azure.core.http.rest.PagedIterableBase; import com.azure.core.http.rest.PagedResponse; import com.azure.core.util.Context; +import com.azure.search.documents.indexes.SearchIndexClient; import com.azure.search.documents.models.SuggestOptions; import com.azure.search.documents.models.SuggestResult; import com.azure.search.documents.test.environment.models.Author; @@ -45,19 +46,19 @@ public class SuggestSyncTests extends SearchTestBase { private final List indexesToDelete = new ArrayList<>(); - private SearchIndexClient client; + private SearchClient client; @Override protected void afterTest() { super.afterTest(); - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); for (String index : indexesToDelete) { serviceClient.deleteIndex(index); } } - private SearchIndexClient setupClient(Supplier indexSupplier) { + private SearchClient setupClient(Supplier indexSupplier) { String indexName = indexSupplier.get(); indexesToDelete.add(indexName); 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 941f4592f359..468fa9f8bc13 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 @@ -4,6 +4,7 @@ package com.azure.search.documents; import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpPipeline; import com.azure.core.test.TestMode; import com.azure.core.util.Configuration; import com.azure.core.util.serializer.JacksonAdapter; @@ -214,33 +215,41 @@ public static T convertToType(Object document, Class cls) { 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 void uploadDocuments(SearchIndexClient client, List uploadDoc) { + public static void uploadDocuments(SearchClient client, List uploadDoc) { client.uploadDocuments(uploadDoc); waitForIndexing(); } - public static void uploadDocuments(SearchIndexAsyncClient client, List uploadDoc) { + public static void uploadDocuments(SearchAsyncClient client, List uploadDoc) { client.uploadDocuments(uploadDoc).block(); waitForIndexing(); } - public static void uploadDocument(SearchIndexClient client, T uploadDoc) { + public static void uploadDocument(SearchClient client, T uploadDoc) { client.uploadDocuments(Collections.singletonList(uploadDoc)); waitForIndexing(); } - public static void uploadDocument(SearchIndexAsyncClient client, T uploadDoc) { + public static void uploadDocument(SearchAsyncClient client, T uploadDoc) { client.uploadDocuments(Collections.singletonList(uploadDoc)).block(); waitForIndexing(); } - public static List> uploadDocumentsJson(SearchIndexClient client, String dataJson) { + public static List> uploadDocumentsJson(SearchClient client, String dataJson) { List> documents = readJsonFileToList(dataJson); uploadDocuments(client, documents); return documents; } + public static HttpPipeline getHttpPipeline(SearchClient searchClient) { + return searchClient.getHttpPipeline(); + } + + public static HttpPipeline getHttpPipeline(SearchAsyncClient searchAsyncClient) { + return searchAsyncClient.getHttpPipeline(); + } + private static List> readJsonFileToList(String filename) { Reader reader = new InputStreamReader(Objects.requireNonNull(TestHelpers.class.getClassLoader() .getResourceAsStream(filename))); diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/CustomAnalyzerSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/CustomAnalyzerSyncTests.java similarity index 93% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/CustomAnalyzerSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/CustomAnalyzerSyncTests.java index 04ab90bdcc38..2a46ef441096 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/CustomAnalyzerSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/CustomAnalyzerSyncTests.java @@ -1,9 +1,12 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; +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.AnalyzeRequest; import com.azure.search.documents.indexes.models.AnalyzedTokenInfo; import com.azure.search.documents.indexes.models.AsciiFoldingTokenFilter; @@ -94,20 +97,20 @@ public class CustomAnalyzerSyncTests extends SearchTestBase { private static final String NAME_PREFIX = "azsmnet"; private static final Collection CHAR_FILTER_NAMES = new ArrayList<>(CharFilterName.values()); - private SearchServiceClient searchServiceClient; + private SearchIndexClient searchIndexClient; private final List indexesToCleanup = new ArrayList<>(); @Override protected void beforeTest() { super.beforeTest(); - searchServiceClient = getSearchServiceClientBuilder().buildClient(); + searchIndexClient = getSearchIndexClientBuilder().buildClient(); } @Override protected void afterTest() { super.afterTest(); for (String index : indexesToCleanup) { - searchServiceClient.deleteIndex(index); + searchIndexClient.deleteIndex(index); } } @@ -142,9 +145,9 @@ public void canSearchWithCustomAnalyzer() { .setName(customCharFilterName.toString()) )); - searchServiceClient.createIndex(index); + searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); - SearchIndexClient searchIndexClient = searchServiceClient.getIndexClient(index.getName()); + SearchClient searchClient = searchIndexClient.getSearchClient(index.getName()); SearchDocument document1 = new SearchDocument(); document1.put("id", "1"); @@ -154,10 +157,10 @@ public void canSearchWithCustomAnalyzer() { document2.put("message", "His email is someone@nowhere.nothing."); List documents = Arrays.asList(document1, document2); - searchIndexClient.uploadDocuments(documents); + searchClient.uploadDocuments(documents); waitForIndexing(); - Iterator iterator = searchIndexClient + Iterator iterator = searchClient .search("someone@somewhere.something", new SearchOptions(), generateRequestOptions(), Context.NONE) .iterator(); SearchResult searchResult = iterator.next(); @@ -170,7 +173,7 @@ public void canSearchWithCustomAnalyzer() { public void canUseAllAnalyzerNamesInIndexDefinition() { SearchIndex index = prepareIndexWithAllLexicalAnalyzerNames(); indexesToCleanup.add(index.getName()); - SearchIndex res = searchServiceClient.createIndex(index); + SearchIndex res = searchIndexClient.createIndex(index); assertObjectEquals(index, res, true, "etag"); @@ -198,13 +201,13 @@ public void canUseAllAnalyzerNamesInIndexDefinition() { @Test public void canAnalyze() { SearchIndex index = createTestIndex(); - searchServiceClient.createIndex(index); + searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); AnalyzeRequest request = new AnalyzeRequest() .setText("One two") .setAnalyzer(LexicalAnalyzerName.WHITESPACE); - PagedIterable results = searchServiceClient.analyzeText(index.getName(), request); + 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()); @@ -215,13 +218,13 @@ public void canAnalyze() { .setTokenizer(LexicalTokenizerName.WHITESPACE) .setTokenFilters(Collections.singletonList(TokenFilterName.APOSTROPHE)) .setCharFilters(Collections.singletonList(CharFilterName.HTML_STRIP)); - results = searchServiceClient.analyzeText(index.getName(), request); + 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()); - results = searchServiceClient.analyzeText(index.getName(), request, generateRequestOptions(), Context.NONE); + results = searchIndexClient.analyzeText(index.getName(), request, generateRequestOptions(), Context.NONE); // 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()); @@ -231,7 +234,7 @@ public void canAnalyze() { @Test public void canAnalyzeWithAllPossibleNames() { SearchIndex index = createTestIndex(); - searchServiceClient.createIndex(index); + searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); LexicalAnalyzerName.values() @@ -239,34 +242,34 @@ public void canAnalyzeWithAllPossibleNames() { .map(an -> new AnalyzeRequest() .setText("One two") .setAnalyzer(an)) - .forEach(r -> searchServiceClient.analyzeText(index.getName(), r)); + .forEach(r -> searchIndexClient.analyzeText(index.getName(), r)); LexicalTokenizerName.values() .stream() .map(tn -> new AnalyzeRequest() .setText("One two") .setTokenizer(tn)) - .forEach(r -> searchServiceClient.analyzeText(index.getName(), r)); + .forEach(r -> searchIndexClient.analyzeText(index.getName(), r)); AnalyzeRequest request = new AnalyzeRequest() .setText("One two") .setTokenizer(LexicalTokenizerName.WHITESPACE) .setTokenFilters(new ArrayList<>(TokenFilterName.values())) .setCharFilters(new ArrayList<>(CharFilterName.values())); - searchServiceClient.analyzeText(index.getName(), request); + searchIndexClient.analyzeText(index.getName(), request); } @Test public void addingCustomAnalyzerThrowsHttpExceptionByDefault() { SearchIndex index = createTestIndex() .setAnalyzers(Collections.singletonList(new StopAnalyzer().setName("a1"))); - searchServiceClient.createIndex(index); + searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); addAnalyzerToIndex(index, new StopAnalyzer().setName("a2")); assertHttpResponseException( - () -> searchServiceClient.createOrUpdateIndex(index), + () -> searchIndexClient.createOrUpdateIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "Index update not allowed because it would cause downtime." ); @@ -276,11 +279,11 @@ public void addingCustomAnalyzerThrowsHttpExceptionByDefault() { public void canAddCustomAnalyzerWithIndexDowntime() { SearchIndex index = createTestIndex() .setAnalyzers(Collections.singletonList(new StopAnalyzer().setName("a1"))); - searchServiceClient.createIndex(index); + searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); addAnalyzerToIndex(index, new StopAnalyzer().setName("a2")); - SearchIndex updatedIndex = searchServiceClient.createOrUpdateIndexWithResponse(index, + SearchIndex updatedIndex = searchIndexClient.createOrUpdateIndexWithResponse(index, true, false, generateRequestOptions(), Context.NONE).getValue(); assertAnalysisComponentsEqual(index, updatedIndex); @@ -290,10 +293,10 @@ public void canAddCustomAnalyzerWithIndexDowntime() { public void canCreateAllAnalysisComponents() { SearchIndex index = prepareIndexWithAllAnalysisComponentTypes(); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); - searchServiceClient.deleteIndex(index.getName()); + searchIndexClient.deleteIndex(index.getName()); // We have to split up analysis components into two indexes, one where any components with optional properties // have defaults that are zero or null, and another where we need to specify the default values we @@ -306,9 +309,9 @@ public void canCreateAllAnalysisComponents() { List splittedExpectedIndexWithSpecialDefaults = splitIndex(expectedIndexWithSpecialDefaults); for (int j = 0; j < splittedIndexWithSpecialDefaults.size(); j++) { SearchIndex expected = splittedExpectedIndexWithSpecialDefaults.get(j); - SearchIndex actual = searchServiceClient.createIndex(expected); + SearchIndex actual = searchIndexClient.createIndex(expected); assertAnalysisComponentsEqual(expected, actual); - searchServiceClient.deleteIndex(actual.getName()); + searchIndexClient.deleteIndex(actual.getName()); } } @@ -316,7 +319,7 @@ public void canCreateAllAnalysisComponents() { public void canUseAllAnalysisComponentNames() { SearchIndex index = prepareIndexWithAllAnalysisComponentNames(); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertCustomAnalysisComponentsEqual(index, createdIndex); } @@ -331,7 +334,7 @@ public void canUseAllRegexFlagsAnalyzer() { .setFlags(new ArrayList<>(RegexFlags.values())) .setName(generateName()))); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -342,7 +345,7 @@ public void canUseAllRegexFlagsNullAnalyzer() { SearchIndex index = createTestIndex() .setAnalyzers(null); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -353,7 +356,7 @@ public void canUseAllRegexFlagsEmptyAnalyzer() { SearchIndex index = createTestIndex() .setAnalyzers(new ArrayList<>()); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -367,7 +370,7 @@ public void canUseAllRegexFlagsNullNameAnalyzer() { )); assertHttpResponseException( - () -> searchServiceClient.createIndex(index), + () -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "The name field is required." ); @@ -381,7 +384,7 @@ public void canUseAllRegexFlagsEmptyNameAnalyzer() { )); assertHttpResponseException( - () -> searchServiceClient.createIndex(index), + () -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "The name field is required." ); @@ -394,7 +397,7 @@ public void canUseAllRegexFlagsNullLowerCaseAnalyzer() { new PatternAnalyzer().setLowerCaseTerms(null).setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -407,7 +410,7 @@ public void canUseAllRegexFlagsNullPatternAnalyzer() { new PatternAnalyzer().setPattern(null).setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -420,7 +423,7 @@ public void canUseAllRegexFlagsEmptyPatternAnalyzer() { new PatternAnalyzer().setPattern("").setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -433,7 +436,7 @@ public void canUseAllRegexFlagsNullFlagsAnalyzer() { new PatternAnalyzer().setFlags(null).setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -447,7 +450,7 @@ public void canUseAllRegexFlagsEmptyFlagsAnalyzer() { )); assertHttpResponseException( - () -> searchServiceClient.createIndex(index), + () -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "Values of property \\\"flags\\\" must belong to the set of allowed values" ); @@ -460,7 +463,7 @@ public void canUseAllRegexFlagsNullStopwordsAnalyzer() { .setStopwords(null) .setName(generateName()))); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -473,7 +476,7 @@ public void canUseAllRegexFlagsEmptyStopwordsAnalyzer() { .setStopwords(new ArrayList<>()) .setName(generateName()))); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -488,7 +491,7 @@ public void canUseAllRegexFlagsTokenizer() { .setGroup(0) .setName(generateName()))); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -499,7 +502,7 @@ public void canUseAllRegexFlagsNullTokenizer() { SearchIndex index = createTestIndex() .setTokenizers(null); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -510,7 +513,7 @@ public void canUseAllRegexFlagsEmptyTokenizer() { SearchIndex index = createTestIndex() .setTokenizers(new ArrayList<>()); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -524,7 +527,7 @@ public void canUseAllRegexFlagsNullNameTokenizer() { )); assertHttpResponseException( - () -> searchServiceClient.createIndex(index), + () -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "The name field is required." ); @@ -538,7 +541,7 @@ public void canUseAllRegexFlagsEmptyNameTokenizer() { )); assertHttpResponseException( - () -> searchServiceClient.createIndex(index), + () -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "The name field is required." ); @@ -551,7 +554,7 @@ public void canUseAllRegexFlagsNullPatternTokenizer() { .setPattern(null).setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -564,7 +567,7 @@ public void canUseAllRegexFlagsEmptyPatternTokenizer() { .setPattern("").setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -577,7 +580,7 @@ public void canUseAllRegexFlagsNullFlagsTokenizer() { .setFlags(null).setName(generateName()) )); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -592,7 +595,7 @@ public void canUseAllRegexFlagsEmptyFlagsTokenizer() { )); assertHttpResponseException( - () -> searchServiceClient.createIndex(index), + () -> searchIndexClient.createIndex(index), HttpURLConnection.HTTP_BAD_REQUEST, "Values of property \\\"flags\\\" must belong to the set of allowed values" ); @@ -605,7 +608,7 @@ public void canUseAllRegexFlagsNullGroupTokenizer() { .setGroup(null) .setName(generateName()))); - SearchIndex createdIndex = searchServiceClient.createIndex(index); + SearchIndex createdIndex = searchIndexClient.createIndex(index); indexesToCleanup.add(index.getName()); assertAnalysisComponentsEqual(index, createdIndex); @@ -616,10 +619,10 @@ public void canUseAllAnalysisComponentOptions() { List indexes = prepareIndexesWithAllAnalysisComponentOptions(); indexes.forEach(expectedIndex -> { - SearchIndex createdIndex = searchServiceClient.createIndex(expectedIndex); + SearchIndex createdIndex = searchIndexClient.createIndex(expectedIndex); indexesToCleanup.add(expectedIndex.getName()); assertAnalysisComponentsEqual(expectedIndex, createdIndex); - searchServiceClient.deleteIndex(createdIndex.getName()); + searchIndexClient.deleteIndex(createdIndex.getName()); }); } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/DataSourceSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceSyncTests.java similarity index 98% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/DataSourceSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceSyncTests.java index 51ee441f518a..c68c4e9931e2 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/DataSourceSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourceSyncTests.java @@ -1,21 +1,23 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; +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.models.RequestOptions; import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; import com.azure.search.documents.indexes.models.SearchIndexerDataSource; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceType; import com.azure.search.documents.indexes.models.SoftDeleteColumnDeletionDetectionPolicy; import com.azure.search.documents.indexes.models.SqlIntegratedChangeTrackingPolicy; +import com.azure.search.documents.models.RequestOptions; import org.junit.jupiter.api.Test; import java.net.HttpURLConnection; @@ -41,12 +43,12 @@ public class DataSourceSyncTests extends SearchTestBase { "AccountEndpoint=https://NotaRealAccount.documents.azure.com;AccountKey=fake;Database=someFakeDatabase"; private final List dataSourcesToDelete = new ArrayList<>(); - private SearchServiceClient client; + private SearchIndexerClient client; @Override protected void beforeTest() { super.beforeTest(); - client = getSearchServiceClientBuilder().buildClient(); + client = getSearchIndexerClientBuilder().buildClient(); } @Override diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/DataSourcesTest.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourcesTest.java similarity index 97% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/DataSourcesTest.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourcesTest.java index 4f699a0a6771..5b8260e6d825 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/DataSourcesTest.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/DataSourcesTest.java @@ -1,8 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; +import com.azure.search.documents.TestHelpers; import com.azure.search.documents.indexes.models.DataSourceCredentials; import com.azure.search.documents.indexes.models.HighWaterMarkChangeDetectionPolicy; import com.azure.search.documents.indexes.models.SearchIndexerDataContainer; diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FieldBuilderTest.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTest.java similarity index 98% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FieldBuilderTest.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTest.java index 94f52547e4be..833ce2aabdce 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/FieldBuilderTest.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/FieldBuilderTest.java @@ -1,8 +1,9 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; +import com.azure.search.documents.TestHelpers; import com.azure.search.documents.indexes.models.ComplexField; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; import com.azure.search.documents.indexes.models.SearchField; diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexManagementSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementSyncTests.java similarity index 99% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexManagementSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementSyncTests.java index 510acf1b5351..2fddb9d38186 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexManagementSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexManagementSyncTests.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +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.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.CorsOptions; import com.azure.search.documents.indexes.models.GetIndexStatisticsResult; import com.azure.search.documents.indexes.models.LexicalAnalyzerName; @@ -46,12 +47,12 @@ public class IndexManagementSyncTests extends SearchTestBase { private final List indexesToDelete = new ArrayList<>(); private final List synonymMapsToDelete = new ArrayList<>(); - private SearchServiceClient client; + private SearchIndexClient client; @Override protected void beforeTest() { super.beforeTest(); - client = getSearchServiceClientBuilder().buildClient(); + client = getSearchIndexClientBuilder().buildClient(); } @Override diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexersManagementSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexersManagementSyncTests.java similarity index 81% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexersManagementSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexersManagementSyncTests.java index 3565da1817b8..1a5e71e99dce 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/IndexersManagementSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexersManagementSyncTests.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.FieldMapping; import com.azure.search.documents.indexes.models.IndexerExecutionResult; import com.azure.search.documents.indexes.models.IndexerExecutionStatus; @@ -16,7 +17,6 @@ import com.azure.search.documents.indexes.models.InputFieldMappingEntry; import com.azure.search.documents.indexes.models.OcrSkill; import com.azure.search.documents.indexes.models.OutputFieldMappingEntry; -import com.azure.search.documents.models.RequestOptions; import com.azure.search.documents.indexes.models.SearchField; import com.azure.search.documents.indexes.models.SearchFieldDataType; import com.azure.search.documents.indexes.models.SearchIndex; @@ -26,6 +26,7 @@ import com.azure.search.documents.indexes.models.SearchIndexerSkill; import com.azure.search.documents.indexes.models.SearchIndexerSkillset; import com.azure.search.documents.indexes.models.SearchIndexerStatus; +import com.azure.search.documents.models.RequestOptions; import com.azure.search.documents.test.CustomQueryPipelinePolicy; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.Test; @@ -61,11 +62,12 @@ public class IndexersManagementSyncTests extends SearchTestBase { private final List indexesToDelete = new ArrayList<>(); private final List skillsetsToDelete = new ArrayList<>(); - private SearchServiceClient client; + private SearchIndexerClient searchIndexerClient; + private SearchIndexClient searchIndexClient; private String createDataSource() { SearchIndexerDataSource dataSource = createTestSqlDataSourceObject(); - client.createOrUpdateDataSource(dataSource); + searchIndexerClient.createOrUpdateDataSource(dataSource); dataSourcesToDelete.add(dataSource.getName()); return dataSource.getName(); @@ -73,7 +75,7 @@ private String createDataSource() { private String createIndex() { SearchIndex index = createTestIndexForLiveDatasource(); - client.createIndex(index); + searchIndexClient.createIndex(index); indexesToDelete.add(index.getName()); return index.getName(); @@ -82,7 +84,7 @@ private String createIndex() { private SearchIndexer createTestDataSourceAndIndexer() { // Create the indexer object SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - client.createIndexer(indexer); + searchIndexerClient.createIndexer(indexer); indexersToDelete.add(indexer.getName()); return indexer; @@ -95,7 +97,7 @@ private SearchIndexer createTestDataSourceAndIndexer() { */ private void createAndValidateIndexer(SearchIndexer indexer) { // create this indexer in the service - SearchIndexer indexerResponse = client.createIndexer(indexer); + SearchIndexer indexerResponse = searchIndexerClient.createIndexer(indexer); indexersToDelete.add(indexerResponse.getName()); // verify the returned updated indexer is as expected @@ -106,7 +108,8 @@ private void createAndValidateIndexer(SearchIndexer indexer) { @Override protected void beforeTest() { super.beforeTest(); - client = getSearchServiceClientBuilder().buildClient(); + searchIndexerClient = getSearchIndexerClientBuilder().buildClient(); + searchIndexClient = getSearchIndexClientBuilder().buildClient(); } @Override @@ -114,19 +117,19 @@ protected void afterTest() { super.afterTest(); for (String skillset : skillsetsToDelete) { - client.deleteSkillset(skillset); + searchIndexerClient.deleteSkillset(skillset); } for (String dataSource : dataSourcesToDelete) { - client.deleteDataSource(dataSource); + searchIndexerClient.deleteDataSource(dataSource); } for (String indexer : indexersToDelete) { - client.deleteIndexer(indexer); + searchIndexerClient.deleteIndexer(indexer); } for (String index : indexesToDelete) { - client.deleteIndex(index); + searchIndexClient.deleteIndex(index); } } @@ -139,7 +142,7 @@ public void createIndexerReturnsCorrectDefinition() { .setMaxFailedItems(10) .setMaxFailedItemsPerBatch(10)); - SearchIndexer actualIndexer = client.createIndexer(expectedIndexer); + SearchIndexer actualIndexer = searchIndexerClient.createIndexer(expectedIndexer); indexersToDelete.add(actualIndexer.getName()); expectedIndexer.setParameters(new IndexingParameters() @@ -159,12 +162,12 @@ public void canCreateAndListIndexers() { indexer1.setName("a" + indexer1.getName()); SearchIndexer indexer2 = createBaseTestIndexerObject(indexName, dataSourceName); indexer2.setName("b" + indexer2.getName()); - client.createIndexer(indexer1); + searchIndexerClient.createIndexer(indexer1); indexersToDelete.add(indexer1.getName()); - client.createIndexer(indexer2); + searchIndexerClient.createIndexer(indexer2); indexersToDelete.add(indexer2.getName()); - Iterator indexers = client.listIndexers().iterator(); + Iterator indexers = searchIndexerClient.listIndexers().iterator(); SearchIndexer returnedIndexer = indexers.next(); assertObjectEquals(indexer1, returnedIndexer, true, "etag"); @@ -182,12 +185,12 @@ public void canCreateAndListIndexerNames() { indexer1.setName("a" + indexer1.getName()); SearchIndexer indexer2 = createBaseTestIndexerObject(indexName, dataSourceName); indexer2.setName("b" + indexer2.getName()); - client.createIndexer(indexer1); + searchIndexerClient.createIndexer(indexer1); indexersToDelete.add(indexer1.getName()); - client.createIndexer(indexer2); + searchIndexerClient.createIndexer(indexer2); indexersToDelete.add(indexer2.getName()); - Iterator indexersRes = client.listIndexers("name", generateRequestOptions(), Context.NONE).iterator(); + Iterator indexersRes = searchIndexerClient.listIndexers("name", generateRequestOptions(), Context.NONE).iterator(); SearchIndexer actualIndexer = indexersRes.next(); assertEquals(indexer1.getName(), actualIndexer.getName()); @@ -205,7 +208,7 @@ public void createIndexerFailsWithUsefulMessageOnUserError() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), "thisdatasourcedoesnotexist"); assertHttpResponseException( - () -> client.createIndexer(indexer), + () -> searchIndexerClient.createIndexer(indexer), HttpURLConnection.HTTP_BAD_REQUEST, "This indexer refers to a data source 'thisdatasourcedoesnotexist' that doesn't exist"); } @@ -214,8 +217,8 @@ public void createIndexerFailsWithUsefulMessageOnUserError() { public void canResetIndexerAndGetIndexerStatus() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - client.resetIndexer(indexer.getName()); - SearchIndexerStatus indexerStatus = client.getIndexerStatus(indexer.getName()); + searchIndexerClient.resetIndexer(indexer.getName()); + SearchIndexerStatus indexerStatus = searchIndexerClient.getIndexerStatus(indexer.getName()); assertEquals(IndexerStatus.RUNNING, indexerStatus.getStatus()); assertEquals(IndexerExecutionStatus.RESET, indexerStatus.getLastResult().getStatus()); } @@ -224,8 +227,8 @@ public void canResetIndexerAndGetIndexerStatus() { public void canResetIndexerAndGetIndexerStatusWithResponse() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - client.resetIndexerWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE); - SearchIndexerStatus indexerStatusResponse = client.getIndexerStatusWithResponse(indexer.getName(), + searchIndexerClient.resetIndexerWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE); + SearchIndexerStatus indexerStatusResponse = searchIndexerClient.getIndexerStatusWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE).getValue(); assertEquals(IndexerStatus.RUNNING, indexerStatusResponse.getStatus()); assertEquals(IndexerExecutionStatus.RESET, indexerStatusResponse.getLastResult().getStatus()); @@ -234,17 +237,17 @@ public void canResetIndexerAndGetIndexerStatusWithResponse() { @Test public void canRunIndexer() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - client.runIndexer(indexer.getName()); + searchIndexerClient.runIndexer(indexer.getName()); - SearchIndexerStatus indexerExecutionInfo = client.getIndexerStatus(indexer.getName()); + SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); } @Test public void canRunIndexerWithResponse() { SearchIndexer indexer = createTestDataSourceAndIndexer(); - Response response = client.runIndexerWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE); - SearchIndexerStatus indexerExecutionInfo = client.getIndexerStatus(indexer.getName()); + Response response = searchIndexerClient.runIndexerWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE); + SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); assertEquals(HttpURLConnection.HTTP_ACCEPTED, response.getStatusCode()); assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); @@ -255,21 +258,22 @@ public void canRunIndexerAndGetIndexerStatus() { // When an indexer is created, the execution info may not be available immediately. Hence, a // pipeline policy that injects a "mock_status" query string is added to the client, which results in service // returning a well-known mock response - client = getSearchServiceClientBuilder(MOCK_STATUS_PIPELINE_POLICY).buildClient(); + searchIndexerClient = getSearchIndexerClientBuilder(MOCK_STATUS_PIPELINE_POLICY).buildClient(); + searchIndexClient = getSearchIndexClientBuilder(MOCK_STATUS_PIPELINE_POLICY).buildClient(); SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - client.createIndexer(indexer); + searchIndexerClient.createIndexer(indexer); indexersToDelete.add(indexer.getName()); - SearchIndexerStatus indexerExecutionInfo = client.getIndexerStatus(indexer.getName()); + SearchIndexerStatus indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); assertEquals(IndexerStatus.RUNNING, indexerExecutionInfo.getStatus()); - Response indexerRunResponse = client.runIndexerWithResponse(indexer.getName(), new RequestOptions(), + Response indexerRunResponse = searchIndexerClient.runIndexerWithResponse(indexer.getName(), new RequestOptions(), Context.NONE); assertEquals(HttpResponseStatus.ACCEPTED.code(), indexerRunResponse.getStatusCode()); - indexerExecutionInfo = client.getIndexerStatus(indexer.getName()); + indexerExecutionInfo = searchIndexerClient.getIndexerStatus(indexer.getName()); assertValidSearchIndexerStatus(indexerExecutionInfo); } @@ -280,12 +284,12 @@ public void canUpdateIndexer() { String dataSourceName = createDataSource(); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexer updated = createIndexerWithDifferentDescription(indexName, dataSourceName) .setName(initial.getName()); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); // verify the returned updated indexer is as expected setSameStartTime(updated, indexerResponse); @@ -298,12 +302,12 @@ public void canUpdateIndexerFieldMapping() { String dataSourceName = createDataSource(); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexer updated = createIndexerWithDifferentFieldMapping(indexName, dataSourceName) .setName(initial.getName()); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); // verify the returned updated indexer is as expected setSameStartTime(updated, indexerResponse); @@ -322,12 +326,12 @@ public void canUpdateIndexerDisabled() { String dataSourceName = createDataSource(); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexer updated = createDisabledIndexer(indexName, dataSourceName) .setName(initial.getName()); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); setSameStartTime(updated, indexerResponse); assertObjectEquals(updated, indexerResponse, true, "etag"); @@ -339,12 +343,12 @@ public void canUpdateIndexerSchedule() { String dataSourceName = createDataSource(); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexer updated = createIndexerWithDifferentSchedule(indexName, dataSourceName) .setName(initial.getName()); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); setSameStartTime(updated, indexerResponse); assertObjectEquals(updated, indexerResponse, true, "etag"); @@ -362,11 +366,11 @@ public void canUpdateIndexerBatchSizeMaxFailedItems() { String dataSourceName = createDataSource(); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexer updated = createIndexerWithDifferentIndexingParameters(initial); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); setSameStartTime(updated, indexerResponse); assertObjectEquals(updated, indexerResponse, true, "etag"); @@ -385,16 +389,16 @@ public void canCreateIndexerWithBatchSizeMaxFailedItems() { @Test public void canUpdateIndexerBlobParams() { String indexName = createIndex(); - String dataSourceName = client.createDataSource(createBlobDataSource()).getName(); + String dataSourceName = searchIndexerClient.createDataSource(createBlobDataSource()).getName(); dataSourcesToDelete.add(dataSourceName); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexer updated = createIndexerWithStorageConfig(indexName, dataSourceName) .setName(initial.getName()); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); setSameStartTime(updated, indexerResponse); assertObjectEquals(updated, indexerResponse, true, "etag"); @@ -408,7 +412,7 @@ public void canCreateIndexerWithBlobParams() { SearchIndexerDataSource blobDataSource = createBlobDataSource(); // Create the data source within the search service - SearchIndexerDataSource dataSource = client.createOrUpdateDataSource(blobDataSource); + SearchIndexerDataSource dataSource = searchIndexerClient.createOrUpdateDataSource(blobDataSource); dataSourcesToDelete.add(dataSource.getName()); // modify the indexer's blob params @@ -420,19 +424,19 @@ public void canCreateIndexerWithBlobParams() { @Test public void canCreateAndDeleteIndexer() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - client.createIndexer(indexer); + searchIndexerClient.createIndexer(indexer); - client.deleteIndexer(indexer.getName()); - assertThrows(HttpResponseException.class, () -> client.getIndexer(indexer.getName())); + searchIndexerClient.deleteIndexer(indexer.getName()); + assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName())); } @Test public void canCreateAndDeleteIndexerWithResponse() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - client.createIndexerWithResponse(indexer, new RequestOptions(), Context.NONE); + searchIndexerClient.createIndexerWithResponse(indexer, new RequestOptions(), Context.NONE); - client.deleteIndexerWithResponse(indexer, false, new RequestOptions(), Context.NONE); - assertThrows(HttpResponseException.class, () -> client.getIndexer(indexer.getName())); + searchIndexerClient.deleteIndexerWithResponse(indexer, false, new RequestOptions(), Context.NONE); + assertThrows(HttpResponseException.class, () -> searchIndexerClient.getIndexer(indexer.getName())); } @Test @@ -441,31 +445,31 @@ public void deleteIndexerIsIdempotent() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); // Try delete before the indexer even exists. - Response result = client.deleteIndexerWithResponse(indexer, false, generateRequestOptions(), + Response result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, generateRequestOptions(), Context.NONE); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); // Actually create the indexer - client.createIndexer(indexer); + searchIndexerClient.createIndexer(indexer); // Now delete twice. - result = client.deleteIndexerWithResponse(indexer, false, generateRequestOptions(), Context.NONE); + result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, generateRequestOptions(), Context.NONE); assertEquals(HttpURLConnection.HTTP_NO_CONTENT, result.getStatusCode()); - result = client.deleteIndexerWithResponse(indexer, false, generateRequestOptions(), Context.NONE); + result = searchIndexerClient.deleteIndexerWithResponse(indexer, false, generateRequestOptions(), Context.NONE); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, result.getStatusCode()); } @Test public void canCreateAndGetIndexer() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - client.createIndexer(indexer); + searchIndexerClient.createIndexer(indexer); indexersToDelete.add(indexer.getName()); - SearchIndexer indexerResult = client.getIndexer(indexer.getName()); + SearchIndexer indexerResult = searchIndexerClient.getIndexer(indexer.getName()); assertObjectEquals(indexer, indexerResult, true, "etag"); - indexerResult = client.getIndexerWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE) + indexerResult = searchIndexerClient.getIndexerWithResponse(indexer.getName(), generateRequestOptions(), Context.NONE) .getValue(); assertObjectEquals(indexer, indexerResult, true, "etag"); } @@ -473,7 +477,7 @@ public void canCreateAndGetIndexer() { @Test public void getIndexerThrowsOnNotFound() { assertHttpResponseException( - () -> client.getIndexer("thisindexerdoesnotexist"), + () -> searchIndexerClient.getIndexer("thisindexerdoesnotexist"), HttpURLConnection.HTTP_NOT_FOUND, "Indexer 'thisindexerdoesnotexist' was not found"); } @@ -481,7 +485,7 @@ public void getIndexerThrowsOnNotFound() { @Test public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResource() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - SearchIndexer created = client.createOrUpdateIndexerWithResponse(indexer, true, null, Context.NONE) + SearchIndexer created = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, null, Context.NONE) .getValue(); indexersToDelete.add(created.getName()); @@ -491,14 +495,14 @@ public void createOrUpdateIndexerIfNotExistsSucceedsOnNoResource() { @Test public void deleteIndexerIfExistsWorksOnlyWhenResourceExists() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - SearchIndexer created = client.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) + SearchIndexer created = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) .getValue(); - client.deleteIndexerWithResponse(created, true, null, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(created, true, null, Context.NONE); // Try to delete again and expect to fail try { - client.deleteIndexerWithResponse(created, true, null, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(created, true, null, Context.NONE); fail("deleteFunc should have failed due to non existent resource."); } catch (HttpResponseException ex) { assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); @@ -508,31 +512,31 @@ public void deleteIndexerIfExistsWorksOnlyWhenResourceExists() { @Test public void deleteIndexerIfNotChangedWorksOnlyOnCurrentResource() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - SearchIndexer stale = client.createOrUpdateIndexerWithResponse(indexer, true, null, Context.NONE) + SearchIndexer stale = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, true, null, Context.NONE) .getValue(); - SearchIndexer updated = client.createOrUpdateIndexerWithResponse(stale, false, null, Context.NONE) + SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(stale, false, null, Context.NONE) .getValue(); try { - client.deleteIndexerWithResponse(stale, true, null, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(stale, true, null, Context.NONE); fail("deleteFunc should have failed due to precondition."); } catch (HttpResponseException ex) { assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); } - client.deleteIndexerWithResponse(updated, true, null, Context.NONE); + searchIndexerClient.deleteIndexerWithResponse(updated, true, null, Context.NONE); } @Test public void updateIndexerIfExistsSucceedsOnExistingResource() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - SearchIndexer original = client.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) + SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) .getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); - SearchIndexer updated = client.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), + SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), false, null, Context.NONE) .getValue(); String updatedETag = updated.getETag(); @@ -545,19 +549,19 @@ public void updateIndexerIfExistsSucceedsOnExistingResource() { @Test public void updateIndexerIfNotChangedFailsWhenResourceChanged() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - SearchIndexer original = client.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) + SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) .getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); - SearchIndexer updated = client.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), + SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), true, null, Context.NONE) .getValue(); String updatedETag = updated.getETag(); // Update and check the eTags were changed try { - client.createOrUpdateIndexerWithResponse(original, true, null, Context.NONE); + searchIndexerClient.createOrUpdateIndexerWithResponse(original, true, null, Context.NONE); fail("createOrUpdateDefinition should have failed due to precondition."); } catch (HttpResponseException ex) { assertEquals(HttpURLConnection.HTTP_PRECON_FAILED, ex.getResponse().getStatusCode()); @@ -572,12 +576,12 @@ public void updateIndexerIfNotChangedFailsWhenResourceChanged() { @Test public void updateIndexerIfNotChangedSucceedsWhenResourceUnchanged() { SearchIndexer indexer = createBaseTestIndexerObject(createIndex(), createDataSource()); - SearchIndexer original = client.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) + SearchIndexer original = searchIndexerClient.createOrUpdateIndexerWithResponse(indexer, false, null, Context.NONE) .getValue(); String originalETag = original.getETag(); indexersToDelete.add(original.getName()); - SearchIndexer updated = client.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), + SearchIndexer updated = searchIndexerClient.createOrUpdateIndexerWithResponse(original.setDescription("ABrandNewDescription"), true, null, Context.NONE) .getValue(); String updatedETag = updated.getETag(); @@ -594,15 +598,15 @@ public void canUpdateIndexerSkillset() { String dataSourceName = createDataSource(); SearchIndexer initial = createBaseTestIndexerObject(indexName, dataSourceName).setIsDisabled(true); - client.createIndexer(initial); + searchIndexerClient.createIndexer(initial); indexersToDelete.add(initial.getName()); SearchIndexerSkillset skillset = createSkillsetObject(); - client.createSkillset(skillset); + searchIndexerClient.createSkillset(skillset); skillsetsToDelete.add(skillset.getName()); SearchIndexer updated = createIndexerWithDifferentSkillset(indexName, dataSourceName, skillset.getName()) .setName(initial.getName()); - SearchIndexer indexerResponse = client.createOrUpdateIndexer(updated); + SearchIndexer indexerResponse = searchIndexerClient.createOrUpdateIndexer(updated); setSameStartTime(updated, indexerResponse); assertObjectEquals(updated, indexerResponse, true, "etag"); @@ -610,7 +614,7 @@ public void canUpdateIndexerSkillset() { @Test public void canCreateIndexerWithSkillset() { - SearchIndexerSkillset skillset = client.createSkillset(createSkillsetObject()); + SearchIndexerSkillset skillset = searchIndexerClient.createSkillset(createSkillsetObject()); skillsetsToDelete.add(skillset.getName()); SearchIndexer indexer = createIndexerWithDifferentSkillset(createIndex(), createDataSource(), skillset.getName()); 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 new file mode 100644 index 000000000000..1227d3f37bc4 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/IndexesTestHelpers.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.search.documents.indexes; + +import com.azure.core.http.HttpPipeline; + +public class IndexesTestHelpers { + public static HttpPipeline getHttpPipeline(SearchIndexClient searchIndexClient) { + return searchIndexClient.getHttpPipeline(); + } + + public static HttpPipeline getHttpPipeline(SearchIndexAsyncClient searchIndexAsyncClient) { + return searchIndexAsyncClient.getHttpPipeline(); + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexClientBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexClientBuilderTests.java new file mode 100644 index 000000000000..b65d3d36f9a0 --- /dev/null +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexClientBuilderTests.java @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.search.documents.indexes; + +import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.DateTimeRfc1123; +import com.azure.search.documents.SearchServiceVersion; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.SecureRandom; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class SearchIndexClientBuilderTests { + private final AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential("0123"); + private final String searchEndpoint = "https://test.search.windows.net"; + private final SearchServiceVersion apiVersion = SearchServiceVersion.V2019_05_06_Preview; + + @Test + public void buildSyncClientTest() { + SearchIndexClient client = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .serviceVersion(apiVersion) + .buildClient(); + + assertNotNull(client); + assertEquals(SearchIndexClient.class.getSimpleName(), client.getClass().getSimpleName()); + } + + @Test + public void buildSyncClientUsingDefaultApiVersionTest() { + SearchIndexClient client = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .buildClient(); + + assertNotNull(client); + assertEquals(SearchIndexClient.class.getSimpleName(), client.getClass().getSimpleName()); + } + + @Test + public void buildAsyncClientTest() { + SearchIndexAsyncClient client = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .serviceVersion(apiVersion) + .buildAsyncClient(); + + assertNotNull(client); + assertEquals(SearchIndexAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); + } + + @Test + public void buildAsyncClientUsingDefaultApiVersionTest() { + SearchIndexAsyncClient client = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .buildAsyncClient(); + + assertNotNull(client); + assertEquals(SearchIndexAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); + } + + @Test + public void whenApiVersionSpecifiedThenSpecifiedValueExists() { + SearchServiceVersion expectedApiVersion = SearchServiceVersion.V2019_05_06_Preview; + + SearchIndexClient client = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .serviceVersion(expectedApiVersion) + .buildClient(); + + assertEquals(expectedApiVersion.getVersion(), client.getServiceVersion().getVersion()); + + SearchIndexAsyncClient asyncClient = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .serviceVersion(expectedApiVersion) + .buildAsyncClient(); + assertEquals(expectedApiVersion.getVersion(), asyncClient.getServiceVersion().getVersion()); + } + + @Test + public void whenBuildClientAndVerifyPropertiesThenSuccess() { + SearchIndexClient client = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .buildClient(); + + assertEquals(searchEndpoint, client.getEndpoint()); + assertEquals(apiVersion, client.getServiceVersion()); + + SearchIndexAsyncClient asyncClient = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .serviceVersion(apiVersion) + .buildAsyncClient(); + + assertEquals(searchEndpoint, asyncClient.getEndpoint()); + assertEquals(apiVersion, asyncClient.getServiceVersion()); + } + + @Test + public void emptyEndpointThrowsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder().endpoint("")); + } + + @Test + public void nullCredentialThrowsNullPointerException() { + assertThrows(NullPointerException.class, () -> new SearchIndexClientBuilder().credential(null)); + } + + @Test + public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> new SearchIndexClientBuilder() + .credential(new AzureKeyCredential(""))); + } + + @Test + void nullApiVersionSetsLatest() { + SearchIndexClientBuilder builder = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .serviceVersion(null); + + assertEquals(SearchServiceVersion.getLatest(), builder.buildAsyncClient().getServiceVersion()); + assertEquals(SearchServiceVersion.getLatest(), builder.buildClient().getServiceVersion()); + } + + @Test + public void verifyEmptyApiVersionSetsLatest() { + SearchIndexClient searchIndexClient = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .buildClient(); + + assertEquals(SearchServiceVersion.getLatest(), searchIndexClient.getServiceVersion()); + } + + @Test + public void verifyEmptyApiVersionSetsLatestAsync() { + SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .buildAsyncClient(); + + assertEquals(SearchServiceVersion.getLatest(), searchIndexAsyncClient.getServiceVersion()); + } + + @Test + public void serviceClientFreshDateOnRetry() throws MalformedURLException { + byte[] randomData = new byte[256]; + new SecureRandom().nextBytes(randomData); + SearchIndexAsyncClient searchIndexAsyncClient = new SearchIndexClientBuilder() + .endpoint(searchEndpoint) + .credential(searchApiKeyCredential) + .httpClient(new FreshDateTestClient()) + .buildAsyncClient(); + + + StepVerifier.create(searchIndexAsyncClient.getHttpPipeline().send( + request(searchIndexAsyncClient.getEndpoint()))) + .assertNext(response -> assertEquals(200, response.getStatusCode())) + .verifyComplete(); + } + + public static HttpRequest request(String url) throws MalformedURLException { + return new HttpRequest(HttpMethod.HEAD, + new URL(url), new HttpHeaders().put("Content-Length", "0"), + Flux.empty()); + } + + public static final class FreshDateTestClient implements HttpClient { + private DateTimeRfc1123 firstDate; + + @Override + public Mono send(HttpRequest request) { + if (firstDate == null) { + firstDate = convertToDateObject(request.getHeaders().getValue("Date")); + return Mono.error(new IOException("IOException!")); + } + + assert !firstDate.equals(convertToDateObject(request.getHeaders().getValue("Date"))); + return Mono.just(new MockHttpResponse(request, 200)); + } + + private static DateTimeRfc1123 convertToDateObject(String dateHeader) { + if (CoreUtils.isNullOrEmpty(dateHeader)) { + throw new RuntimeException("Failed to set 'Date' header."); + } + + return new DateTimeRfc1123(dateHeader); + } + } +} diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceClientBuilderTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexerClientBuilderTests.java similarity index 79% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceClientBuilderTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexerClientBuilderTests.java index 418dd2205d17..51da232004ca 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceClientBuilderTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchIndexerClientBuilderTests.java @@ -1,6 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.http.HttpClient; @@ -11,6 +11,7 @@ import com.azure.core.test.http.MockHttpResponse; import com.azure.core.util.CoreUtils; import com.azure.core.util.DateTimeRfc1123; +import com.azure.search.documents.SearchServiceVersion; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -25,62 +26,62 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; -public class SearchServiceClientBuilderTests { +public class SearchIndexerClientBuilderTests { private final AzureKeyCredential searchApiKeyCredential = new AzureKeyCredential("0123"); private final String searchEndpoint = "https://test.search.windows.net"; private final SearchServiceVersion apiVersion = SearchServiceVersion.V2019_05_06_Preview; @Test public void buildSyncClientTest() { - SearchServiceClient client = new SearchServiceClientBuilder() + SearchIndexerClient client = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .serviceVersion(apiVersion) .buildClient(); assertNotNull(client); - assertEquals(SearchServiceClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchIndexerClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void buildSyncClientUsingDefaultApiVersionTest() { - SearchServiceClient client = new SearchServiceClientBuilder() + SearchIndexerClient client = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .buildClient(); assertNotNull(client); - assertEquals(SearchServiceClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchIndexerClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void buildAsyncClientTest() { - SearchServiceAsyncClient client = new SearchServiceClientBuilder() + SearchIndexerAsyncClient client = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .serviceVersion(apiVersion) .buildAsyncClient(); assertNotNull(client); - assertEquals(SearchServiceAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchIndexerAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void buildAsyncClientUsingDefaultApiVersionTest() { - SearchServiceAsyncClient client = new SearchServiceClientBuilder() + SearchIndexerAsyncClient client = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .buildAsyncClient(); assertNotNull(client); - assertEquals(SearchServiceAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); + assertEquals(SearchIndexerAsyncClient.class.getSimpleName(), client.getClass().getSimpleName()); } @Test public void whenApiVersionSpecifiedThenSpecifiedValueExists() { SearchServiceVersion expectedApiVersion = SearchServiceVersion.V2019_05_06_Preview; - SearchServiceClient client = new SearchServiceClientBuilder() + SearchIndexerClient client = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .serviceVersion(expectedApiVersion) @@ -88,7 +89,7 @@ public void whenApiVersionSpecifiedThenSpecifiedValueExists() { assertEquals(expectedApiVersion.getVersion(), client.getServiceVersion().getVersion()); - SearchServiceAsyncClient asyncClient = new SearchServiceClientBuilder() + SearchIndexerAsyncClient asyncClient = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .serviceVersion(expectedApiVersion) @@ -98,7 +99,7 @@ public void whenApiVersionSpecifiedThenSpecifiedValueExists() { @Test public void whenBuildClientAndVerifyPropertiesThenSuccess() { - SearchServiceClient client = new SearchServiceClientBuilder() + SearchIndexerClient client = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .buildClient(); @@ -106,7 +107,7 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { assertEquals(searchEndpoint, client.getEndpoint()); assertEquals(apiVersion, client.getServiceVersion()); - SearchServiceAsyncClient asyncClient = new SearchServiceClientBuilder() + SearchIndexerAsyncClient asyncClient = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .serviceVersion(apiVersion) @@ -118,23 +119,23 @@ public void whenBuildClientAndVerifyPropertiesThenSuccess() { @Test public void emptyEndpointThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchServiceClientBuilder().endpoint("")); + assertThrows(IllegalArgumentException.class, () -> new SearchIndexerClientBuilder().endpoint("")); } @Test public void nullCredentialThrowsNullPointerException() { - assertThrows(NullPointerException.class, () -> new SearchServiceClientBuilder().credential(null)); + assertThrows(NullPointerException.class, () -> new SearchIndexerClientBuilder().credential(null)); } @Test public void credentialWithEmptyApiKeyThrowsIllegalArgumentException() { - assertThrows(IllegalArgumentException.class, () -> new SearchServiceClientBuilder() + assertThrows(IllegalArgumentException.class, () -> new SearchIndexerClientBuilder() .credential(new AzureKeyCredential(""))); } @Test void nullApiVersionSetsLatest() { - SearchServiceClientBuilder builder = new SearchServiceClientBuilder() + SearchIndexerClientBuilder builder = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .serviceVersion(null); @@ -145,37 +146,37 @@ void nullApiVersionSetsLatest() { @Test public void verifyEmptyApiVersionSetsLatest() { - SearchServiceClient searchServiceClient = new SearchServiceClientBuilder() + SearchIndexerClient searchIndexerClient = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .buildClient(); - assertEquals(SearchServiceVersion.getLatest(), searchServiceClient.getServiceVersion()); + assertEquals(SearchServiceVersion.getLatest(), searchIndexerClient.getServiceVersion()); } @Test public void verifyEmptyApiVersionSetsLatestAsync() { - SearchServiceAsyncClient searchServiceAsyncClient = new SearchServiceClientBuilder() + SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .buildAsyncClient(); - assertEquals(SearchServiceVersion.getLatest(), searchServiceAsyncClient.getServiceVersion()); + assertEquals(SearchServiceVersion.getLatest(), searchIndexerAsyncClient.getServiceVersion()); } @Test public void serviceClientFreshDateOnRetry() throws MalformedURLException { byte[] randomData = new byte[256]; new SecureRandom().nextBytes(randomData); - SearchServiceAsyncClient searchServiceAsyncClient = new SearchServiceClientBuilder() + SearchIndexerAsyncClient searchIndexerAsyncClient = new SearchIndexerClientBuilder() .endpoint(searchEndpoint) .credential(searchApiKeyCredential) .httpClient(new FreshDateTestClient()) .buildAsyncClient(); - StepVerifier.create(searchServiceAsyncClient.getHttpPipeline().send( - request(searchServiceAsyncClient.getEndpoint()))) + StepVerifier.create(searchIndexerAsyncClient.getHttpPipeline().send( + request(searchIndexerAsyncClient.getEndpoint()))) .assertNext(response -> assertEquals(200, response.getStatusCode())) .verifyComplete(); } diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchServiceSyncTests.java similarity index 88% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchServiceSyncTests.java index c9fb04b9644e..f4e3fdab30d8 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SearchServiceSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SearchServiceSyncTests.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +package com.azure.search.documents.indexes; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; -import com.azure.search.documents.models.RequestOptions; +import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.ServiceCounters; import com.azure.search.documents.indexes.models.ServiceStatistics; +import com.azure.search.documents.models.RequestOptions; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -19,14 +20,14 @@ public class SearchServiceSyncTests extends SearchTestBase { @Test public void getServiceStatsReturnsCorrectDefinition() { - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); validateServiceStatistics(serviceClient.getServiceStatistics()); } @Test public void getServiceStatsReturnsCorrectDefinitionWithResponse() { - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); ServiceStatistics serviceStatistics = serviceClient.getServiceStatisticsWithResponse(generateRequestOptions(), Context.NONE).getValue(); @@ -35,7 +36,7 @@ public void getServiceStatsReturnsCorrectDefinitionWithResponse() { @Test public void getServiceStatsReturnsRequestId() { - SearchServiceClient serviceClient = getSearchServiceClientBuilder().buildClient(); + SearchIndexClient serviceClient = getSearchIndexClientBuilder().buildClient(); RequestOptions requestOptions = new RequestOptions().setXMsClientRequestId(UUID.randomUUID()); Response response = serviceClient.getServiceStatisticsWithResponse(requestOptions, diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SkillsetManagementSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementSyncTests.java similarity index 99% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SkillsetManagementSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementSyncTests.java index 8ef5d07bba49..b73cc19a05fb 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SkillsetManagementSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SkillsetManagementSyncTests.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +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.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.ConditionalSkill; import com.azure.search.documents.indexes.models.DefaultCognitiveServicesAccount; import com.azure.search.documents.indexes.models.EntityCategory; @@ -61,12 +62,12 @@ public class SkillsetManagementSyncTests extends SearchTestBase { private final List skillsetsToDelete = new ArrayList<>(); - private SearchServiceClient client; + private SearchIndexerClient client; @Override protected void beforeTest() { super.beforeTest(); - client = getSearchServiceClientBuilder().buildClient(); + client = getSearchIndexerClientBuilder().buildClient(); } @Override diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SynonymMapManagementSyncTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementSyncTests.java similarity index 98% rename from sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SynonymMapManagementSyncTests.java rename to sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementSyncTests.java index bdb5a60dc509..f55eac44f4c1 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/SynonymMapManagementSyncTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/indexes/SynonymMapManagementSyncTests.java @@ -1,12 +1,13 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.search.documents; +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.util.Context; import com.azure.core.util.CoreUtils; +import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.indexes.models.SynonymMap; import org.junit.jupiter.api.Test; @@ -30,12 +31,12 @@ public class SynonymMapManagementSyncTests extends SearchTestBase { private final List synonymMapsToDelete = new ArrayList<>(); - private SearchServiceClient client; + private SearchIndexClient client; @Override protected void beforeTest() { super.beforeTest(); - client = getSearchServiceClientBuilder().buildClient(); + client = getSearchIndexClientBuilder().buildClient(); } @Override diff --git a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/GeoPointTests.java b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/GeoPointTests.java index bde7e8e3152a..390cfdd693c2 100644 --- a/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/GeoPointTests.java +++ b/sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/models/GeoPointTests.java @@ -4,7 +4,7 @@ package com.azure.search.documents.models; import com.azure.core.util.Context; -import com.azure.search.documents.SearchIndexClient; +import com.azure.search.documents.SearchClient; import com.azure.search.documents.SearchTestBase; import com.azure.search.documents.implementation.SerializationUtil; import com.azure.search.documents.indexes.models.SearchField; @@ -34,7 +34,7 @@ public class GeoPointTests extends SearchTestBase { private static final String DATA_JSON_HOTELS = "HotelsDataArray.json"; - private SearchIndexClient client; + private SearchClient client; private void uploadDocuments() throws Exception { Reader docsData = new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader() @@ -52,7 +52,7 @@ private void uploadDocuments() throws Exception { @Override protected void afterTest() { - getSearchServiceClientBuilder().buildClient().deleteIndex(client.getIndexName()); + getSearchIndexClientBuilder().buildClient().deleteIndex(client.getIndexName()); } @Test