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

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

标签字段类型

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. 根据单值字段进行搜索

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

您要查询的内容 查询字符串
评论设为“hello”的项 labels/contract.comment = 'hello'
评论以“hello”开头的文件 labels/contract.comment STARTS WITH 'hello'
执行状态的文件 labels/contract.status = 'executed'
未执行状态的文件 labels/contract.status != 'executed'
执行_date 早于特定日期的文件 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

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

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