파일 및 폴더 검색

Google Drive API는 파일 및 폴더를 검색하는 여러 가지 방법을 지원합니다.

files.list 메서드를 사용하여 Drive 사용자의 파일 및 폴더의 전체 또는 일부를 반환할 수 있습니다. files.list 메서드를 사용하여 일부 리소스 메서드 (예: files.getfiles.update)에 필요한 fileId를 검색할 수도 있습니다.

현재 사용자의 내 드라이브에 있는 모든 파일 및 폴더 검색

매개변수 없이 files.list 메서드를 사용하여 모든 파일과 폴더를 반환합니다.

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

현재 사용자의 내 드라이브에서 특정 파일 또는 폴더 검색

특정 파일 또는 폴더 집합을 검색하려면 files.list 메서드와 함께 쿼리 문자열 q 필드를 사용하여 하나 이상의 검색어를 결합하여 반환할 파일을 필터링합니다.

쿼리 문자열은 다음과 같은 세 부분으로 구성됩니다.

query_term operator values

각 항목의 의미는 다음과 같습니다.

  • query_term은 검색할 검색어 또는 필드입니다.

  • operator는 쿼리 조건의 조건을 지정합니다.

  • values는 검색 결과를 필터링하는 데 사용할 특정 값입니다.

필터 파일 및 폴더를 사용할 수 있는 쿼리 및 연산자를 보려면 검색어 및 연산자를 참조하세요.

예를 들어 다음 쿼리 문자열은 MIME 유형을 설정하여 폴더만 반환하도록 검색을 필터링합니다.

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

MIME 유형에 관한 자세한 내용은 Google Workspace 및 Google Drive에서 지원하는 MIME 유형을 참고하세요.

쿼리 문자열 예시

다음 표에는 몇 가지 기본 쿼리 문자열의 예가 나와 있습니다. 실제 코드는 검색에 사용하는 클라이언트 라이브러리에 따라 다릅니다.

쿼리하려는 대상
이름이 'hello'인 파일 name = 'hello'
이름에 '안녕하세요'와 '작별'이라는 단어가 포함된 파일 name contains 'hello' and name contains 'goodbye'
이름에 '안녕하세요'라는 단어가 포함되지 않은 파일 not name contains 'hello'
'중요'라는 텍스트가 포함되고 휴지통에 있는 파일 fullText contains 'important' and trashed = true
'안녕하세요'라는 단어가 포함된 파일 fullText contains '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;
  }
}

2,399필리핀

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 매개변수를 설정하세요.

단일 쿼리에서 여러 코퍼스를 검색할 수 있지만 결합된 코퍼스가 너무 크면 불완전한 결과가 반환될 수 있습니다. 응답 본문에서 incompleteSearchtrue이면 모든 문서가 반환되지 않은 것입니다. 이 경우 user 또는 drive와 같은 다른 코퍼스를 선택하여 쿼리 범위를 좁혀야 합니다.