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

ファイルとフォルダを検索するには、files.list メソッドを使用します。

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

すべてのファイルとフォルダを返すには、パラメータを指定せずに files.list を使用します。

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

特定のファイルまたはフォルダのセットを検索するには、files.list でクエリ文字列 q を使用して、返すファイルをフィルタリングします。

次の例は、クエリ文字列の形式を示しています。

query_term operator values

ここで

  • query_term は、検索するクエリ語句またはフィールドです。共有ドライブのフィルタに使用できるクエリ語句を表示するには、検索キーワードをご覧ください。
  • operator はクエリ語句の条件を指定します。各クエリ語句で使用できる演算子を確認するには、クエリ演算子をご覧ください。
  • values は、検索結果のフィルタリングに使用する特定の値です。

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

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

次の例は、クライアント ライブラリを使用して、検索結果を JPEG 画像ファイルのファイル名と ID でフィルタリングする方法を示しています。この例では、mimeType クエリ語句を使用して、結果を image/jpeg タイプのファイルに絞り込みます。また、spacesdrive に設定して、検索をさらに drive スペースに絞り込みます。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
from __future__ import print_function

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 とドライブの 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 検索クエリを使用します。たとえば、値が 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 を呼び出す検索では、デフォルトで user コーパスが使用されます。他のコーパス(Google Workspace ドメインで共有されているファイルなど)を検索するには、corpora パラメータを使用します。

1 つのクエリで複数のコーパスを検索することもできますが、コーパスが大きすぎると不完全な結果が返されることがあります。incompleteSearch の結果が true の場合、すべてのドキュメントが返されているわけではありません。