搜尋檔案和資料夾

使用 files.list 方法搜尋檔案和資料夾。

搜尋目前「我的雲端硬碟」中的所有檔案和資料夾

使用 files.list 時不含任何參數,可傳回所有檔案和資料夾。

在目前使用者的「我的雲端硬碟」中搜尋特定檔案或資料夾

如要搜尋一組特定檔案或資料夾,請使用查詢字串 q 搭配 files.list 來篩選要傳回的檔案。

以下範例顯示查詢字串的格式:

query_term operator values

在此情況下:

  • 「query_term」是要搜尋的查詢字詞或欄位。如要查看可用來篩選共用雲端硬碟的查詢字詞,請參閱搜尋查詢字詞
  • 運算子會指定查詢字詞的條件。如要查看每個查詢字詞可用的運算子,請參閱查詢運算子
  • 是您希望用來篩選搜尋結果的特定值。

舉例來說,以下查詢字串會篩選搜尋範圍,只傳回資料夾:

q: mimeType = 'application/vnd.google-apps.folder'

以下範例說明如何使用用戶端程式庫,根據搜尋結果篩選 JPEG 圖片檔名稱和 ID。這個範例使用 mimeType 查詢字詞,將結果範圍縮小至 image/jpeg 類型的檔案。此範例也將 spaces 設為 drive,以進一步將搜尋範圍縮小至 drive 空間。當 nextPageToken 回傳 null 時,就沒有其他結果。

Java

drive/snippets/drive_v3/src/main/java/SearchFile.java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/* Class to demonstrate use-case of search files. */
public class SearchFile {

  /**
   * Search for specific set of files.
   *
   * @return search result list.
   * @throws IOException if service account credentials file not found.
   */
  public static List<File> searchFile() throws IOException {
           /*Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
           guides on implementing OAuth2 for your application.*/
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
        .createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    Drive service = new Drive.Builder(new NetHttpTransport(),
        GsonFactory.getDefaultInstance(),
        requestInitializer)
        .setApplicationName("Drive samples")
        .build();

    List<File> files = new ArrayList<File>();

    String pageToken = null;
    do {
      FileList result = service.files().list()
          .setQ("mimeType='image/jpeg'")
          .setSpaces("drive")
          .setFields("nextPageToken, items(id, title)")
          .setPageToken(pageToken)
          .execute();
      for (File file : result.getFiles()) {
        System.out.printf("Found file: %s (%s)\n",
            file.getName(), file.getId());
      }

      files.addAll(result.getFiles());

      pageToken = result.getNextPageToken();
    } while (pageToken != null);

    return files;
  }
}

Python

drive/snippets/drive-v3/file_snippet/search_file.py
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def search_file():
    """Search file in drive location

    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.
    """
    creds, _ = google.auth.default()

    try:
        # create drive api client
        service = build('drive', 'v3', credentials=creds)
        files = []
        page_token = None
        while True:
            # pylint: disable=maybe-no-member
            response = service.files().list(q="mimeType='image/jpeg'",
                                            spaces='drive',
                                            fields='nextPageToken, '
                                                   'files(id, name)',
                                            pageToken=page_token).execute()
            for file in response.get('files', []):
                # Process change
                print(F'Found file: {file.get("name")}, {file.get("id")}')
            files.extend(response.get('files', []))
            page_token = response.get('nextPageToken', None)
            if page_token is None:
                break

    except HttpError as error:
        print(F'An error occurred: {error}')
        files = None

    return files


if __name__ == '__main__':
    search_file()

Node.js

drive/snippets/drive_v3/file_snippets/search_file.js
/**
 * Search file in drive location
 * @return{obj} data file
 * */
async function searchFile() {
  const {GoogleAuth} = require('google-auth-library');
  const {google} = require('googleapis');

  // Get credentials and build service
  // TODO (developer) - Use appropriate auth mechanism for your app
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });
  const service = google.drive({version: 'v3', auth});
  const files = [];
  try {
    const res = await service.files.list({
      q: 'mimeType=\'image/jpeg\'',
      fields: 'nextPageToken, files(id, name)',
      spaces: 'drive',
    });
    Array.prototype.push.apply(files, res.files);
    res.data.files.forEach(function(file) {
      console.log('Found file:', file.name, file.id);
    });
    return res.data.files;
  } catch (err) {
    // TODO(developer) - Handle error
    throw err;
  }
}

