搜尋檔案和資料夾

Google Drive API 支援數種搜尋檔案和資料夾的方式。

您可以使用 files.list 方法,傳回雲端硬碟使用者的所有或部分檔案和資料夾。files.list 方法也可用來擷取某些資源方法所需的 fileId (例如 files.getfiles.update)。

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

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

GET https://www.googleapis.com/drive/v3/files

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

如要搜尋一組特定檔案或資料夾,請使用查詢字串 q 欄位搭配 files.list 方法,合併一或多個搜尋字詞來篩選要傳回的檔案。

查詢字串包含以下三個部分:

query_term operator values

在此情況下:

  • query_term 是要搜尋的查詢字詞或欄位。

  • operator 用於指定查詢字詞的條件。

  • values 是您要用於篩選搜尋結果的特定值。

如要查看可使用篩選檔案和資料夾的查詢字詞和運算子,請參閱搜尋查詢詞彙和運算子

舉例來說,下列查詢字串會篩選搜尋,僅透過設定 MIME 類型傳回資料夾:

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

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

查詢字串範例

下表列舉了一些基本查詢字串的範例。實際程式碼會因您用於搜尋的用戶端程式庫而異。

您想查詢的內容 範例
名為「hello」的檔案 name = 'hello'
名稱包含「hello」和「goodbye」字詞的檔案 name contains 'hello' and name contains 'goodbye'
名稱不含「hello」一詞的檔案 not name contains 'hello'
垃圾桶中含有「重要」文字的檔案 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'
屬於資料夾的檔案 mimeType = 'application/vnd.google-apps.folder'
不屬於資料夾的檔案 mimeType != 'application/vnd.google-apps.folder'
在指定日期之後修改的檔案 (預設時區為世界標準時間) modifiedTime > '2012-06-04T12:00:00'
在特定日期後修改的圖片或影片檔案 modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')
已加星號的檔案 starred = true
集合中的檔案 (例如 parents 集合中的資料夾 ID) '1234567' in parents
集合中應用程式資料夾中的檔案 'appDataFolder' in parents
擁有者為「test@example.org」的檔案 'test@example.org' in owners
使用者「test@example.org」擁有寫入權限的檔案 'test@example.org' in writers
「group@example.org」群組成員擁有寫入權限的檔案 'group@example.org' in writers
與授權使用者共用且名稱包含「hello」的檔案 sharedWithMe and name contains 'hello'
所有應用程式都能查看具備自訂檔案屬性的檔案 properties has { key='mass' and value='1.3kg' }
含有自訂檔案屬性的檔案,僅限提出要求的應用程式 appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
尚未與任何人或網域共用的檔案 (僅限私人或與特定使用者/群組共用) visibility = 'limited'

使用用戶端程式庫篩選搜尋結果

以下程式碼範例說明如何使用用戶端程式庫,篩選出 JPEG 檔案名稱和 ID 的搜尋結果。這個範例使用 mimeType 查詢字詞,將結果範圍縮小為 image/jpeg 類型的檔案。此外,也會將 spaces 設為 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
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;
    }
}

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

如要搜尋含有自訂檔案屬性的檔案,請使用 propertiesappProperties 搜尋查詢,並加上索引鍵和值。舉例來說,如要搜尋僅供要求應用程式使用 additionalID 且值為 8e8aceg2af2ge72e78 的自訂檔案屬性:

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

詳情請參閱「新增自訂檔案屬性」。

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

如要搜尋含有特定標籤的檔案,請使用 labels 搜尋查詢含有特定標籤 ID。例如:'labels/LABEL_ID' in labels。如果成功,回應主體會包含已套用該標籤的所有檔案執行個體。

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

您也可以根據特定欄位值搜尋檔案。舉例來說,如要搜尋含有文字值的檔案,請使用 labels/LABEL_ID.text_field_id ='TEXT'

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

搜尋語料庫

根據預設,呼叫 files.list 的搜尋會使用 usercorpora。如要搜尋其他語料庫 (例如與 domain 共用的檔案),請設定 corpora 參數。

在單一查詢中可以搜尋多個語料庫,但如果合併的語料庫太大,系統則可能會傳回不完整的結果。如果回應主體中的 incompleteSearchtrue,系統就不會傳回所有文件。如果發生這種情況,建議您選擇其他語料庫 (例如 userdrive) 來縮小查詢範圍。