ファイルとフォルダを検索する

このガイドでは、Google Drive API でファイルやフォルダを検索する方法について説明します。

files リソースで list メソッドを使用すると、 ドライブ ユーザーのファイルとフォルダのすべてまたは一部を返すことができます。また、list メソッドを使用して、一部のリソース メソッド( get メソッドや update メソッドなど)に必要な fileId を取得することもできます。

fields パラメータを使用する

レスポンスで返すフィールドを指定する場合は、 fields システム パラメータ を files リソースの任意のメソッドで設定します。fields パラメータを省略すると、メソッド固有のデフォルトのフィールド セットが返されます。たとえば、 list メソッドは、各ファイルの kind、id、 name、mimeType、および resourceKey フィールドのみを返します。別の フィールドを返す方法については、特定のフィールドを返すをご覧ください。

ID でファイルを取得する

ファイルを取得するには、get メソッドを files リソースで使用し、fileId パスパラメータを指定します。 ファイル ID がわからない場合は、すべてのファイルを一覧表示するには、list メソッドを使用します。

このメソッドは、ファイルを files リソースのインスタンスとして返します。alt=media パラメータを指定すると、レスポンスの本文にファイルの内容が含まれます。BLOB ファイルをダウンロードするには、BLOB ファイルの内容をダウンロードするをご覧ください。

既知のマルウェアやその他の 不正使用ファイルがダウンロードされるリスクを認識するには、 acknowledgeAbuse クエリ パラメータを true に設定します。このフィールドは、alt=media パラメータが設定されていて、ユーザーがファイルのオーナーであるか、ファイルが保存されている共有ドライブの管理者のいずれかである場合にのみ適用されます。

マイドライブ内のすべてのファイルとフォルダを一覧表示する

パラメータを指定せずに list メソッドを使用すると、現在のユーザーのマイドライブ内のすべてのファイルとフォルダが返されます。

次の curl コマンドは、すべてのファイルを一覧表示する方法を示しています。

curl -X GET \
  'https://www.googleapis.com/drive/v3/files' \
  -H 'Authorization: Bearer ACCESS_TOKEN' \
  -H 'Accept: application/json'

ACCESS_TOKEN は、承認済みの OAuth 2.0 アクセス トークンに置き換えます。

マイドライブ内の特定のファイルとフォルダを検索する

現在のユーザーのマイドライブ内の特定のファイルまたはフォルダを検索するには、クエリ文字列 q フィールドを list メソッドとともに使用して、1 つ以上の検索語句を組み合わせて返すファイルをフィルタします。

クエリ文字列の構文は、次の 3 つの部分で構成されています。

query_term operator values

ここで

  • query_term は、検索するクエリ語句またはフィールドです。

  • operator は、クエリ語句の条件を指定します。

  • values は、検索結果のフィルタに使用する特定の値です。

たとえば、次のクエリ文字列は、MIME タイプを設定して フォルダのみを返すように検索をフィルタします。

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

すべてのファイル クエリ語句を表示するには、ファイル固有のクエリ語句をご覧ください。

クエリの作成に使用できるすべてのクエリ演算子を表示するには、クエリ 演算子をご覧ください。

クエリ文字列の例

次の表に、基本的なクエリ文字列の例を示します。実際のコードは、検索に使用するクライアント ライブラリによって異なります。

クエリが正しく機能するように、ファイル名内の特殊文字もエスケープする必要があります。たとえば、ファイル名にアポストロフィ (')とバックスラッシュ("\")の両方の文字が含まれている場合は、バックスラッシュを使用してエスケープします(name contains 'quinn\'s paper\\essay')。

