搜索具有特定标签或字段值的文件

本页介绍了如何搜索应用了特定标签或字段值的文件。

标签字段类型

Google 云端硬盘标签字段是强类型,每种类型支持不同的索引和搜索语义。下表列出了可用的数据类型。

类型 标签类型选项 支持的搜索运算符
文字 TextOptions is null, is not null, =, contains, starts with
长文本 LongTextOptions is null, is not null, contains
整数 IntegerOptions is null, is not null, =, !=, <, >, <=, >=
日期 DateOptions is null, is not null, =, !=, <, >, <=, >=
选择 SelectionOptions is null, is not null, =, !=
用户 UserOptions is null, is not null, =, !=
选项列表 SelectionOptions(包含 max_entries > 1) is null, is not null, in, not in
用户名单 UserOptions(max_entries > 1) is null, is not null, in, not in

1. 根据是否存在标签或字段进行搜索

您可以搜索已应用(或未)应用特定标签的内容:

  • 'labels/contract' in labels
  • not 'labels/contract' in labels

您还可以搜索已设置(或未设置)特定字段的项:

  • labels/contract.comment IS NOT NULL
  • labels/contract.comment IS NULL

2. 根据单值字段搜索

您可以编写搜索查询,使其与预期字段值匹配。下表显示了有效的字段查询:

您要查询的内容 查询字符串
评论设为“您好”的项 labels/contract.comment = 'hello'
评论以“hello”开头的文件 labels/contract.comment STARTS WITH 'hello'
执行状态的文件 labels/contract.status = 'executed'
未执行状态的文件 labels/contract.status != 'executed'
执行日期早于特定日期的文件 labels/contract.execution_date < '2020-06-22'
value_usd(整数)小于特定值的文件 labels/contract.value_usd < 2000
将 client_contact 设置为特定电子邮件地址的文件 labels/contract.client_contact = 'alex@altostrat.com'

3. 根据包含多值字段的字段(例如 ListOptions.max_entries > 1)搜索

仅支持使用 IN 运算符查询支持多个值的字段:

  • 'EMAIL_ADDRESS' IN labels/project.project_leads
  • NOT 'EMAIL_ADDRESS' IN labels/project.project_leads

示例

以下代码示例展示了如何使用一个或多个 labelId 列出云端硬盘文件资源中具有特定标签或字段值的所有文件。它还使用 files.list 方法。请求正文必须为空。

如果您想在响应中包含 labelInfo,则还必须指定:

  • includeLabels,以英文逗号分隔的 ID 列表。

  • fields 参数中的 labelInfo,表示您希望 includeLabels 中返回 labelInfo

如果成功,响应正文将包含文件列表。

Java

List<File> fileList = driveService.files().list().setIncludeLabels("LABEL_1_ID,LABEL_2_ID").setFields("items(labelInfo, id)").setQ("'labels/LABEL_1_ID' in labels and 'labels/LABEL_2_ID' in labels").execute().getItems();

Python

file_list = drive_service.files().list(includeLabels="LABEL_1_ID,LABEL_2_ID", q="'labels/LABEL_1_ID' in labels and 'labels/LABEL_2_ID' in labels", fields="items(labelInfo, id)").execute();

Node.js

/**
* Search for Drive files with specific labels
* @return{obj} file list with labelInfo
**/
async function searchForFileWithLabels() {
  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app

  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'});
  const service = google.drive({version: 'v3', auth});
  try {
    const fileList = await service.files.list({
      includeLabels: 'LABEL_1_ID,LABEL_2_ID',
      q: '\'labels/LABEL_1_ID\' in labels and \'labels/LABEL_2_ID\' in labels',
      fields:'files(labelInfo, id)',
    });
    return file;
  } catch (err) {
    // TODO (developer) - Handle error
    throw err;
  }

替换以下内容:

  • LABEL_1_ID:要返回的标签的第一个 labelId
  • LABEL_2_ID:要返回的标签的第二个 labelId