搜尋含有特定標籤或欄位值的檔案

本頁面說明如何搜尋已套用特定標籤或欄位值的檔案。

標籤欄位類型

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'
run_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

如果成功,回應主體會包含檔案清單。

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