クエリ対象 例
文字列一致演算子(contains)
「hello」という単語を含むファイル fullText contains 'hello'
「hello world」というフレーズを含むファイル fullText contains '"hello world"'
「\」文字(「\authors」など)を含むクエリを含むファイル fullText contains '\\authors'
「budget」を含む名前のファイル name contains 'budget'
等価演算子と不等価演算子(=、!=)
「hello」という名前のファイル name = 'hello'
フォルダであるファイル mimeType = 'application/vnd.google-apps.folder'
フォルダではないファイル mimeType != 'application/vnd.google-apps.folder'
スター付きのファイル starred = true
ゴミ箱内のファイル trashed = true
ゴミ箱にないファイル trashed = false
特定のファイル ID を指すショートカット shortcutDetails.targetId = '1987654321'
誰ともドメインとも共有されていないファイル(非公開、または特定のユーザーやグループと共有されている) visibility = 'limited'
リンクを知っているすべてのユーザーがアクセスできるファイル visibility = 'anyoneWithLink'
ウェブ上で一般公開されているファイル visibility = 'anyoneCanFind'
比較演算子(>、>=、<、<=)
指定した日付以降に変更されたファイル(デフォルトのタイムゾーンは UTC) modifiedTime > '2012-06-04T12:00:00'
2023 年 1 月 1 日以降に作成されたファイル createdTime > '2023-01-01T00:00:00'
2023 年 1 月 1 日より前に変更されたファイル modifiedTime < '2023-01-01T00:00:00'
コレクション メンバーシップ演算子(in)
コレクション内のファイル(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
ユーザー「test@example.org」に読み取り権限があるファイル 'test@example.org' in readers
コレクション一致演算子(has)
すべてのアプリに表示されるカスタム ファイル プロパティを持つファイル properties has { key='mass' and value='1.3kg' }
リクエスト元のアプリに非公開のカスタム ファイル プロパティを持つファイル appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
キー「department」のカスタム ファイル プロパティを持つファイル(値に関係なく) properties has { key='department' }
論理演算子(and、or、not)
「hello」と「goodbye」という単語を含む名前のファイル name contains 'hello' and name contains 'goodbye'
「hello」という単語を含まない名前のファイル not name contains 'hello'
「important」というテキストを含み、ゴミ箱にあるファイル fullText contains 'important' and trashed = true
「hello」という単語を含まないファイル not fullText contains 'hello'
特定の日付以降に変更された画像ファイルまたは動画ファイル modifiedTime > '2012-06-04T12:00:00' and (mimeType contains 'image/' or mimeType contains 'video/')
承認済みユーザーと共有され、名前に「hello」が含まれるファイル sharedWithMe and name contains 'hello'
フォルダまたはショートカットであるファイル mimeType = 'application/vnd.google-apps.folder' or mimeType = 'application/vnd.google-apps.shortcut'
「Project Plan」という名前で、ゴミ箱にないファイル name = 'Project Plan' and trashed = false
特定のフォルダにあり、ゴミ箱にないファイル '1234567' in parents and trashed = false

クライアント ライブラリで検索結果をフィルタする

次のコードサンプルは、クライアント ライブラリを使用して検索結果をフィルタし、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, files(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
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Searches for files in Google Drive.
 * @return {Promise<object[]>} A list of files.
 */
async function searchFile() {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // Search for files with the specified query.
  const result = await service.files.list({
    q: "mimeType='image/jpeg'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
  });

  // Print the name and ID of each found file.
  (result.data.files ?? []).forEach((file) => {
    console.log('Found file:', file.name, file.id);
  });

  return result.data.files ?? [];
}

PHP

drive/snippets/drive_v3/src/DriveSearchFiles.php
<?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;
    }
}

一般公開フォルダ内のファイルを一覧表示する

一般公開されているフォルダ(アクセス権が [リンクを知っている全員] または [ウェブ上で一般公開] に設定されている)内のファイルを検索または一覧表示するには、list メソッドを files リソースで使用し、q クエリ パラメータを設定して parents コレクション内のフォルダ ID でフィルタします。

'FOLDER_ID' in parents and trashed = false

一般公開フォルダ内のファイルを一覧表示する場合は、OAuth 2.0 ユーザー認証情報の代わりに API キーを使用してリクエストを認証できます。フォルダが共有ドライブ内にある場合は、リクエストで supportsAllDrives=true と includeItemsFromAllDrives=true も設定する必要があります。