PHP

drive/snippets/drive_v3/src/DriveSearchFiles.php
use Google\Client;
use Google\Service\Drive;
function searchFiles()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);
        $files = array();
        $pageToken = null;
        do {
            $response = $driveService->files->listFiles(array(
                'q' => "mimeType='image/jpeg'",
                'spaces' => 'drive',
                'pageToken' => $pageToken,
                'fields' => 'nextPageToken, files(id, name)',
            ));
            foreach ($response->files as $file) {
                printf("Found file: %s (%s)\n", $file->name, $file->id);
            }
            array_push($files, $response->files);

            $pageToken = $response->pageToken;
        } while ($pageToken != null);
        return $files;
    } catch(Exception $e) {
       echo "Error Message: ".$e;
    }
}

如要將搜尋範圍限制在資料夾,請使用查詢字串將 MIME 類型設為 q: mimeType = 'application/vnd.google-apps.folder'

如要進一步瞭解 MIME 類型,請參閱「Google Workspace 和雲端硬碟 MIME 類型」。

查詢字串範例

此表格會顯示一些基本查詢字串。實際程式碼會因用於搜尋的用戶端程式庫而異。

您想查詢的內容 範例
名為「hello」的檔案 name = 'hello'
名稱包含「hello」和「goodbye」的檔案 name contains 'hello' and name contains 'goodbye'
名稱不含「hello」的檔案 not name contains 'hello'
資料夾為 Google 應用程式,或資料夾 MIME 類型 mimeType = 'application/vnd.google-apps.folder'
不屬於資料夾的檔案 mimeType != 'application/vnd.google-apps.folder'
含有「重要」字樣及垃圾桶中檔案的檔案 fullText contains 'important' and trashed = true
含有「hello」字詞的檔案 fullText contains 'hello'
不含「hello」一詞的檔案 not fullText contains 'hello'
含有「hello world」一詞的檔案 fullText contains '"hello world"'
檔案含有「\」字元 (例如「\authors」) fullText contains '\\authors'
集合內的 ID 檔案,例如 parents 集合 '1234567' in parents
集合中的「應用程式資料」資料夾檔案 'appDataFolder' in parents
使用者「test@example.org」擁有寫入權限的檔案 'test@example.org' in writers
「group@example.org」群組成員擁有的檔案權限 'group@example.org' in writers
在指定日期之後修改的檔案 modifiedTime > '2012-06-04T12:00:00' // default time zone is UTC
與授權使用者共用的檔案,檔案名稱中有「hello」 sharedWithMe and name contains 'hello'
未與任何個人或網域共用的檔案 (僅限私人或與特定使用者或群組共用) visibility = 'limited'
經過特定日期修改的圖片或影片檔案 modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')

搜尋含有自訂檔案屬性的檔案

如要搜尋含有自訂檔案屬性的檔案,請使用 appProperties 搜尋字詞搭配索引鍵和值。舉例來說,如要搜尋名為 additionalID 的自訂檔案屬性,且值為 8e8aceg2af2ge72e78

appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }

如要進一步瞭解自訂檔案屬性,請參閱「新增自訂檔案屬性」一文。

搜尋已加上特定標籤或欄位值的檔案

如要搜尋含有特定標籤的檔案,請使用具有特定標籤 ID 的 labels 搜尋字詞。例如:'labels/LABEL_ID' in labels

如何搜尋不含特定標籤 ID 的檔案:Not 'labels/LABEL_ID' in labels

您也可以根據特定欄位值搜尋檔案。例如,如要搜尋含有文字值的檔案,請按照下列步驟操作: labels/LABEL_ID.text_field_id = 'TEXT'

詳情請參閱「搜尋包含特定標籤或欄位值的檔案」。

搜尋主體

根據預設,呼叫 files.list 會使用 user 主體。如要搜尋其他主體 (例如共用至Google Workspace 網域的檔案),請使用 corpora 參數。

可以在單一查詢中搜尋多個主體,但如果綜合資料庫過大,系統可能會傳回不完整的結果。如果 incompleteSearch 結果為 true,則不會傳回所有文件。