# @azure/search-documents 中文文档

规范地址：https://npmcn.com/package/%40azure/search-documents/

版本：13\.1\.0
npm 元数据更新时间：2026-11-11T00:22:39.823Z
中文译文更新时间：2026-11-11T00:25:01.213Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/search-documents
原文对照：https://npmcn.com/package/%40azure/search-documents/?lang=original
项目主页：https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search-documents/README.md
源码仓库：https://github.com/Azure/azure-sdk-for-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：14.8 MB，1172 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.0\.0
- 运行依赖：8 个
- 首次发布：2020-04-04T08:43:50.153Z
- 最新版本发布：2026-11-11T00:22:39.608Z
- 近 30 天下载量：2082677（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：414（近 12 个月 74 个）

## 中文简介

Azure客户端库使用AI搜索节点.js和浏览器.

## 安装

```sh
npm install @azure/search-documents
```

也可以使用：`pnpm add @azure/search-documents`、`yarn add @azure/search-documents`、`bun add @azure/search-documents`

## README

# Azure AI 搜索 JavaScript 客户端库

[Azure AI 搜索](https://learn.microsoft.com/azure/search/) (原名"Azure Conceptiontive Search")是一个由AI驱动的信息检索平台,帮助开发者建立丰富的搜索体验和基因化的AI应用,将大型语言模型与企业数据相结合.

Azure AI搜索服务非常适合下列应用情景:

-   将各种内容类型合并为单一的可搜索索引. 要填充索引,你可以推JSON文件 包含你的内容, 或者如果您的数据已经在Azure中,请创建索引器来拉取数据 自动.
-   附加到索引器上, 从图像创建可搜索的内容 和无结构的文档。 Azure AI Services的API 工具 用于内置的 OCR, 实体识别, 关键短语提取, 语言 检测 文本翻译 情绪分析 您还可以添加 自定义技能,用于整合您内容的外部处理 数据摄取.
-   在搜索客户端应用程序中,执行查询逻辑和用户体验 类似于商业网络搜索引擎和聊天式应用.

使用@azure/search-documents 客户端库以 :

-   使用向量、关键词和混合查询表提交查询.
-   执行对元数据、地理空间搜索、面相导航、, 或根据过滤标准缩小结果.
-   创建和管理搜索索引.
-   上传并更新搜索索引中的文档.
-   创建和管理将数据从Azure拖入索引的索引器.
-   创建并管理能将AI浓缩到数据摄取中的技能器.
-   创建和管理高级文本分析或多语言内容的分析器.
-   通过语义排名和评分剖析来优化结果,以在业务逻辑或新鲜度中考虑因素.

密钥链接 :

-   [源代码](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/search/search-documents/)
-   [软件包( NPM)](https://www.npmjs.com/package/@azure/search-documents)
-   [API 参考文件](https://learn.microsoft.com/javascript/api/@azure/search-documents)
-   [REST API 文档](https://learn.microsoft.com/rest/api/searchservice/)
-   [产品文档](https://learn.microsoft.com/azure/search/)
-   [样本](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search-documents/samples)

## 开始

### 安装 `@azure/search-documents` 软件包

```bash
npm install @azure/search-documents
```

第13.1.0版的目标是: `2026-10-01` 默认 GA 服务 API. 升级时从 第13.0.0版,审查 [GA 间断变化](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/search/search-documents/CHANGELOG.md#1310-2026-11-13)。 。 。 . 更新的 TypeScript 和 JavaScript 示例在 [样本/v13](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search-documents/samples/v13)。 。 。 .

### 目前得到支持的环境

-   [节点.js的LTS版本](https://github.com/nodejs/release#release-schedule)
-   Safari,Chrome,Microsoft Edge,和Firefox的最新版本.

看我们的 [支助政策](https://github.com/Azure/azure-sdk-for-js/blob/main/SUPPORT.md) 更多细节.

### 先决条件

-   一个 [Azure 订阅](https://azure.microsoft.com/free/)
-   A 类 [搜索服务](https://learn.microsoft.com/azure/search/search-create-service-portal)

要创建新搜索服务, 您可以使用 [Azure 门户网站](https://learn.microsoft.com/azure/search/search-create-service-portal), (中文(简体) ), [Azure 动力壳](https://learn.microsoft.com/azure/search/search-manage-powershell#create-or-delete-a-service),或 [阿苏尔CLI](https://learn.microsoft.com/cli/azure/search/service?view=azure-cli-latest#az-search-service-create)以下是使用Azure CLI为开始创建自由实例的例子:

```Powershell
az search service create --name <mysearch> --resource-group <mysearch-rg> --sku free --location westus
```

见 [选择定价等级](https://learn.microsoft.com/azure/search/search-sku-tier) 需要更多关于现有备选方案的信息.

### 认证客户端

要与搜索服务互动, 请创建适当的客户端 : `SearchClient` 用于文件, `SearchIndexClient` 指数和知识资源, `SearchIndexerClient` 数据来源/索引器/技能,或 `KnowledgeRetrievalClient` 用于知识库检索。 要抓捕客户对象,你需要 **结束点** 财务报告和审定财务报表 **Azure 角色** 或一个 **API 密钥**。您可以参考文档获取更多信息 [支持的认证方法](https://learn.microsoft.com/azure/search/search-security-overview#authentication) 与搜索服务.

#### 获取 API 密钥

API密钥可以是一种更容易开始的方法,因为它不需要事先存在的角色分配.

你可以得到这个 **结束点** 还有一个 **API 密钥** 从搜索服务中 [Azure 门户网站](https://portal.azure.com/)请参考 [文档](https://learn.microsoft.com/azure/search/search-security-api-keys) 用于指示如何获取 API 密钥.

或者,您可以使用以下选项: [阿苏尔CLI](https://learn.microsoft.com/cli/azure/) 命令从搜索服务中获取 API 密钥 :

```Powershell
az search admin-key show --resource-group <your-resource-group-name> --service-name <your-resource-name>
```

访问搜索服务的密钥有两种: **管理员** _(读-写)_ 财务报告和审定财务报表 **查询** _(只读)_ 键。 限制客户端应用程序的访问和操作对于保护您服务的搜索资产至关重要。 对来自客户端应用程序的任何查询,总是使用查询密钥而不是管理密钥.

_注意:上面的Azure CLI片段的例子检索到一个管理员密钥,因此更容易开始探索API,但应该谨慎管理._

一旦拥有了Api-key,可以使用如下:

```ts
import {
  SearchClient,
  AzureKeyCredential,
  SearchIndexClient,
  SearchIndexerClient,
  KnowledgeRetrievalClient,
} from "@azure/search-documents";

// To query and manipulate documents
const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

// To manage indexes and synonymmaps
const indexClient = new SearchIndexClient("<endpoint>", new AzureKeyCredential("<apiKey>"));

// To manage indexers, datasources and skillsets
const indexerClient = new SearchIndexerClient("<endpoint>", new AzureKeyCredential("<apiKey>"));

// To retrieve from a knowledge base
const knowledgeRetrievalClient = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  new AzureKeyCredential("<apiKey>"),
);
```

### 在国家云中认证

在a中认证 [国家云](https://learn.microsoft.com/azure/active-directory/develop/authentication-national-cloud),您需要在客户端配置中添加以下内容:

-   设定 `Audience` 内 `SearchClientOptions`

```ts
import { DefaultAzureCredential } from "@azure/identity";
import {
  SearchClient,
  KnownSearchAudience,
  SearchIndexClient,
  SearchIndexerClient,
  KnowledgeRetrievalClient,
} from "@azure/search-documents";

const credential = new DefaultAzureCredential({
  authorityHost: "https://login.chinacloudapi.cn",
});

// To query and manipulate documents
const searchClient = new SearchClient("<endpoint>", "<indexName>", credential, {
  audience: KnownSearchAudience.AzureChina,
});

// To manage indexes and synonymmaps
const indexClient = new SearchIndexClient("<endpoint>", credential, {
  audience: KnownSearchAudience.AzureChina,
});

// To manage indexers, datasources and skillsets
const indexerClient = new SearchIndexerClient("<endpoint>", credential, {
  audience: KnownSearchAudience.AzureChina,
});

// To retrieve from a knowledge base
const knowledgeRetrievalClient = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  credential,
  { audience: KnownSearchAudience.AzureChina },
);
```

## 关键概念

Azure AI搜索服务包含一个或多个索引,以JSON文档的形式提供可搜索数据的持久存储. _(如果你是全新的搜索者,你可以在索引和数据库表之间作一个非常粗略的类比. )_ @azure/search-documents 客户端库 通过四种主要客户类型来揭露这些资源上的操作.

-   `SearchClient` 帮助:
    
    -   [搜索中](https://learn.microsoft.com/azure/search/search-lucene-query-architecture) 使用 [向量查询](https://learn.microsoft.com/azure/search/vector-search-how-to-query), (中文(简体) ), [关键字查询](https://learn.microsoft.com/azure/search/search-query-create) 财务报告和审定财务报表 [混合查询](https://learn.microsoft.com/azure/search/hybrid-search-how-to-query)
    -   [矢量查询过滤器](https://learn.microsoft.com/azure/search/vector-search-filters) 财务报告和审定财务报表 [文本查询过滤器](https://learn.microsoft.com/azure/search/search-filters)
    -   [语义排名](https://learn.microsoft.com/azure/search/semantic-how-to-query-request) 财务报告和审定财务报表 [评分配置](https://learn.microsoft.com/azure/search/index-add-scoring-profiles) 提高相关性
    -   [自动完成](https://learn.microsoft.com/rest/api/searchservice/autocomplete) 基于索引中文档的部分输入搜索名词
    -   [建议](https://learn.microsoft.com/rest/api/searchservice/suggestions) 作为用户类型的文档中最有可能匹配的文本
    -   [添加、更新或删除文档](https://learn.microsoft.com/rest/api/searchservice/addupdate-or-delete-documents) 来自索引的文档
-   `SearchIndexClient` 允许您:
    
    -   [创建、删除、更新或配置搜索索引](https://learn.microsoft.com/rest/api/searchservice/index-operations)
    -   [声明用于扩展或重写查询的自定义同义字地图](https://learn.microsoft.com/rest/api/searchservice/synonym-map-operations)
    -   管理知识库、知识来源和上传到文件知识来源的文件
-   `SearchIndexerClient` 允许您:
    
    -   [启动索引器自动爬行数据源](https://learn.microsoft.com/rest/api/searchservice/indexer-operations)
    -   [定义 AI 授权技能器来转换和丰富您的数据](https://learn.microsoft.com/rest/api/searchservice/skillset-operations)
-   `KnowledgeRetrievalClient` 允许您:
    
    -   从知识库取用并检查其活动和参考资料
    -   作为服务器发送事件流出输入的检索进度和终端结果

**说明**: 浏览器的使用取决于选择的搜索操作和资源是否配置了 CORS 。 文件知识源和知识库暴露了CORS的设置,但许多管理操作都是为了被信任的服务器侧应用.

## TypeScript/JavaScript 特定概念

### 文档

存储在搜索索引中的项目 。 此文档的形状在索引中使用 `fields` 属性。 每个 `SearchField` 具有名称、数据类型和额外元数据,如可以搜索或过滤.

### 倾斜

通常你只会希望 [显示搜索结果的子集](https://learn.microsoft.com/azure/search/search-pagination-page-layout#total-hits-and-page-counts) 一次给用户。 为了支持这一点,你可以使用 `top`, (中文(简体) ), `skip` 财务报告和审定财务报表 `includeTotalCount` 参数,以在搜索结果上提供一页的经验.

### 文档字段编码

[支持的数据类型](https://learn.microsoft.com/rest/api/searchservice/Supported-data-types) 在索引中,在 API 请求/答复中将 JSON 类型映射。 联合来文的客户图书馆基本上保持不变,但有一些例外:

-   `Edm.DateTimeOffset` 改为联合来文 `Date`。 。 。 .
-   `Edm.GeographyPoint` 转换为 a `GeographyPoint` 类型由客户端库导出.
-   联合国的特殊价值 `number` 类型( NAN, Infinity, - Infinity) 在 REST API 中被串列为字符串,但被转换回 `number` 在客户端图书馆旁.

**说明**:数据类型根据值来转换,而不是指数图中的字段类型. 这意味着,如果您有ISO8601 Date字符串(如"2020-03-06T18:48:27.896Z")作为一个字段的值,那么无论您如何将它存储在您的计划中,它都会被转换为Date.

## 实例

以下例子说明了基本情况――请 [看看我们的样本](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search-documents/samples) 对于更多.

-   [创建索引](https://npmcn.com/package/%40azure/search-documents/#readme-create-an-index)
-   [从索引中获取特定文档](https://npmcn.com/package/%40azure/search-documents/#readme-retrieve-a-specific-document-from-an-index)
-   [将文档添加到索引中](https://npmcn.com/package/%40azure/search-documents/#readme-adding-documents-into-an-index)
-   [对文档进行搜索](https://npmcn.com/package/%40azure/search-documents/#readme-perform-a-search-on-documents)
    -   [使用类型脚本查询](https://npmcn.com/package/%40azure/search-documents/#readme-querying-with-typescript)
    -   [使用 OData 过滤器查询](https://npmcn.com/package/%40azure/search-documents/#readme-querying-with-odata-filters)
    -   [询问方方面面](https://npmcn.com/package/%40azure/search-documents/#readme-querying-with-facets)
-   [从知识库获取](https://npmcn.com/package/%40azure/search-documents/#readme-retrieve-from-a-knowledge-base)
-   [查找类似的文档](https://npmcn.com/package/%40azure/search-documents/#readme-find-similar-documents)
-   [配置知识库](https://npmcn.com/package/%40azure/search-documents/#readme-configure-a-knowledge-base)
-   [列出带有调用控制的资源](https://npmcn.com/package/%40azure/search-documents/#readme-list-resources-with-paging-controls)
-   [配置 SharePoint 文档权限](https://npmcn.com/package/%40azure/search-documents/#readme-configure-sharepoint-document-permissions)
-   [索引 SharePoint 网站内容](https://npmcn.com/package/%40azure/search-documents/#readme-index-sharepoint-site-content)
-   [刷新不变的 ADLS Gen2 权限](https://npmcn.com/package/%40azure/search-documents/#readme-refresh-unchanged-adls-gen2-permissions)
-   [流取知识](https://npmcn.com/package/%40azure/search-documents/#readme-stream-knowledge-retrieval)
-   [检查文件知识源容量](https://npmcn.com/package/%40azure/search-documents/#readme-check-file-knowledge-source-capacity)
-   [上传并更新一个知识源文件](https://npmcn.com/package/%40azure/search-documents/#readme-upload-and-update-a-knowledge-source-file)

下面的例子使用马厩 `2026-10-01` 服务 API,是客户端的默认值. 它们扩展了现有的索引、索引器、知识源和检索工作流程,而不是 需要一组单独的客户.

对于完整的可运行工作流程 [抽样来源](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search-documents/samples-dev) 还覆盖索引化的 SQL 内容 列、 私人摄入和服务选择分析器、 内容理解图像描述 模型和语义分解,服务/索引运行时预算,以及搜索自有引用 URL. 可选资源设置和先决条件列于 [样本.env](https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/search/search-documents/sample.env)。 。 。 .

### 查找类似的文档

使用 `moreLikeThis` 带有已存在的文档密钥并省略搜索文本。 选择可搜索的顶级 明确文本字段:此操作不支持复杂的字段。 索引必须包含 返回有用匹配的其他文档.

```ts
import { SearchClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchClient("<endpoint>", "<indexName>", new DefaultAzureCredential());

const response = await client.search(undefined, {
  moreLikeThis: "1",
  searchFields: ["hotelName", "description"],
  select: ["hotelId", "hotelName"],
  top: 5,
});
for await (const result of response.results) {
  console.log(result.document);
}
```

### 配置知识库

使用配置有语义搜索功能的集合知识源 。 部署已配置的聊天模式 并授予搜索服务管理的身份 **认知服务 OpenAI 用户** azure OpenAI 地图 资源。 部署名称和模型名称是独立的设置;部署可以有一个自定义名称. 打电话的人需要 **搜索服务撰稿人** 管理知识库.

存储指令、输出模式和推理工作可以更新而不替换 知识的来源. `answerSynthesis` 使用所配置的模型; `extractiveData` 已提取的返回 内容不合成一个答案。 GA 推理模式为 `minimal`, (中文(简体) ), `low`,以及 `medium`。 。 。 . 明确请求意图绕过模型查询规划.

```ts
import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());

const knowledgeBase = await client.createKnowledgeBase({
  name: "hotel-knowledge-base",
  knowledgeSources: [{ name: "<existingKnowledgeSourceName>" }],
  models: [
    {
      kind: "azureOpenAI",
      azureOpenAIParameters: {
        resourceUrl: "<azureOpenAIEndpoint>",
        deploymentId: "<chatDeploymentName>",
        modelName: "gpt-5.4-mini",
      },
    },
  ],
  retrievalReasoningEffort: { kind: "low" },
  outputMode: "answerSynthesis",
  retrievalInstructions: "Prioritize hotel amenities and pricing information.",
  answerInstructions: "Answer concisely and cite the supporting sources.",
});

knowledgeBase.outputMode = "extractiveData";
await client.createOrUpdateKnowledgeBase(knowledgeBase);
```

### 使用 Page 控制列表资源

按名称前缀过滤初始列表,并让SDK遵循不透明的延续链接. 这个 `SearchIndexClient` 寻呼器曝光 `byPage()`。现有的同义词图、索引器、数据源和技能集 收集所有页面后继续返回数组; 协议客户端 曝光相应的被页操作.

```ts
import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());

for await (const page of client
  .listIndexes({
    search: "hotel",
    searchType: "prefix",
    pageSize: 10,
  })
  .byPage()) {
  console.log(page.map((index) => index.name));
}
```

### 配置共享点文档权限

在创建索引前注册SharePoint连接器应用程序及其联邦证书. `applicationId` 财务报告和审定财务报表 `federatedCredentialId` 需要一起进行; `tenantId` 不同时可以提供 从搜索服务租户。 打电话的人需要 **搜索服务撰稿人**。 。 。 .

组织范围共享赠款用途 `orgLink:<tenantId>` 输入 `userIds` 权限字段. `organizationAccessExpiration` 识别过期时间戳。 最多一个顶级 `Edm.DateTimeOffset` 字段可能会启用它。 服务验证用户的租户和时间戳 权限过滤查询; 仅声明这些字段不能允许访问.

```ts
import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());

await client.createIndex({
  name: "sharepoint-permissions",
  permissionFilterOption: "enabled",
  sharePointConnectorAppRegistration: {
    applicationId: "<applicationId>",
    federatedCredentialId: "<federatedCredentialId>",
  },
  fields: [
    { name: "id", type: "Edm.String", key: true },
    { name: "content", type: "Edm.String", searchable: true },
    {
      name: "userIds",
      type: "Collection(Edm.String)",
      filterable: true,
      permissionFilter: "userIds",
    },
    {
      name: "organizationLinkExpiresAt",
      type: "Edm.DateTimeOffset",
      organizationAccessExpiration: true,
    },
  ],
});
```

### 索引共享点网站内容

GA 共享点范围包括 `AllSiteLists`, (中文(简体) ), `AllSitePages`,以及 `AllSiteContent`,此外 现有的库范围。 通过环境提供连接器连接字符串 而不是在源代码中嵌入应用程序秘密.

```ts
import { SearchIndexClient, KnownIndexedSharePointContainerName } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());
const connectionString = process.env.SHAREPOINT_CONNECTION_STRING;
if (!connectionString) {
  throw new Error("Set SHAREPOINT_CONNECTION_STRING before creating the knowledge source.");
}

await client.createKnowledgeSource({
  name: "sharepoint-site",
  kind: "indexedSharePoint",
  indexedSharePointParameters: {
    connectionString,
    containerName: KnownIndexedSharePointContainerName.AllSiteContent,
  },
});
```

### 刷新未更改的 ADLS Gen2 权限

对于一个现有的 ADLS Gen2 索引器, 摄取权限, `refreshAllAcls` 刷新权限 元数据,即使文档内容没有改变。 默认为 `true`,最多运行一次 24小时,不重新处理内容或浓缩。 准备吧 `false` 以禁用刷新.

```ts
import { SearchIndexerClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexerClient("<endpoint>", new DefaultAzureCredential());
const indexer = await client.getIndexer("<existingAdlsGen2Indexer>");

indexer.parameters = {
  ...indexer.parameters,
  configuration: {
    ...indexer.parameters?.configuration,
    refreshAllAcls: true,
  },
};
await client.createOrUpdateIndexer(indexer);
```

### 从知识库获取

```ts
import {
  KnowledgeRetrievalClient,
  AzureKeyCredential,
  KnownKnowledgeRetrievalReasoningEffortKind,
} from "@azure/search-documents";

const client = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  new AzureKeyCredential("<apiKey>"),
);

const response = await client.retrieve({
  intents: [{ type: "semantic", search: "What information is available?" }],
  retrievalReasoningEffort: { kind: KnownKnowledgeRetrievalReasoningEffortKind.Low },
  includeActivity: true,
});

console.log(response.response);
```

### 流取知识

键入的传动器使用一个 SSE 连接,处理框架和心跳,然后停止 `response.completed` 或者说 `error`. 完成情况可以全面报告`200`)或部分(`206`)结果. 打电话 `controller.abort()` 取消请求。 未知事件名称被忽略; 符号- delta 事件 不属于此 API 。 活动关联和取消处理参见流出样本.

```ts
import { KnowledgeRetrievalClient, AzureKeyCredential } from "@azure/search-documents";

const client = new KnowledgeRetrievalClient(
  "<endpoint>",
  "<knowledgeBaseName>",
  new AzureKeyCredential("<apiKey>"),
);

const controller = new AbortController();
for await (const event of await client.retrieveStream(
  {
    intents: [{ type: "semantic", search: "Summarize the indexed information." }],
    includeActivity: true,
  },
  { abortSignal: controller.signal },
)) {
  if (event.event === "activity.completed") {
    console.log(`Activity ${event.data.id} took ${event.data.elapsedInMs}ms`);
  } else if (event.event === "response.completed") {
    console.log(event.data.statusCode === 206 ? "Partial results" : "Complete results");
    console.log(event.data.response.response);
  } else if (event.event === "error") {
    throw new Error(event.data.error.message);
  }
}
```

### 上传并更新知识源文件

```ts
import { SearchIndexClient, AzureKeyCredential } from "@azure/search-documents";

const client = new SearchIndexClient("<endpoint>", new AzureKeyCredential("<apiKey>"));
const body = {
  metadata: { fileName: "manuals/example.txt", metadata: { category: "manual" } },
  content: {
    contents: new TextEncoder().encode("Azure AI Search retrieves relevant information."),
    contentType: "text/plain",
    filename: "example.txt",
  },
};

const uploaded = await client.uploadKnowledgeSourceFileMultipart("<knowledgeSourceName>", body);
if (!uploaded.fileId) {
  throw new Error("The service did not return an uploaded file ID.");
}

await client.updateKnowledgeSourceFile("<knowledgeSourceName>", uploaded.fileId, {
  ...body,
  metadata: { ...body.metadata, metadata: { category: "updated-manual" } },
});
for await (const file of client.listKnowledgeSourceFiles("<knowledgeSourceName>", {
  prefix: "manuals/",
  pageSize: 10,
})) {
  console.log(file.fileName, file.parsingMode, file.extractionMode);
}
```

### 检查文件知识源能力

文件知识源的状态曝光 `fileCapacity` (单位:千美元)`KnowledgeSourceFileCapacity`与 剩余文件计数和每个文件字节限制。 上传前检查; 其他知识源类型 不报告此字段。 需要直接上传 **搜索服务撰稿人**,搜索服务 管理身份需求 **认知服务 OpenAI 用户** 在嵌入资源上.

```ts
import { SearchIndexClient } from "@azure/search-documents";
import { DefaultAzureCredential } from "@azure/identity";

const client = new SearchIndexClient("<endpoint>", new DefaultAzureCredential());
const status = await client.getKnowledgeSourceStatus("<fileKnowledgeSourceName>");

if (!status.fileCapacity) {
  throw new Error("The knowledge source did not report File upload capacity.");
}
console.log(`Remaining files: ${status.fileCapacity.remainingFileCount}`);
console.log(`Maximum file size: ${status.fileCapacity.maxFileSizeBytes} bytes`);
```

### 创建索引

```ts
import { SearchIndexClient, AzureKeyCredential } from "@azure/search-documents";

const indexClient = new SearchIndexClient("<endpoint>", new AzureKeyCredential("<apiKey>"));

const result = await indexClient.createIndex({
  name: "example-index",
  fields: [
    {
      type: "Edm.String",
      name: "id",
      key: true,
    },
    {
      type: "Edm.Double",
      name: "awesomenessLevel",
      sortable: true,
      filterable: true,
      facetable: true,
    },
    {
      type: "Edm.String",
      name: "description",
      searchable: true,
    },
    {
      type: "Edm.ComplexType",
      name: "details",
      fields: [
        {
          type: "Collection(Edm.String)",
          name: "tags",
          searchable: true,
        },
      ],
    },
    {
      type: "Edm.Int32",
      name: "hiddenWeight",
      hidden: true,
    },
  ],
});

console.log(`Index created with name ${result.name}`);
```

### 从索引中获取特定文档

特定文档可按其主要关键值检索:

```ts
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const result = await searchClient.getDocument("1234");
```

### 将文档添加到索引

您可以在批次内将多个文档上传到索引中:

```ts
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const uploadResult = await searchClient.uploadDocuments([
  // JSON objects matching the shape of the client's index
  {},
  {},
  {},
]);
for (const result of uploadResult.results) {
  console.log(`Uploaded ${result.key}; succeeded? ${result.succeeded}`);
}
```

### 对文档进行搜索

要列出特定查询的所有结果, 您可以使用 `search` 使用搜索字符串 [简单的查询语法](https://learn.microsoft.com/azure/search/query-simple-syntax)数字 :

```ts
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search("wifi -luxury");
for await (const result of searchResults.results) {
  console.log(result);
}
```

更高级的搜索使用 [Lucene 语法](https://learn.microsoft.com/azure/search/query-lucene-syntax),指定 `queryType` 将会是 `full`数字 :

```ts
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search('Category:budget AND "recently renovated"^3', {
  queryType: "full",
  searchMode: "all",
});
for await (const result of searchResults.results) {
  console.log(result);
}
```

#### 使用类型脚本查询

在类型脚本中, `SearchClient` 取一个通用参数,即索引文档的模型形状。 这样您就可以对返回的字段进行强烈的打字检查。 TypeScript 在指定一个字段时也可以检查返回的字段 `select` 参数.

```ts
import { SearchClient, AzureKeyCredential, SelectFields } from "@azure/search-documents";

// An example schema for documents in the index
interface Hotel {
  hotelId?: string;
  hotelName?: string | null;
  description?: string | null;
  descriptionVector?: Array<number>;
  parkingIncluded?: boolean | null;
  lastRenovationDate?: Date | null;
  rating?: number | null;
  rooms?: Array<{
    beds?: number | null;
    description?: string | null;
  }>;
}

const searchClient = new SearchClient<Hotel>(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search("wifi -luxury", {
  // Only fields in Hotel can be added to this array.
  // TS will complain if one is misspelled.
  select: ["hotelId", "hotelName", "rooms/beds"],
});

// These are other ways to declare the correct type for `select`.
const select = ["hotelId", "hotelName", "rooms/beds"] as const;
// This declaration lets you opt out of narrowing the TypeScript type of your documents,
// though the AI Search service will still only return these fields.
const selectWide: SelectFields<Hotel>[] = ["hotelId", "hotelName", "rooms/beds"];
// This is an invalid declaration. Passing this to `select` will result in a compiler error
// unless you opt out of including the model in the client constructor.
const selectInvalid = ["hotelId", "hotelName", "rooms/beds"];

for await (const result of searchResults.results) {
  // result.document has hotelId, hotelName, and rooms with only the beds property.
  // Trying to access result.document.description would emit a TS error.
  console.log(result.document.hotelName);
}
```

#### 使用 OData 过滤器查询

使用 `filter` 查询参数允许您使用语法查询索引 [OData $filter 表达式](https://learn.microsoft.com/azure/search/search-query-odata-filter)。 。 。 .

```ts
import { SearchClient, AzureKeyCredential, odata } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const baseRateMax = 200;
const ratingMin = 4;
const searchResults = await searchClient.search("WiFi", {
  filter: odata`Rooms/any(room: room/BaseRate lt ${baseRateMax}) and Rating ge ${ratingMin}`,
  orderBy: ["Rating desc"],
  select: ["hotelId", "hotelName", "Rating"],
});
for await (const result of searchResults.results) {
  // Each result will have "HotelId", "HotelName", and "Rating"
  // in addition to the standard search result property "score"
  console.log(result);
}
```

#### 用向量查询

可以使用 `vector` 搜索参数。 见 [查询向量](https://learn.microsoft.com/azure/search/vector-search-how-to-query) 财务报告和审定财务报表 [过滤向量查询](https://learn.microsoft.com/azure/search/vector-search-filters) 更多信息.

```ts
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const queryVector: number[] = [
  // Embedding of the query "What are the most luxurious hotels?"
];
const searchResults = await searchClient.search("*", {
  vectorSearchOptions: {
    queries: [
      {
        kind: "vector",
        vector: queryVector,
        fields: ["descriptionVector"],
        kNearestNeighborsCount: 3,
      },
    ],
  },
});
for await (const result of searchResults.results) {
  // These results are the nearest neighbors to the query vector
  console.log(result);
}
```

#### 询问方方面面

[面额](https://learn.microsoft.com/azure/search/search-filters-facets) 用于帮助应用程序的用户按照预配置的尺寸改进搜索. [面额语法](https://learn.microsoft.com/rest/api/searchservice/search-documents#facetstring-zero-or-more) 提供了排序和桶面值的选项.

```ts
import { SearchClient, AzureKeyCredential } from "@azure/search-documents";

const searchClient = new SearchClient(
  "<endpoint>",
  "<indexName>",
  new AzureKeyCredential("<apiKey>"),
);

const searchResults = await searchClient.search("WiFi", {
  facets: ["category,count:3,sort:count", "rooms/baseRate,interval:100"],
});
console.log(searchResults.facets);
```

获取结果时, a `facets` 属性将显示每个面桶中的结果数量。 这可以用来推动改进(例如,发布后续搜索,对系统进行过滤) `Rating` 大于或等于3和小于4)

## 解决问题

### 日志

启用记录有助于发现有关失败的有用信息。 为了查看 HTTP 请求和回复的日志,设置 `AZURE_LOG_LEVEL` 环境变量改为 `info`。或者,可以在运行时拨打 `setLogLevel` 输入 `@azure/logger`数字 :

```ts
import { setLogLevel } from "@azure/logger";

setLogLevel("info");
```

关于如何启用日志的更详细指示,您可以查看 [@ azure/ logger 包文件](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/core/logger)。 。 。 .

## 今后的步骤

-   [继续搜索文档和样本](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/search/search-documents/samples)
-   [更多信息: Azure AI搜索服务](https://learn.microsoft.com/azure/search/search-what-is-azure-search)

## 捐款

如果您想为图书馆捐钱 请读一下 [贡献指南](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) 学习如何构建和测试密码.

该项目欢迎各方的贡献和建议。 大部分捐款都要求你同意一项贡献者许可协议(CLA),声明你有权并且实际上确实给了我们使用你的捐款的权利. 详情请访问 [cla.microsoft.com (中文(简体) )](https://cla.microsoft.com/)。 。 。 .

该项目通过了 [Microsoft 开源行为守则](https://opensource.microsoft.com/codeofconduct/)。更多信息见 [《行为守则》](https://opensource.microsoft.com/codeofconduct/faq/) 或联系人 [打开码@ microsoft.com](mailto:opencode@microsoft.com) 并附上任何其他问题或评论.

## 相关项目

-   [微软 Azure SDK 用于 JavaScript](https://github.com/Azure/azure-sdk-for-js)

## 常见问题

### @azure/search-documents 是什么？

Azure客户端库使用AI搜索节点\.js和浏览器\.

### 如何安装 @azure/search-documents？

在项目目录运行 npm install @azure/search-documents，或使用 pnpm add / yarn add / bun add。

### @azure/search-documents 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @azure/search-documents 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @azure/search-documents 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @azure/search-documents 可以商用吗？

@azure/search-documents 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @azure/search-documents 的下载量有多少？

根据 npm 官方下载统计，@azure/search-documents 在 2026/10/08 – 2026/11/06 这 30 天内被下载 2,082,677 次，日均约 69,423 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @azure/search-documents 还在维护吗？

最新版本 13\.1\.0 发布于 2026/11/11（今天）；至今共发布 414 个版本，其中过去 12 个月发布了 74 个；首次发布于 2020/04/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

