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

このガイドでは、Google Drive API がファイルとフォルダの検索方法をどのようにサポートしているかについて説明します。

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

fields パラメータを使用する

レスポンスで返すフィールドを指定する場合は、files リソースの任意のメソッドを使用して fields システム パラメータを設定できます。fields パラメータを省略すると、サーバーはメソッドに固有のデフォルトのフィールド セットを返します。たとえば、list メソッドは、各ファイルの kindidnamemimeTyperesourceKey フィールドのみを返します。別のフィールドを返すには、特定のフィールドを返すをご覧ください。

ファイルを取得する

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

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

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

現在のユーザーのマイドライブにあるすべてのファイルとフォルダを検索する

パラメータなしで list メソッドを使用すると、すべてのファイルとフォルダが返されます。

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

現在のユーザーのマイドライブで特定のファイルまたはフォルダを検索する

特定のファイルやフォルダのセットを検索するには、list メソッドで q クエリ文字列フィールドを使用して、1 つ以上の検索語句を組み合わせて返すファイルをフィルタします。

クエリ文字列の構文には、次の 3 つの部分が含まれます。

query_term operator values

ここで

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

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

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

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

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

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

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

クエリ文字列の例

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

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

クエリの対象
「hello」という名前のファイル name = 'hello'
ファイル名に「hello」と「goodbye」という単語が含まれているファイル name contains 'hello' and name contains 'goodbye'
ファイル名に「hello」という単語が含まれていないファイル not name contains 'hello'
「important」というテキストが含まれていて、ゴミ箱にあるファイル 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'
指定した日付以降に変更されたファイル(デフォルトのタイムゾーンは UTC) 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 タイプのファイルに絞り込んでいます。また、spacesdrive に設定して、検索範囲を ドライブのスペースに絞り込みます。nextPageTokennull を返した場合、それ以上の結果はありません。

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
<?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;
    }
}

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

カスタム ファイル プロパティを使用してファイルを検索するには、properties または appProperties の検索クエリ語句にキーと値を指定します。たとえば、値が 8e8aceg2af2ge72e78 で、リクエスト元のアプリに固有の additionalID というカスタム ファイル プロパティを検索するには:

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' を使用します。

詳細については、特定のラベルまたはフィールド値を持つファイルを検索するをご覧ください。

コーパスを検索する

list メソッドを呼び出す検索では、デフォルトで usercorpora が使用されます。domain と共有されているファイルなど、他のコーパスを検索するには、corpora パラメータを設定します。

1 つのクエリで複数のコーパスを検索できますが、結合されたコーパスが大きすぎると、不完全な結果が返されることがあります。レスポンス本文で incompleteSearchtrue の場合、すべてのドキュメントが返されませんでした。この場合は、userdrive などの別のコーパスを選択して、クエリを絞り込む必要があります。