google-api-nodejs-client 实战:用 Cloud Search API 在 Node.js 中索引并搜索 Google Workspace 数据
google-api-nodejs-client 实战:用 Cloud Search API 在 Node.js 中索引并搜索 Google Workspace 数据
本篇文章以 src/apis/cloudsearch/README.md 为核心,结合 google-api-nodejs-client 仓库中自动生成的 Cloud Search API 客户端源码(v1.ts、index.ts),完整讲解如何安装、认证并调用 Cloud Search API:包括把非 Google Workspace 的第三方数据索引进 Cloud Search、通过 Query API 检索 Workspace 与第三方数据,以及数据源(Datasource)与搜索应用(Search Application)的配置管理。读完本文,你将掌握 @googleapis/cloudsearch 独立包的安装方式、OAuth 作用域配置、索引(indexing)与搜索(query)两大核心调用链,并能直接上手编写可运行的 Node.js 代码。
Cloud Search API 是什么
Cloud Search 为 Google Workspace 数据提供云上搜索能力,而 Cloud Search API 的核心价值在于:允许开发者将非 Google Workspace 的第三方数据索引到 Cloud Search 中,从而让 Gmail、Google Drive 等原生数据与业务系统数据(如 CRM 记录、内部文档、工单)在同一个搜索体验下被统一检索。这一点在 src/apis/cloudsearch/README.md 中直接定义为该 API 的定位:
Cloud Search provides cloud-based search capabilities over Google Workspace data. The Cloud Search API allows indexing of non-Google Workspace data into Cloud Search.
在 google-api-nodejs-client 仓库中,Cloud Search 客户端位于 src/apis/cloudsearch/,主要由三部分组成:
- index.ts:客户端入口,负责注册版本并导出
Cloudsearch类与auth实例; - v1.ts:由 Google API Discovery 文档自动生成的全部资源类、方法重载与 TypeScript Schema 定义(共 1 万余行);
- package.json 与 CHANGELOG.md:包元数据与版本演进记录。
安装与引入
方式一:独立子包(推荐)
Cloud Search 客户端同时以独立子包发布,按 src/apis/cloudsearch/README.md 的 Installation 说明安装:
$ npm install @googleapis/cloudsearch
该独立包当前版本为 26.0.1(见 package.json),运行时依赖 googleapis-common ^9.0.0,并要求 Node.js 版本不低于 22.0.0(engines.node 字段)。使用方式:
const {cloudsearch} = require('@googleapis/cloudsearch');
const cloudsearchClient = cloudsearch('v1');
方式二:统一 googleapis 包
在安装整个 googleapis 主包的前提下,也可以从总入口按版本取用:
const {google} = require('googleapis');
const cloudsearch = google.cloudsearch('v1');
这一写法正是 v1.ts 中每个方法示例代码的统一开头(见 v1.ts 的 @example)。两种方式底层都走 index.ts 中的 cloudsearch() 工厂函数,其签名支持两种调用形态:
export function cloudsearch(version: 'v1'): cloudsearch_v1.Cloudsearch;
export function cloudsearch(options: cloudsearch_v1.Options): cloudsearch_v1.Cloudsearch;
即既可以传 'v1' 字符串,也可以传一个带 version: 'v1' 的全局配置对象。入口通过 getAPI('cloudsearch', versionOrOptions, VERSIONS, this) 完成分发,VERSIONS 表目前仅注册 v1 一个版本:
export const VERSIONS = {
v1: cloudsearch_v1.Cloudsearch,
};
同时入口导出了 AuthPlus 类型的 auth 实例,供需要单独管理认证令牌的场景使用。
认证与授权:作用域与账号类型
Cloud Search API 的所有请求都需要认证。v1.ts 中生成的每个方法示例都使用 google.auth.GoogleAuth 统一获取认证客户端,例如 query.search 的标准写法:
const auth = new google.auth.GoogleAuth({
scopes: [
'https://www.googleapis.com/auth/cloud_search',
'https://www.googleapis.com/auth/cloud_search.query',
],
});
const authClient = await auth.getClient();
google.options({auth: authClient});
从 v1.ts 各资源方法的示例注释中可以确认,Cloud Search API 实际使用的作用域(Scope)集合如下:
| 作用域 | 用途 |
|---|---|
https://www.googleapis.com/auth/cloud_search |
全局访问(多数接口的默认作用域) |
https://www.googleapis.com/auth/cloud_search.query |
执行搜索、自动补全、移除用户活动等查询类接口 |
https://www.googleapis.com/auth/cloud_search.indexing |
索引导入类接口(如 media.upload) |
https://www.googleapis.com/auth/cloud_search.settings |
管理数据源与搜索应用设置 |
https://www.googleapis.com/auth/cloud_search.settings.indexing |
数据源 Schema 管理(如 deleteSchema) |
https://www.googleapis.com/auth/cloud_search.debug |
调试类接口(如 debug.datasources.items.checkAccess) |
账号类型限制
从各方法的 **Note:** 注释中可以归纳出两条关键的账号约束,这在设计系统时需要特别注意:
- 查询类接口(Query API)要求标准终端用户账号:
query.search、query.suggest、query.removeActivity的注释均明确说明 service account 不能直接执行 Query API 请求。若必须用服务账号执行查询,需配置 Google Workspace 域级委托(domain-wide delegation of authority)。 - 索引导入与调试类接口要求服务账号或管理员账号:
media.upload注释要求 service account;indexing.datasources.deleteSchema要求 admin 或 service account;debug.datasources.items.checkAccess要求 admin 账号。
另外,v1.ts 的 StandardParameters(v1.ts)表明每个请求还支持 auth(OAuth2Client / JWT / Compute / UserRefreshClient / BaseExternalAccountClient / GoogleAuth 或 API Key)、key(API Key)、access_token、fields(部分响应字段选择)、quotaUser、uploadType/upload_protocol 等标准参数,与 googleapis-common 的全局选项体系一致。
客户端资源结构:顶层 8 大资源
Cloudsearch 类(v1.ts)在构造函数中挂载了 8 个顶层资源,对应 Cloud Search API 的功能域:
this.debug = new Resource$Debug(this.context); // 调试:检查 item 访问权限、查看未映射 ID
this.indexing = new Resource$Indexing(this.context); // 索引:数据源 Schema 与 Items 管理
this.media = new Resource$Media(this.context); // 媒体上传:大内容流式上传
this.operations = new Resource$Operations(this.context); // 长时操作:获取/取消/列举
this.query = new Resource$Query(this.context); // 查询:search / suggest / removeActivity
this.settings = new Resource$Settings(this.context); // 设置:数据源与搜索应用
this.stats = new Resource$Stats(this.context); // 统计:index / query / session / user 维度
this.v1 = new Resource$V1(this.context); // 顶层方法(如 initializeCustomer 等)
从源码结构看(v1.ts),这些资源继续向下细分,形成如下的完整调用树:
debug.datasources.items:提供checkAccess,检查 item 是否可被指定 principal(用户/群组/域名)访问,返回{hasAccess: boolean};debug.datasources.items.unmappedids、debug.identitysources.items.unmappedids:处理身份映射失败的未映射 ID;indexing.datasources:管理数据源 Schema(如deleteSchema,返回Schema$Operation);indexing.datasources.items:item 的索引导入、查询、删除等核心操作;query.sources:列举可用搜索源;settings.datasources/settings.searchapplications:数据源与搜索应用的创建、读取、列举、更新等管理;stats.index.datasources、stats.query.searchapplications、stats.session.searchapplications、stats.user.searchapplications:各维度统计。
所有方法统一通过 createAPIRequest 发送请求,每个方法都基于同一模板,例如 query.removeActivity 的请求构造(v1.ts):
const rootUrl = options.rootUrl || 'https://cloudsearch.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/query:removeActivity').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST',
apiVersion: '',
},
options
),
params,
requiredParams: [],
pathParams: [],
context: this.context,
};
return createAPIRequest<Schema$RemoveActivityResponse>(parameters);
即所有请求默认指向 https://cloudsearch.googleapis.com/(rootUrl),同时支持通过 options 覆盖 rootUrl 或指定流式(StreamMethodOptions)与回调(BodyResponseCallback)两种调用方式。
索引导入:把第三方数据写入 Cloud Search
Item 数据模型
Cloud Search 以 Item 为最小索引单元。v1.ts 中的 Schema$Item(v1.ts)核心字段如下:
| 字段 | 说明 |
|---|---|
name |
item 名称,格式 datasources/{source_id}/items/{item_id},必填,最长 1536 字符 |
acl |
该 item 的访问控制列表(Schema$ItemAcl) |
content |
要被索引、可被全文检索的 item 内容(Schema$ItemContent) |
itemType |
item 类型 |
metadata |
元数据信息(Schema$ItemMetadata) |
payload |
connector 可为 item 保存的附加状态,最长 10000 字节 |
queue |
item 所属队列名,最长 100 字符 |
status |
item 状态,只读输出字段(Schema$ItemStatus) |
发起索引请求
索引请求体由 Schema$IndexItemRequest(v1.ts)定义:
export interface Schema$IndexItemRequest {
connectorName?: string | null; // 格式: datasources/{source_id}/connectors/{ID}
debugOptions?: Schema$DebugOptions; // 调试选项
indexItemOptions?: Schema$IndexItemOptions;
item?: Schema$Item; // 要索引的 item
mode?: string | null; // 必填,RequestMode
}
其中 mode(RequestMode)是必填字段,常见取值包括同步/异步索引模式,用于控制索引请求以何种方式返回结果。索引调用形如:
const res = await cloudsearch.indexing.datasources.items.index({
name: 'datasources/my-datasource/items/my-item',
requestBody: {
item: {
name: 'datasources/my-datasource/items/my-item',
itemType: 'CONTENT_ITEM',
content: {inlineContent: '...', contentType: 'text/plain'},
metadata: {title: '...', sourceRepositoryUrl: '...'},
acl: {...},
},
mode: 'SYNCHRONOUS',
connectorName: 'datasources/my-datasource/connectors/my-connector',
},
});
大文件上传的三步流程
对于无法内联进索引请求(inline)的大内容,v1.ts 中 media.upload 的注释给出了官方推荐的三步式 content connector 流程:
- 调用
indexing.datasources.items.upload,传入 item 名称以开启上传会话,并取回UploadItemRef; - 调用
media.upload,以流式请求上传内容,复用第 1 步UploadItemRef中的资源名; - 调用
indexing.datasources.items.index完成索引,用第 1 步的UploadItemRef填充ItemContent。
media.upload 的示例代码如下(v1.ts):
const res = await cloudsearch.media.upload({
resourceName: 'datasources/my-datasource/items/my-item',
requestBody: {resourceName: 'datasources/my-datasource/items/my-item'},
media: {
mimeType: 'application/pdf',
body: 'placeholder-value', // 实际应为可读流或 Buffer
},
});
该接口需要 service account 执行,并依赖 cloud_search / cloud_search.indexing 作用域。
执行搜索:Query API 核心调用
search:最相关的搜索结果
query.search 是 Cloud Search 的核心查询方法,其注释明确:结果既可来自 Gmail、Google Drive 等 Workspace 应用,也可来自你从第三方索引进来的数据。请求体由 Schema$SearchRequest(v1.ts)定义,关键参数:
| 参数 | 说明 |
|---|---|
query |
原始查询字符串,支持 Cloud Search 的搜索运算符语法 |
dataSourceRestrictions |
限定查询的数据源;不指定时使用当前搜索应用的全部数据源 |
pageSize |
每页结果数,有效范围 1–100(含),默认 10;当请求超过 2000 条结果时最小值提高到 50 |
start |
结果起始下标,用于分页 |
sortOptions |
排序选项 |
facetOptions |
分面(facet)聚合选项 |
requestOptions |
请求级选项,如搜索应用与用户时区 |
queryInterpretationOptions |
用户查询意图解释选项 |
contextAttributes |
用于调整结果排名的上下文属性,最多 10 个元素 |
调用示例(取自 v1.ts 的生成代码):
const res = await cloudsearch.query.search({
requestBody: {
query: 'my_query',
pageSize: 20,
start: 0,
dataSourceRestrictions: [{source: {name: 'datasources/my-datasource'}}],
requestOptions: {searchApplicationId: 'searchapplications/my-app'},
},
});
console.log(res.data);
响应由 Schema$SearchResponse(v1.ts)定义,包含 results(结果列表)、resultCountEstimate(估算结果数)、resultCountExact(精确结果数)、hasMoreResults(是否还有更多)、facetResults(分面结果)、spellResults(拼写建议)、structuredResults(结构化结果)、queryInterpretation(查询意图解释结果)以及 debugInfo/errorInfo 等字段。分页可基于 hasMoreResults 与 resultCountEstimate 持续累加 start 直到取完。
suggest:输入即补全
query.suggest 为搜索框提供自动补全建议,请求体仅需 query、dataSourceRestrictions 与 requestOptions,响应返回 suggestResults 数组。与 search 一样,需要标准终端用户账号(或配置域级委托的服务账号),作用域为 cloud_search / cloud_search.query。
removeActivity:移除用户活动记录
query.removeActivity 用于移除某用户被记录的活动,源码注释标明"目前仅用于 Chat 1p 客户端",同样要求标准终端用户账号,响应体为空对象。
配置管理:数据源与搜索应用
搜索的可用性与范围取决于 settings 资源下的两类配置对象:
- Data Source(数据源):
Schema$DataSource(v1.ts)定义数据源的名称、索引配置与身份源绑定,是第三方数据的容器;通过settings.datasources资源管理,同时indexing.datasources.deleteSchema等接口负责其 Schema 的增删。 - Search Application(搜索应用):
Schema$SearchApplication(v1.ts)定义搜索体验的边界,包括可用数据源、默认排序、facet 配置、权限与启用状态等;通过settings.searchapplications资源管理。
从源码结构看(v1.ts),settings.datasources 与 settings.searchapplications 均提供创建、读取、列举、更新等管理方法,且这些设置类接口通常需要 admin 账号或 cloud_search.settings 系列作用域。
长时操作与运维观测
indexing.datasources.deleteSchema 等接口返回的是 Schema$Operation(v1.ts)——Google 标准的 long-running operation 结构,包含 done、error、metadata、name、response 五个字段。这表示 Schema 删除、批量索引等重操作是异步执行的:调用后需通过 operations.get(携带 operation 的 name)轮询完成状态,直到 done: true;operations 资源还提供 cancel、delete、list 以及 operations.lro 子资源(v1.ts)。
此外,stats 资源按 index、query、session、user 四个维度提供统计查询能力,分别面向索引量、搜索行为、会话活跃度与用户维度,可用于观测整个搜索系统的健康度与使用情况(v1.ts)。
常见问题与注意事项
- Query API 与服务账号:
query.search/suggest不能用服务账号直接执行,需为标准终端用户配置 OAuth 2.0,或将服务账号做 Google Workspace 域级委托。 - 权限等级:
checkAccess需要 admin 账号;media.upload需要 service account;deleteSchema需要 admin 或 service account——开发前先对照各方法注释中的 Note 确认账号类型,避免 403。 - 作用域最小化:按实际功能选择最小作用域,如只做检索就只申请
cloud_search.query,而不是笼统使用cloud_search。 - 分页边界:
pageSize超出 1–100 范围会报错;请求 2000 条之后的结果时,pageSize至少要为 50。 - 大文件不要内联:超过内联上限的内容务必走
upload → media.upload → index三步流程。 - Node 版本:
@googleapis/cloudsearch26.x 要求 Node.js >= 22(见 package.json 的engines),低版本环境需先升级运行时。
进一步探索
- 客户端入口与版本分发:index.ts
- 全部资源类、方法签名与 Schema 定义:v1.ts
- 版本变更记录(含破坏性变更提示):CHANGELOG.md
- 包元数据与构建脚本:package.json
- 更多 API 包的统一用法与认证示例:仓库根目录的 README.md 与 samples/
该库遵循 Apache 2.0 开源协议,完整许可文本见仓库 LICENSE。若在使用中遇到问题,可在对应 Issue 中反馈;按仓库 CONTRIBUTING.md 的指引,提交 Pull Request 前建议先开启一个 Issue 讨论改动方案。