חיפוש קבצים ותיקיות

ממשק Google Drive API תומך בכמה דרכים לחיפוש קבצים ותיקיות.

אתם יכולים להשתמש בשיטה של files.list כדי להחזיר את כל הקבצים והתיקיות של משתמש ב-Drive או רק חלק מהם. אפשר גם להשתמש בשיטה files.list כדי לאחזר את fileId שנדרש לשיטות מסוימות של משאבים (כמו files.get ו-files.update).

חיפוש של כל הקבצים והתיקיות בתיקייה 'האחסון שלי' של המשתמש הנוכחי

כדי להחזיר את כל הקבצים והתיקיות, משתמשים בשיטה files.list ללא פרמטרים.

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

חיפוש קבצים או תיקיות ספציפיים בתיקיית 'האחסון שלי' של המשתמש הנוכחי

כדי לחפש קבוצה ספציפית של קבצים או תיקיות, משתמשים במחרוזת השאילתה q field עם השיטה files.list כדי לסנן את הקבצים שיוחזרו על ידי שילוב של מונח חיפוש אחד או יותר.

מחרוזת שאילתה מכילה את שלושת החלקים הבאים:

query_term operator values

כאשר:

  • query_term הוא מונח השאילתה או השדה שרוצים לחפש בו.

  • operator מציין את התנאי למונח השאילתה.

  • values הם הערכים הספציפיים שרוצים להשתמש בהם כדי לסנן את תוצאות החיפוש.

כדי לראות את המונחים והאופרטורים של השאילתות שבהם אפשר להשתמש כדי לסנן קבצים ותיקיות, אפשר לעיין במאמר מונחים ואופרטורים של שאילתות חיפוש.

לדוגמה, מחרוזת השאילתה הבאה מסננת את החיפוש כך שיוחזרו רק תיקיות על ידי הגדרת סוג ה-MIME:

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

מידע נוסף על סוגי MIME זמין במאמר סוגי MIME שנתמכים ב-Google Workspace וב-Google Drive.

דוגמאות למחרוזות שאילתה

בטבלה הבאה מפורטות דוגמאות לכמה מחרוזות שאילתה בסיסיות. הקוד בפועל שונה בהתאם לספריית הלקוח שבה אתם משתמשים לחיפוש.

בנוסף, צריך להוסיף תווי בריחה (escape) לתווים מיוחדים בשמות הקבצים כדי לוודא שהשאילתה פועלת בצורה תקינה. לדוגמה, אם שם קובץ מכיל גם גרש (') וגם לוכסן הפוך ("\"), צריך להשתמש בלוכסן הפוך כדי לבטל את המשמעות המיוחדת שלהם: name contains 'quinn\'s paper\\essay'.

מה רוצים לשאול דוגמה
קבצים בשם 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) '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. בדוגמה הזו נעשה שימוש במונח השאילתה mimeType כדי לצמצם את התוצאות לקבצים מהסוג image/jpeg. הוא גם מגדיר את הערך של spaces ל-drive כדי לצמצם עוד יותר את החיפוש ל מרחב ב-Drive. אם הפונקציה nextPageToken מחזירה null, אין יותר תוצאות.

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 עם מפתח וערך. לדוגמה, כדי לחפש מאפיין מותאם אישית של קובץ שהוא פרטי לאפליקציה ששולחת את הבקשה, שנקרא additionalID עם הערך 8e8aceg2af2ge72e78:

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

מידע נוסף זמין במאמר הוספת מאפיינים מותאמים אישית לקבצים.

חיפוש קבצים עם תווית ספציפית או ערך שדה ספציפי

כדי לחפש קבצים עם תוויות ספציפיות, משתמשים במונח labels של שאילתת החיפוש עם מזהה תווית ספציפי. לדוגמה: 'labels/LABEL_ID' in labels אם הפעולה בוצעה בהצלחה, גוף התגובה יכיל את כל המקרים של הקובץ שבהם התווית הוחלה.

כדי לחפש קבצים ללא מזהה תווית ספציפי: Not 'labels/LABEL_ID' in labels.

אפשר גם לחפש קבצים לפי ערכים ספציפיים בשדות. לדוגמה, כדי לחפש קבצים עם ערך טקסט: labels/LABEL_ID.text_field_id ='TEXT'.

מידע נוסף זמין במאמר חיפוש קבצים עם תווית או ערך שדה ספציפיים.

חיפוש במקורות המידע

חיפושים שמתבצעים באמצעות files.list משתמשים בcorpora של user כברירת מחדל. כדי לחפש מאגרי מידע אחרים, כמו קבצים ששותפו עם domain, מגדירים את הפרמטר corpora.

אפשר לחפש בכמה מאגרי מידע בשאילתה אחת, אבל אם השילוב של מאגרי המידע גדול מדי, יכול להיות שיוחזרו תוצאות חלקיות. אם incompleteSearch הוא true בגוף התגובה, סימן שלא כל המסמכים הוחזרו. אם זה קורה, כדאי לצמצם את השאילתה על ידי בחירת מאגר מידע אחר, כמו user או drive.