搜索文件和文件夹

使用 files.list 方法可返回云端硬盘用户的全部或部分文件和文件夹。

您还可以使用 files.list 方法来检索某些资源方法(如 files.getfiles.update)所需的 fileId

搜索当前用户的“我的云端硬盘”中的所有文件和文件夹

使用不带任何参数的 files.list 可返回所有文件和文件夹。

搜索当前用户的“我的云端硬盘”中的特定文件或文件夹

如需搜索一组特定的文件或文件夹,请将查询字符串 q 字段与 files.list 结合使用,通过组合一个或多个搜索字词来过滤要返回的文件。

查询字符串包含以下三个部分:

query_term operator values

其中:

  • query_term 是要搜索的查询字词或字段。如需查看可用于过滤共享云端硬盘的查询字词,请参阅搜索查询字词和运算符

  • operator 指定查询字词的条件。如需了解您可以用于每个查询字词的运算符,请参阅查询运算符

  • values 是您要用于过滤搜索结果的具体值。

例如,以下查询字符串会对搜索进行过滤,仅返回文件夹:

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

以下示例展示了如何使用客户端库将搜索结果过滤为 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;
    }
}

如需将搜索范围限制为文件夹,请使用查询字符串将 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'
属于 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,则表示并未返回所有文档。