// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. /// import type { KeyCredential, TokenCredential } from "@azure/core-auth"; import { isTokenCredential } from "@azure/core-auth"; import { bearerTokenAuthenticationPolicy, bearerTokenAuthenticationPolicyName, type Pipeline, } from "@azure/core-rest-pipeline"; import { decode, encode } from "./base64.js"; import type { AutocompleteResult, IndexDocumentsResult, QueryAnswerType as BaseAnswers, QueryCaptionType as BaseCaptions, SearchRequest as GeneratedSearchRequest, VectorQueryUnion as GeneratedVectorQuery, SemanticSearchResultsType, } from "./models/azure/search/documents/index.js"; import type { SearchClientOptionalParams } from "./search/searchClient.js"; import { createSearch, type SearchContext } from "./search/api/searchContext.js"; import { autocompletePost, getDocument, getDocumentCount, index, _suggestPostSend, _suggestPostDeserialize, } from "./search/api/operations.js"; import { searchPostWithCompatibility } from "./searchCompatibility.js"; import { IndexDocumentsBatch } from "./indexDocumentsBatch.js"; import type { AutocompleteOptions, CountDocumentsOptions, DeleteDocumentsOptions, GetDocumentOptions, IndexDocumentsAction, IndexDocumentsOptions, ListSearchResultsPageSettings, MergeDocumentsOptions, MergeOrUploadDocumentsOptions, NarrowedModel, QueryAnswer, QueryCaption, SearchDocumentsPageResult, SearchDocumentsResult, SearchFieldArray, SearchIterator, SearchOptions, SearchResult, SelectFields, SemanticErrorReason, SuggestDocumentsResult, SuggestOptions, UploadDocumentsOptions, VectorQuery, } from "./indexModels.js"; import { logger } from "./logger.js"; import { createOdataMetadataPolicy } from "./odataMetadataPolicy.js"; import { createSearchApiKeyCredentialPolicy } from "./searchApiKeyCredentialPolicy.js"; import { KnownSearchAudience } from "./searchAudience.js"; import type { IndexDocumentsClient } from "./searchIndexingBufferedSender.js"; import { deserialize, serialize } from "./serialization.js"; import * as utils from "./serviceUtils.js"; import { tracingClient } from "./tracing.js"; import type { ClientOptions, OperationOptions } from "@azure-rest/core-client"; import type { GetDocumentOptionalParams, SuggestPostOptionalParams, SearchPostOptionalParams, } from "./search/index.js"; /** * Client options used to configure AI Search API requests. */ export interface SearchClientOptions extends ClientOptions { /** * The API version to use when communicating with the service. * @deprecated use {@link serviceVersion} instead */ apiVersion?: string; /** * The service version to use when communicating with the service. */ serviceVersion?: string; /** * The Audience to use for authentication with Azure Active Directory (AAD). The * audience is not considered when using a shared key. * {@link KnownSearchAudience} can be used interchangeably with audience */ audience?: string; } /** * Class used to perform operations against a search index, * including querying documents in the index as well as * adding, updating, and removing them. */ export class SearchClient implements IndexDocumentsClient { /// Maintenance note: when updating supported API versions, /// the ContinuationToken logic will need to be updated below. /** * The service version to use when communicating with the service. */ public readonly serviceVersion: string = utils.defaultServiceVersion; /** * The API version to use when communicating with the service. * @deprecated use {@Link serviceVersion} instead */ public readonly apiVersion: string = utils.defaultServiceVersion; /** * The endpoint of the search service */ public readonly endpoint: string; /** * The name of the index */ public readonly indexName: string; /** * @hidden * A reference to the auto-generated SearchClient */ private readonly client: SearchContext; /** * A reference to the internal HTTP pipeline for use with raw requests */ public readonly pipeline: Pipeline; /** * Creates an instance of SearchClient. * * Example usage: * ```ts snippet:ReadmeSampleSearchClient * import { SearchClient, AzureKeyCredential } from "@azure/search-documents"; * * const searchClient = new SearchClient( * "", * "", * new AzureKeyCredential(""), * ); * ``` * * Optionally, the type of the model can be used to enable strong typing and type hints: * ```ts snippet:ReadmeSampleSearchClientWithModel * import { SearchClient, AzureKeyCredential } from "@azure/search-documents"; * * type TModel = { * keyName: string; * field1?: string | null; * field2?: { * anotherField?: string | null; * } | null; * }; * * const searchClient = new SearchClient( * "", * "", * new AzureKeyCredential(""), * ); * ``` * * @param endpoint - The endpoint of the search service * @param indexName - The name of the index * @param credential - Used to authenticate requests to the service. * @param options - Used to configure the Search client. * * @typeParam TModel - An optional type that represents the documents stored in * the search index. For the best typing experience, all non-key fields should * be marked optional and nullable, and the key property should have the * non-nullable type `string`. */ constructor( endpoint: string, indexName: string, credential: KeyCredential | TokenCredential, options: SearchClientOptions = {}, ) { this.endpoint = endpoint; this.indexName = indexName; const internalClientPipelineOptions: SearchClientOptionalParams = { ...options, ...{ loggingOptions: { logger: logger.info, additionalAllowedHeaderNames: [ "elapsed-time", "Location", "OData-MaxVersion", "OData-Version", "Prefer", "throttle-reason", ], }, }, }; this.serviceVersion = options.serviceVersion ?? options.apiVersion ?? utils.defaultServiceVersion; this.apiVersion = this.serviceVersion; this.client = createSearch(this.endpoint, credential, this.indexName, { ...internalClientPipelineOptions, apiVersion: this.serviceVersion, }); this.pipeline = this.client.pipeline; // Replaced with a custom policy below this.pipeline.removePolicy({ name: bearerTokenAuthenticationPolicyName }); if (isTokenCredential(credential)) { const scope: string = options.audience ? `${options.audience}/.default` : `${KnownSearchAudience.AzurePublicCloud}/.default`; this.client.pipeline.addPolicy( bearerTokenAuthenticationPolicy({ credential, scopes: scope }), ); } else { this.client.pipeline.addPolicy(createSearchApiKeyCredentialPolicy(credential)); } this.client.pipeline.addPolicy(createOdataMetadataPolicy("none")); } /** * Retrieves the number of documents in the index. * @param options - Options to the count operation. */ // eslint-disable-next-line @azure/azure-sdk/ts-naming-options public async getDocumentsCount(options: CountDocumentsOptions = {}): Promise { return tracingClient.withSpan( "SearchClient-getDocumentsCount", options, async (updatedOptions) => { const count = await getDocumentCount(this.client, updatedOptions); return Number(count); }, ); } /** * Based on a partial searchText from the user, return a list of potential completion strings * based on a specified suggester. * @param searchText - The search text on which to base autocomplete results. * @param suggesterName - The name of the suggester as specified in the suggesters collection * that's part of the index definition. * @param options - Options to the autocomplete operation. * @example * ```ts snippet:ReadmeSampleAutocomplete * import { SearchClient, AzureKeyCredential, SearchFieldArray } from "@azure/search-documents"; * * type TModel = { * key: string; * azure?: { * sdk: string | null; * } | null; * }; * * const client = new SearchClient( * "endpoint.azure", * "indexName", * new AzureKeyCredential("key"), * ); * * const searchFields: SearchFieldArray = ["azure/sdk"]; * * const autocompleteResult = await client.autocomplete("searchText", "suggesterName", { * searchFields, * }); * ``` */ public async autocomplete( searchText: string, suggesterName: string, options: AutocompleteOptions = {}, ): Promise { if (!searchText) { throw new RangeError("searchText must be provided."); } if (!suggesterName) { throw new RangeError("suggesterName must be provided."); } const { searchFields, ...restOptions } = options; return tracingClient.withSpan("SearchClient-autocomplete", options, async (updatedOptions) => { return autocompletePost(this.client, searchText, suggesterName, { ...updatedOptions, ...restOptions, // Cast readonly array to mutable - the generated code doesn't mutate it searchFields: searchFields as string[] | undefined, }); }); } private async searchDocuments>( searchText?: string, options: SearchOptions = {}, nextPageParameters?: GeneratedSearchRequest, ): Promise> { const { includeTotalCount, orderBy, searchFields, select, highlightFields, vectorSearchOptions, semanticSearchOptions, debug, ...restOptions } = options as typeof options & { queryType: "semantic" }; const { semanticFields, configurationName, errorMode, answers, captions, debugMode, ...restSemanticOptions } = semanticSearchOptions ?? {}; const { queries, filterMode, ...restVectorOptions } = vectorSearchOptions ?? {}; const fullOptions: SearchPostOptionalParams = { ...restSemanticOptions, ...restVectorOptions, ...restOptions, searchFields: this.convertSearchFields(searchFields), select: this.convertSelect(select) || "*", highlightFields: highlightFields?.split(","), orderBy: this.convertOrderBy(orderBy), includeTotalCount, vectorQueries: queries?.map(this.convertVectorQuery.bind(this)), answers: this.convertQueryAnswers(answers), captions: this.convertQueryCaptions(captions), semanticErrorHandling: errorMode, semanticConfigurationName: configurationName, debug: debugMode ?? debug, // Use semanticSearchOptions.debugMode if set, otherwise use top-level debug vectorFilterMode: filterMode, searchText, ...nextPageParameters, }; return tracingClient.withSpan( "SearchClient-searchDocuments", fullOptions, async (updatedOptions) => { const continuationFields = ( nextPageParameters as (GeneratedSearchRequest & { semanticFields?: string }) | undefined )?.semanticFields; const result = await searchPostWithCompatibility( this.client, updatedOptions, continuationFields?.split(",") ?? semanticFields, ); const { results, nextLink, nextPageParameters: resultNextPageParameters, semanticPartialResponseReason: semanticErrorReason, semanticPartialResponseType: semanticSearchResultsType, facets, answers: resultAnswers, ...restResult } = result as typeof result & { semanticPartialResponseReason: SemanticErrorReason | undefined; semanticPartialResponseType: SemanticSearchResultsType | undefined; }; const modifiedResults = utils.generatedSearchResultToPublicSearchResult( results, ); const converted: SearchDocumentsPageResult = { ...restResult, facets: utils.convertGeneratedFacetsToPublic(facets), answers: utils.convertGeneratedAnswersToPublic(resultAnswers), results: modifiedResults, semanticErrorReason, semanticSearchResultsType, continuationToken: this.encodeContinuationToken(nextLink, resultNextPageParameters), }; return deserialize>(converted); }, ); } private async *listSearchResultsPage>( searchText?: string, options: SearchOptions = {}, settings: ListSearchResultsPageSettings = {}, ): AsyncIterableIterator> { let decodedContinuation = this.decodeContinuationToken(settings.continuationToken); let result = await this.searchDocuments( searchText, options, decodedContinuation?.nextPageParameters, ); yield result; // Technically, we should also leverage nextLink, but the generated code // doesn't support this yet. while (result.continuationToken) { decodedContinuation = this.decodeContinuationToken(result.continuationToken); result = await this.searchDocuments( searchText, options, decodedContinuation?.nextPageParameters, ); yield result; } } private async *listSearchResultsAll>( firstPage: SearchDocumentsPageResult, searchText?: string, options: SearchOptions = {}, ): AsyncIterableIterator> { yield* firstPage.results; if (firstPage.continuationToken) { for await (const page of this.listSearchResultsPage(searchText, options, { continuationToken: firstPage.continuationToken, })) { yield* page.results; } } } private listSearchResults>( firstPage: SearchDocumentsPageResult, searchText?: string, options: SearchOptions = {}, ): SearchIterator { const iter = this.listSearchResultsAll(firstPage, searchText, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: (settings: ListSearchResultsPageSettings = {}) => { return this.listSearchResultsPage(searchText, options, settings); }, }; } /** * Performs a search on the current index given * the specified arguments. * @param searchText - Text to search * @param options - Options for the search operation. * @example * ```ts snippet:ReadmeSampleSearchTModel * import { SearchClient, AzureKeyCredential, SearchFieldArray } from "@azure/search-documents"; * * type TModel = { * key: string; * azure?: { * sdk: string | null; * } | null; * }; * * const client = new SearchClient( * "endpoint.azure", * "indexName", * new AzureKeyCredential("key"), * ); * * const select = ["azure/sdk"] as const; * const searchFields: SearchFieldArray = ["azure/sdk"]; * * const searchResult = await client.search("searchText", { * select, * searchFields, * }); * ``` */ public async search>( searchText?: string, options: SearchOptions = {}, ): Promise> { return tracingClient.withSpan("SearchClient-search", options, async (updatedOptions) => { const pageResult = await this.searchDocuments(searchText, updatedOptions); return { ...pageResult, results: this.listSearchResults(pageResult, searchText, updatedOptions), }; }); } /** * Returns a short list of suggestions based on the searchText and specified suggester. * @param searchText - The search text to use to suggest documents. Must be at least 1 character, * and no more than 100 characters. * @param suggesterName - The name of the suggester as specified in the suggesters collection * that's part of the index definition. * @param options - Options for the suggest operation * @example * ```ts snippet:ReadmeSampleSuggest * import { SearchClient, AzureKeyCredential, SearchFieldArray } from "@azure/search-documents"; * * type TModel = { * key: string; * azure?: { * sdk: string | null; * } | null; * }; * * const client = new SearchClient( * "endpoint.azure", * "indexName", * new AzureKeyCredential("key"), * ); * * const select = ["azure/sdk"] as const; * const searchFields: SearchFieldArray = ["azure/sdk"]; * * const suggestResult = await client.suggest("searchText", "suggesterName", { * select, * searchFields, * }); * ``` */ public async suggest = never>( searchText: string, suggesterName: string, options: SuggestOptions = {}, ): Promise> { const { select, searchFields, orderBy, ...nonFieldOptions } = options; const fullOptions: SuggestPostOptionalParams = { // Cast readonly arrays to mutable - the generated code doesn't mutate them searchFields: this.convertSearchFields(searchFields), select: this.convertSelect(select), orderBy: this.convertOrderBy(orderBy), ...nonFieldOptions, }; if (!searchText) { throw new RangeError("searchText must be provided."); } if (!suggesterName) { throw new RangeError("suggesterName must be provided."); } return tracingClient.withSpan("SearchClient-suggest", fullOptions, async (updatedOptions) => { const response = await _suggestPostSend( this.client, searchText, suggesterName, updatedOptions, ); const generatedResult = await _suggestPostDeserialize(response); // Recover document fields before the generated deserializer confuses `text` with metadata. const wireResults: Record[] = response.body.value; const result = { ...generatedResult, results: generatedResult.results.map((suggestion, i) => ({ ...suggestion, additionalProperties: Object.fromEntries( Object.entries(wireResults[i]).filter(([key]) => !key.startsWith("@search.")), ), })), }; const modifiedResult = utils.generatedSuggestDocumentsResultToPublicSuggestDocumentsResult< TModel, TFields >(result); return deserialize>(modifiedResult); }); } /** * Retrieve a particular document from the index by key. * @param key - The primary key value of the document * @param options - Additional options */ public async getDocument>( key: string, options: GetDocumentOptions = {}, ): Promise> { return tracingClient.withSpan( "SearchClient-getDocument", options as OperationOptions, async (updatedOptions: GetDocumentOptionalParams) => { const result = await getDocument(this.client, key, { ...updatedOptions, selectedFields: updatedOptions.selectedFields, }); // The generated code puts document fields in additionalProperties return deserialize>(result.additionalProperties ?? {}); }, ); } /** * Perform a set of index modifications (upload, merge, mergeOrUpload, delete) * for the given set of documents. * This operation may partially succeed and not all document operations will * be reflected in the index. If you would like to treat this as an exception, * set the `throwOnAnyFailure` option to true. * For more details about how merging works, see: https://learn.microsoft.com/rest/api/searchservice/AddUpdate-or-Delete-Documents * @param batch - An array of actions to perform on the index. * @param options - Additional options. */ public async indexDocuments( // eslint-disable-next-line @azure/azure-sdk/ts-use-interface-parameters batch: IndexDocumentsBatch, options: IndexDocumentsOptions = {}, ): Promise { return tracingClient.withSpan( "SearchClient-indexDocuments", options, async (updatedOptions) => { let status = 0; const serializedActions = serialize[]>(batch.actions); const result = await index( this.client, { actions: utils.convertPublicActionsToGeneratedActions(serializedActions) }, { ...updatedOptions, onResponse: (rawResponse, flatResponse) => { status = rawResponse.status; if (updatedOptions.onResponse) { updatedOptions.onResponse(rawResponse, flatResponse); } }, }, ); if (options.throwOnAnyFailure && status === 207) { throw result; } return result; }, ); } /** * Upload an array of documents to the index. * @param documents - The documents to upload. * @param options - Additional options. */ public async uploadDocuments( documents: TModel[], options: UploadDocumentsOptions = {}, ): Promise { return tracingClient.withSpan( "SearchClient-uploadDocuments", options, async (updatedOptions) => { const batch = new IndexDocumentsBatch(); batch.upload(documents); return this.indexDocuments(batch, updatedOptions); }, ); } /** * Update a set of documents in the index. * * For more details about how merging works, see * https://learn.microsoft.com/rest/api/searchservice/AddUpdate-or-Delete-Documents * @param documents - The updated documents. * @param options - Additional options. */ public async mergeDocuments( documents: TModel[], options: MergeDocumentsOptions = {}, ): Promise { return tracingClient.withSpan( "SearchClient-mergeDocuments", options, async (updatedOptions) => { const batch = new IndexDocumentsBatch(); batch.merge(documents); return this.indexDocuments(batch, updatedOptions); }, ); } /** * Update a set of documents in the index or upload them if they don't exist. * * For more details about how merging works, see * https://learn.microsoft.com/rest/api/searchservice/AddUpdate-or-Delete-Documents * @param documents - The updated documents. * @param options - Additional options. */ public async mergeOrUploadDocuments( documents: TModel[], options: MergeOrUploadDocumentsOptions = {}, ): Promise { return tracingClient.withSpan( "SearchClient-mergeOrUploadDocuments", options, async (updatedOptions) => { const batch = new IndexDocumentsBatch(); batch.mergeOrUpload(documents); return this.indexDocuments(batch, updatedOptions); }, ); } /** * Delete a set of documents. * @param documents - Documents to be deleted. * @param options - Additional options. */ public async deleteDocuments( documents: TModel[], options?: DeleteDocumentsOptions, ): Promise; /** * Delete a set of documents. * @param keyName - The name of their primary key in the index. * @param keyValues - The primary key values of documents to delete. * @param options - Additional options. */ public async deleteDocuments( keyName: keyof TModel, keyValues: string[], options?: DeleteDocumentsOptions, ): Promise; public async deleteDocuments( keyNameOrDocuments: keyof TModel | TModel[], keyValuesOrOptions?: string[] | DeleteDocumentsOptions, options: DeleteDocumentsOptions = {}, ): Promise { const operationOptions = Array.isArray(keyNameOrDocuments) ? ((keyValuesOrOptions as DeleteDocumentsOptions | undefined) ?? {}) : options; return tracingClient.withSpan( "SearchClient-deleteDocuments", operationOptions, async (updatedOptions) => { const batch = new IndexDocumentsBatch(); if (typeof keyNameOrDocuments === "string") { batch.delete(keyNameOrDocuments, keyValuesOrOptions as string[]); } else { batch.delete(keyNameOrDocuments as TModel[]); } return this.indexDocuments(batch, updatedOptions); }, ); } private encodeContinuationToken( nextLink: string | undefined, nextPageParameters: GeneratedSearchRequest | undefined, ): string | undefined { if (!nextLink || !nextPageParameters) { return undefined; } const payload = JSON.stringify({ apiVersion: this.apiVersion, nextLink, nextPageParameters, }); return encode(payload); } private decodeContinuationToken( token?: string, ): { nextPageParameters: GeneratedSearchRequest; nextLink: string } | undefined { if (!token) { return undefined; } const decodedToken = decode(token); try { const result: { apiVersion: string; nextLink: string; nextPageParameters: GeneratedSearchRequest; } = JSON.parse(decodedToken); if (result.apiVersion !== this.apiVersion) { throw new RangeError(`Continuation token uses unsupported apiVersion "${this.apiVersion}"`); } return { nextLink: result.nextLink, nextPageParameters: result.nextPageParameters, }; } catch (e: any) { throw new Error(`Corrupted or invalid continuation token: ${decodedToken}`, { cause: e }); } } private convertSelect>( select?: readonly TFields[], ): string | undefined { if (select) { return select.join(","); } return undefined; } private convertVectorQueryFields(fields?: SearchFieldArray): string | undefined { if (fields) { return fields.join(","); } return undefined; } private convertSearchFields(searchFields?: SearchFieldArray): string | undefined { if (searchFields) { return searchFields.join(","); } return undefined; } private convertOrderBy(orderBy?: string[]): string | undefined { if (orderBy) { return orderBy.join(","); } return undefined; } private convertQueryAnswers(answers?: QueryAnswer): BaseAnswers | undefined { if (!answers) { return undefined; } const config = []; const { answerType: output, count, threshold, maxAnswerLength } = answers; if (count) { config.push(`count-${count}`); } if (threshold !== undefined) { config.push(`threshold-${threshold}`); } if (maxAnswerLength) { config.push(`maxcharlength-${maxAnswerLength}`); } if (config.length) { return output + `|${config.join(",")}`; } return output; } private convertQueryCaptions(captions?: QueryCaption): BaseCaptions | undefined { if (!captions) { return undefined; } const config = []; const { captionType: output, highlight, maxCaptionLength } = captions; if (highlight !== undefined) { config.push(`highlight-${highlight}`); } if (maxCaptionLength) { config.push(`maxcharlength-${maxCaptionLength}`); } if (config.length) { return output + `|${config.join(",")}`; } return output; } private convertVectorQuery>(vectorQuery: T): GeneratedVectorQuery { switch (vectorQuery.kind) { case "text": { const { fields, ...restFields } = vectorQuery; return { ...restFields, fields: this.convertVectorQueryFields(fields), }; } case "vector": { return { ...vectorQuery, fields: this.convertVectorQueryFields(vectorQuery?.fields) }; } default: { logger.warning("Unknown vector query kind; sending without serialization"); return vectorQuery as any; } } } }