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

Google Drive API は、ファイルやフォルダを検索するためにいくつかの方法をサポートしています。

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

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

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

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

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

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

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

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'
指定した日付以降に変更されたファイル(デフォルトのタイムゾーンは 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
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 検索クエリ語句とキーと値を使用します。たとえば、値が 8e8aceg2af2ge72e78additionalID というリクエスト元のアプリ専用のカスタム ファイル プロパティを検索するには、次のようにします。

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

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