次のコードサンプルは、一般公開フォルダ内のファイルを一覧表示する方法を示しています。

Node.js

/**
 * List files in a public folder using an API key.
 * @param {string} folderId The ID of the public folder.
 * @param {string} apiKey Your Google Cloud API key.
 * @return {Promise<Array>} The list of files.
 */
async function listPublicFolder(folderId, apiKey) {
  const {google} = require('googleapis');
  const service = google.drive({version: 'v3', auth: apiKey});

  try {
    const response = await service.files.list({
      q: `'${folderId}' in parents and trashed = false`,
      fields: 'nextPageToken, files(id, name, mimeType)',
      supportsAllDrives: true,
      includeItemsFromAllDrives: true,
    });
    const files = response.data.files;
    console.log('Files:');
    for (const file of files) {
      console.log(`${file.name} (${file.id})`);
    }
    return files;
  } catch (err) {
    // TODO(developer): Handle error
    console.error(err);
  }
}

curl

curl -G \
  'https://www.googleapis.com/drive/v3/files' \
  --data-urlencode "q='FOLDER_ID' in parents and trashed = false" \
  --data-urlencode 'supportsAllDrives=true' \
  --data-urlencode 'includeItemsFromAllDrives=true' \
  --data-urlencode 'fields=nextPageToken,files(id,name,mimeType)' \
  --data-urlencode 'key=API_KEY' \
  -H 'Accept: application/json'

次のように置き換えます。

  • FOLDER_ID: 一般公開フォルダの ID。
  • API_KEY: プロジェクトの API キー。

カスタム プロパティを持つファイルを検索する

カスタム ファイル プロパティを持つファイルを検索するには、キーと値を使用して properties または appProperties 検索クエリ語句を使用します。たとえば、リクエスト元のアプリに非公開のカスタム ファイル プロパティ additionalID を値 8e8aceg2af2ge72e78 で検索するには、次のようにします。

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

詳細については、カスタム ファイル プロパティを追加するをご覧ください。

ラベルまたはフィールド値でファイルを検索する

特定のラベルが付いたファイルを検索するには、labels 検索クエリ語句と特定のラベル ID を使用します。

特定のラベルが適用されているファイルを検索するには:

'labels/LABEL_ID' in labels

特定のラベルが適用されていないファイルを検索するには:

not 'labels/LABEL_ID' in labels

特定のラベル フィールドの値に基づいてファイルを検索するには:

labels/LABEL_ID.FIELD_ID = 'VALUE'

成功した場合、レスポンスの本文にはクエリに一致するすべてのファイル インスタンスが含まれます。詳細については、特定のラベルまたは フィールド値を持つファイルを検索するをご覧ください。

コーパス全体を検索する

デフォルトでは、user アイテム コレクションは、corpora クエリ パラメータ に、list メソッドを使用すると設定されます。domain と共有されているアイテム コレクションなど、他のアイテム コレクションを検索するには、corpora パラメータを明示的に設定する必要があります。

1 つのクエリで複数のコーパスを検索できますが、結合されたコーパスが大きすぎると、API から不完全な結果が返される可能性があります。レスポンスの本文で incompleteSearch フィールドを確認します。true の場合、一部のドキュメントが省略されています。この問題を解決するには、corpora を絞り込んで user または drive を使用します。

list メソッドで orderBy クエリ パラメータを使用する場合は、 大きなアイテム コレクションに対するクエリに createdTime キーを使用しないでください。追加の処理が必要になり、タイムアウトやその他の問題が発生する可能性があります。大きなアイテム コレクションで時間に関連する並べ替えを行う場合は、modifiedTime を使用できます。これは、これらのクエリを処理するように最適化されています。 たとえば、orderBy を modifiedTime(または modifiedTime desc)に設定します。

orderBy クエリ パラメータを省略すると、デフォルトの並べ替え順序がなくなり、アイテムは任意に返されます。