파일 및 폴더 검색

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

files.list 메서드를 사용하여 전체 또는 일부에 액세스할 수 있습니다. files.list 메서드는 일부 리소스에 필요한 fileId를 검색하는 데 사용할 수도 있습니다. 메서드 (예: files.getfiles.update)을 입력합니다.

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

매개변수 없이 files.list 메서드를 사용하여 모든 파일 및 폴더를 만들 수 있습니다

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

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

특정 파일 또는 폴더 세트를 검색하려면 쿼리 문자열 q 필드를 사용합니다. files.list 메서드를 사용하여 파일을 하나 이상의 검색어를 결합하여 반환할 수 있습니다.

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

query_term operator values

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

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

  • operator는 검색어의 조건을 지정합니다.

  • values는 검색을 필터링하는 데 사용할 값입니다. 있습니다.

필터 파일 및 폴더를 사용할 수 있는 검색어 및 연산자를 보려면 다음 안내를 따르세요. 자세한 내용은 검색어 및 연산자를 참조하세요.

예를 들어 다음 쿼리 문자열은 MIME 유형을 설정하여 폴더를 만듭니다.

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

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

쿼리 문자열의 예

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

또한 파일 이름의 특수문자를 이스케이프 처리하여 쿼리가 올바르게 작동하는지 확인할 수 있습니다 예를 들어 파일 이름에 아포스트로피가 모두 포함되어 있는 경우 (')와 백슬래시("\") 문자의 경우 백슬래시를 사용하여 이스케이프 처리합니다(예: name contains 'quinn\'s paper\\essay').

쿼리하려는 대상
이름이 'hello'인 파일 name = 'hello'
이름에 'hello'가 포함된 파일 그리고 '안녕히 가세요' name contains 'hello' and name contains 'goodbye'
이름이 '안녕하세요'라는 단어가 포함되지 않은 파일 not name contains 'hello'
'중요' 텍스트가 포함된 파일 휴지통에 있는 항목 fullText contains 'important' and trashed = true
'hello'라는 단어가 포함된 파일 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
사용자가 '[email protected]'인 파일 님은 소유자입니다. '[email protected]' in owners
사용자가 '[email protected]'인 파일 쓰기 권한 있음 '[email protected]' in writers
'[email protected]' 그룹의 구성원이 해당하는 파일 쓰기 권한 있음 '[email protected]' 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 유형의 파일로 결과 범위를 좁히세요. 또한 검색 범위를 드라이브로 더 좁히려면 spaces~drive하세요. 스페이스입니다. nextPageTokennull를 반환하면 결과가 더 이상 없습니다.

자바

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 검색어를 키 및 값과 함께 표시합니다. 예를 들어 요청하는 앱 전용인 맞춤 파일 속성 검색 additionalID와 값 8e8aceg2af2ge72e78:

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

자세한 내용은 맞춤 파일 추가를 참조하세요. 속성을 참조하세요.

특정 라벨 또는 필드 값이 있는 파일 검색

특정 라벨이 있는 파일을 검색하려면 labels 검색어를 사용합니다. 특정 라벨 ID로 표시됩니다. 예를 들면 'labels/LABEL_ID' in labels입니다. 요청이 성공하면 응답 본문에 라벨이 적용됩니다.

특정 라벨 ID가 없는 파일 검색: Not 'labels/LABEL_ID' in labels

특정 필드 값을 기준으로 파일을 검색할 수도 있습니다. 예를 들어 텍스트 값이 있는 파일 검색: labels/LABEL_ID.text_field_id ='TEXT'

자세한 내용은 특정 라벨 또는 필드가 있는 파일 검색 값을 사용합니다.

코퍼스 검색

files.list를 호출하는 검색은 다음을 사용합니다. 기본값은 user개 중 corpora개입니다. 검색 domain와 공유된 파일과 같은 다른 말뭉치의 경우 corpora를 설정합니다. 매개변수 값으로 사용됩니다.

불완전한 결과가 있더라도 단일 쿼리에서 여러 코퍼스를 검색할 수 있습니다. 는 결합된 코퍼스가 너무 크면 반환될 수 있습니다. incompleteSearch가 다음에 해당하는 경우 true로 반환되면 모든 문서가 반환되지 않았습니다. 만약 다음과 같은 다른 코퍼스를 선택하여 검색 범위를 좁혀야 합니다. user 또는 drive