פריסת המחבר

בדף הזה במדריך ל-Cloud Search מוסבר איך להגדיר מקור נתונים ומחבר תוכן להוספת נתונים לאינדקס. כדי להתחיל מההתחלה של המדריך הזה, אפשר לעיין במדריך לתחילת העבודה עם Cloud Search.

יצירת המחבר

משנים את ספריית העבודה לספרייה cloud-search-samples/end-to-end/connector ומריצים את הפקודה הבאה:

mvn package -DskipTests

הפקודה מורידה את התלות הנדרשת לבניית מחבר התוכן ומקמפלת את הקוד.

יצירת פרטי כניסה לחשבון שירות

המחבר דורש פרטי כניסה של חשבון שירות כדי לקרוא ל-Cloud Search APIs. כדי ליצור את פרטי הכניסה:

  1. חוזרים אל מסוף Google Cloud.
  2. בחלונית הניווט הימנית, לוחצים על פרטי כניסה. יופיע הדף 'אישורים'.
  3. לוחצים על הרשימה הנפתחת + CREATE CREDENTIALS ובוחרים באפשרות Service account. מופיע הדף 'יצירת חשבון שירות'.
  4. בשדה Service account name (שם חשבון השירות), מזינים tutorial.
  5. שימו לב לערך של מזהה חשבון השירות (מימין לשם חשבון השירות). הערך הזה ישמש בהמשך.
  6. לוחצים על יצירה. מופיעה תיבת הדו-שיח 'הרשאות של חשבון שירות (אופציונלי)'.
  7. לוחצים על המשך. מופיעה תיבת הדו-שיח 'הענקת גישה למשתמשים לחשבון השירות הזה (אופציונלי)'.
  8. לוחצים על סיום. יופיע המסך 'פרטי כניסה'.
  9. בקטע Service Accounts (חשבונות שירות), לוחצים על כתובת האימייל של חשבון השירות. יופיע הדף 'פרטי חשבון השירות'.
  10. בקטע Keys (מפתחות), לוחצים על התפריט הנפתח ADD KEY (הוספת מפתח) ובוחרים באפשרות Create new key (יצירת מפתח חדש). מופיעה תיבת הדו-שיח 'יצירת מפתח פרטי'.
  11. לוחצים על יצירה.
  12. (אופציונלי) אם מופיע הדו-שיח 'האם ברצונך לאפשר הורדות ב-console.cloud.google.com?', לוחצים על אישור.
  13. קובץ המפתח הפרטי יישמר במחשב. רושמים או זוכרים את המיקום של הקובץ שהורד. הקובץ הזה משמש להגדרת מחבר התוכן, כדי שהוא יוכל לבצע אימות כשמתבצעת קריאה ל-Google Cloud Search APIs.

הפעלת תמיכה של צד שלישי

כדי שתוכלו לקרוא לממשקי API אחרים של Cloud Search, אתם צריכים לאתחל תמיכה בצד שלישי ב-Google Cloud Search.

כדי לאתחל תמיכה בצד שלישי ב-Cloud Search:

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

  2. משתמשים ב-Google's OAuth 2 playground כדי לקבל אסימון גישה:

    1. לוחצים על סמל ההגדרות ומסמנים את התיבה שימוש בפרטי הכניסה שלכם לאימות.
    2. מזינים את מזהה הלקוח ואת הסוד של הלקוח משלב 1.
    3. לוחצים על סגירה.
    4. בשדה 'היקפים', מקלידים https://www.googleapis.com/auth/cloud_search.settings ולוחצים על הרשאה. ה-OAuth 2 playground מחזיר קוד הרשאה.
    5. לוחצים על Exchange authorization code for tokens (החלפת קוד הרשאה באסימונים). מוחזר טוקן.
  3. כדי לאתחל תמיכה בצד שלישי ב-Cloud Search, משתמשים בפקודת curl הבאה. חשוב להחליף את [YOUR_ACCESS_TOKEN] באסימון שהתקבל בשלב 2.

    curl --request POST \
    'https://cloudsearch.googleapis.com/v1:initializeCustomer' \
      --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
      --header 'Accept: application/json' \
      --header 'Content-Type: application/json' \
      --data '{}' \
      --compressed
    

    אם הפעולה בוצעה ללא שגיאות, גוף התגובה יכיל מופע של operation. לדוגמה:

    {
    name: "operations/customers/01b3fqdm/lro/AOIL6eBv7fEfiZ_hUSpm8KQDt1Mnd6dj5Ru3MXf-jri4xK6Pyb2-Lwfn8vQKg74pgxlxjrY"
    }
    

    אם הניסיון לא מצליח, פנו לתמיכה של Cloud Search.

  4. משתמשים ב-operations.get כדי לוודא שתמיכת הצד השלישי אותחלה:

    curl \
    'https://cloudsearch.googleapis.com/v1/operations/customers/01b3fqdm/lro/AOIL6eBv7fEfiZ_hUSpm8KQDt1Mnd6dj5Ru3MXf-jri4xK6Pyb2-Lwfn8vQKg74pgxlxjrY?key=
    [YOUR_API_KEY]' \
    --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
    --header 'Accept: application/json' \
    --compressed
    

    כשהאתחול של הצד השלישי מסתיים, הוא מכיל את השדה done שמוגדר לערך true. לדוגמה:

    {
    name: "operations/customers/01b3fqdm/lro/AOIL6eBv7fEfiZ_hUSpm8KQDt1Mnd6dj5Ru3MXf-jri4xK6Pyb2-Lwfn8vQKg74pgxlxjrY"
    done: true
    }
    

יצירת מקור הנתונים

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

  1. פותחים את מסוף Google Admin.
  2. לוחצים על סמל האפליקציות. יופיע הדף 'ניהול אפליקציות'.
  3. לוחצים על Google Workspace. מופיע הדף 'ניהול אפליקציות ב-Google Workspace'.
  4. גוללים למטה ולוחצים על Cloud Search. מופיע הדף 'הגדרות של Google Workspace'.
  5. לוחצים על מקורות נתונים של צד שלישי. יופיע הדף 'מקורות נתונים'.
  6. לוחצים על העיגול הצהוב עם +. מופיעה תיבת הדו-שיח 'הוספת מקור נתונים חדש'.
  7. בשדה השם המוצג מקלידים 'tutorial'.
  8. בשדה Service account email addresses, מזינים את כתובת האימייל של חשבון השירות שיצרתם בקטע הקודם. אם אתם לא יודעים את כתובת האימייל של חשבון השירות, תוכלו לחפש את הערך בדף חשבונות שירות.
  9. לוחצים על ADD. מופיעה תיבת הדו-שיח 'יצירת מקור הנתונים הסתיימה'.
  10. לוחצים על *אישור. שימו לב למזהה המקור של מקור הנתונים החדש שיצרתם. מזהה המקור משמש להגדרת מחבר התוכן.

יצירת אסימון גישה אישי ל-GitHub API

כדי לקבל מכסת שימוש מספקת, המחבר דורש גישה מאומתת ל-GitHub API. כדי לפשט את התהליך, המחבר משתמש באסימוני גישה אישיים במקום ב-OAuth. טוקנים אישיים מאפשרים אימות כמשתמש עם מערך מוגבל של הרשאות, בדומה ל-OAuth.

  1. מתחברים ל-GitHub.
  2. בפינה השמאלית העליונה, לוחצים על תמונת הפרופיל. יופיע תפריט נפתח.
  3. לוחצים על הגדרות.
  4. לוחצים על הגדרות למפתחים.
  5. לוחצים על Personal access tokens (אסימוני גישה אישיים).
  6. לוחצים על יצירת אסימון גישה אישי.
  7. בשדה הערה, מזינים 'Cloud Search tutorial'.
  8. בודקים את ההיקף public_repo.
  9. לוחצים על יצירת אסימון.
  10. רושמים את הטוקן שנוצר. המחבר משתמש בו כדי לקרוא ל-API של GitHub, והוא מספק מכסת API לביצוע האינדוקס.

הגדרת המחבר

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

  1. משורת הפקודה, משנים את הספרייה ל-cloud-search-samples/end-to-end/connector/.
  2. פותחים את הקובץ sample-config.properties בכלי לעריכת טקסט.
  3. מגדירים את הפרמטר api.serviceAccountPrivateKeyFile לנתיב הקובץ של פרטי הכניסה לשירות שהורדתם קודם.
  4. מגדירים את הפרמטר api.sourceId למזהה של מקור הנתונים שיצרתם קודם.
  5. מגדירים את הפרמטר github.user לשם המשתמש שלכם ב-GitHub.
  6. מגדירים את הפרמטר github.token לאסימון הגישה שיצרתם קודם.
  7. שומרים את הקובץ.

עדכון הסכימה

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

mvn exec:java -Dexec.mainClass=com.google.cloudsearch.tutorial.SchemaTool \
    -Dexec.args="-Dconfig=sample-config.properties"

הפעלת המחבר

כדי להריץ את המחבר ולהתחיל ליצור אינדקס, מריצים את הפקודה:

mvn exec:java -Dexec.mainClass=com.google.cloudsearch.tutorial.GithubConnector \
    -Dexec.args="-Dconfig=sample-config.properties"

הגדרת ברירת המחדל של המחבר היא יצירת אינדקס של מאגר יחיד בארגון googleworkspace. הוספת המאגר לאינדקס נמשכת כדקה. אחרי האינדוקס הראשוני, המחבר ממשיך לבדוק אם יש שינויים במאגר שצריך לשקף באינדקס של Cloud Search.

בדיקת הקוד

בקטעים הבאים נבדוק איך בנוי המחבר.

הפעלת האפליקציה

נקודת הכניסה למחבר היא הכיתה GithubConnector. ה-method‏ main יוצרת מופע של IndexingApplication SDK ומפעילה אותו.

GithubConnector.java
/**
 * Main entry point for the connector. Creates and starts an indexing
 * application using the {@code ListingConnector} template and the sample's
 * custom {@code Repository} implementation.
 *
 * @param args program command line arguments
 * @throws InterruptedException thrown if an abort is issued during initialization
 */
public static void main(String[] args) throws InterruptedException {
  Repository repository = new GithubRepository();
  IndexingConnector connector = new ListingConnector(repository);
  IndexingApplication application = new IndexingApplication.Builder(connector, args)
      .build();
  application.start();
}

ListingConnector שסופק על ידי ה-SDK מטמיע אסטרטגיית מעבר שמתבססת על תורים של Cloud Search למעקב אחרי מצב הפריטים באינדקס. הוא מעביר את הבקשה אל GithubRepository, שמיושם על ידי מחבר לדוגמה, כדי לגשת לתוכן מ-GitHub.

מעבר בין מאגרי GitHub

במהלך סריקות מלאות, מתבצעת קריאה לשיטה getIds() כדי להעביר לפריטים בתור שאולי צריך להוסיף לאינדקס.

המחבר יכול להוסיף לאינדקס כמה מאגרי מידע או ארגונים. כדי למזער את ההשפעה של כשל, כל מאגר GitHub נסרק בנפרד. נקודת ביקורת מוחזרת עם תוצאות המעבר, שמכילה את רשימת המאגרים שיש לבצע בהם אינדקס בקריאות הבאות אל getIds(). אם מתרחשת שגיאה, ההוספה לאינדקס מתחדשת במאגר הנוכחי במקום להתחיל מההתחלה.

GithubRepository.java
/**
 * Gets all of the existing item IDs from the data repository. While
 * multiple repositories are supported, only one repository is traversed
 * per call. The remaining repositories are saved in the checkpoint
 * are traversed on subsequent calls. This minimizes the amount of
 * data that needs to be reindex in the event of an error.
 *
 * <p>This method is called by {@link ListingConnector#traverse()} during
 * <em>full traversals</em>. Every document ID and metadata hash value in
 * the <em>repository</em> is pushed to the Cloud Search queue. Each pushed
 * document is later polled and processed in the {@link #getDoc(Item)} method.
 * <p>
 * The metadata hash values are pushed to aid document change detection. The
 * queue sets the document status depending on the hash comparison. If the
 * pushed ID doesn't yet exist in Cloud Search, the document's status is
 * set to <em>new</em>. If the ID exists but has a mismatched hash value,
 * its status is set to <em>modified</em>. If the ID exists and matches
 * the hash value, its status is unchanged.
 *
 * <p>In every case, the pushed content hash value is only used for
 * comparison. The hash value is only set in the queue during an
 * update (see {@link #getDoc(Item)}).
 *
 * @param checkpoint value defined and maintained by this connector
 * @return this is typically a {@link PushItems} instance
 */
@Override
public CheckpointCloseableIterable<ApiOperation> getIds(byte[] checkpoint)
    throws RepositoryException {
  List<String> repositories;
  // Decode the checkpoint if present to get the list of remaining
  // repositories to index.
  if (checkpoint != null) {
    try {
      FullTraversalCheckpoint decodedCheckpoint = FullTraversalCheckpoint
          .fromBytes(checkpoint);
      repositories = decodedCheckpoint.getRemainingRepositories();
    } catch (IOException e) {
      throw new RepositoryException.Builder()
          .setErrorMessage("Unable to deserialize checkpoint")
          .setCause(e)
          .build();
    }
  } else {
    // No previous checkpoint, scan for repositories to index
    // based on the connector configuration.
    try {
      repositories = scanRepositories();
    } catch (IOException e) {
      throw toRepositoryError(e, Optional.of("Unable to scan repositories"));
    }
  }

  if (repositories.isEmpty()) {
    // Nothing left to index. Reset the checkpoint to null so the
    // next full traversal starts from the beginning
    Collection<ApiOperation> empty = Collections.emptyList();
    return new CheckpointCloseableIterableImpl.Builder<>(empty)
        .setCheckpoint((byte[]) null)
        .setHasMore(false)
        .build();
  }

  // Still have more repositories to index. Pop the next repository to
  // index off the list. The remaining repositories make up the next
  // checkpoint.
  String repositoryToIndex = repositories.get(0);
  repositories = repositories.subList(1, repositories.size());

  try {
    log.info(() -> String.format("Traversing repository %s", repositoryToIndex));
    Collection<ApiOperation> items = collectRepositoryItems(repositoryToIndex);
    FullTraversalCheckpoint newCheckpoint = new FullTraversalCheckpoint(repositories);
    return new CheckpointCloseableIterableImpl.Builder<>(items)
        .setHasMore(true)
        .setCheckpoint(newCheckpoint.toBytes())
        .build();
  } catch (IOException e) {
    String errorMessage = String.format("Unable to traverse repo: %s",
        repositoryToIndex);
    throw toRepositoryError(e, Optional.of(errorMessage));
  }
}

השיטה collectRepositoryItems() מטפלת במעבר על מאגר GitHub יחיד. השיטה הזו מחזירה אוסף של ApiOperations שמייצג את הפריטים שיועברו לתור. הפריטים נדחפים כשם משאב וכערך גיבוב (hash) שמייצג את המצב הנוכחי של הפריט.

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

GithubRepository.java
/**
 * Fetch IDs to  push in to the queue for all items in the repository.
 * Currently captures issues & content in the master branch.
 *
 * @param name Name of repository to index
 * @return Items to push into the queue for later indexing
 * @throws IOException if error reading issues
 */
private Collection<ApiOperation> collectRepositoryItems(String name)
    throws IOException {
  List<ApiOperation> operations = new ArrayList<>();
  GHRepository repo = github.getRepository(name);

  // Add the repository as an item to be indexed
  String metadataHash = repo.getUpdatedAt().toString();
  String resourceName = repo.getHtmlUrl().getPath();
  PushItem repositoryPushItem = new PushItem()
      .setMetadataHash(metadataHash);
  PushItems items = new PushItems.Builder()
      .addPushItem(resourceName, repositoryPushItem)
      .build();

  operations.add(items);
  // Add issues/pull requests & files
  operations.add(collectIssues(repo));
  operations.add(collectContent(repo));
  return operations;
}

עיבוד התור

אחרי שהמעבר המלא מסתיים, המחבר מתחיל לבצע בדיקות חוזרות בתור כדי למצוא פריטים שצריך להוסיף לאינדקס. השיטה getDoc() נקראת לכל פריט שנשלף מהתור. השיטה קוראת את הפריט מ-GitHub וממירה אותו לייצוג המתאים לאינדקס.

מכיוון שהמחבר פועל על נתונים פעילים שעשויים להשתנות בכל רגע, getDoc() גם מוודא שהפריט בתור עדיין תקף ומוחק מהאינדקס פריטים שכבר לא קיימים.

GithubRepository.java
/**
 * Gets a single data repository item and indexes it if required.
 *
 * <p>This method is called by the {@link ListingConnector} during a poll
 * of the Cloud Search queue. Each queued item is processed
 * individually depending on its state in the data repository.
 *
 * @param item the data repository item to retrieve
 * @return the item's state determines which type of
 * {@link ApiOperation} is returned:
 * {@link RepositoryDoc}, {@link DeleteItem}, or {@link PushItem}
 */
@Override
public ApiOperation getDoc(Item item) throws RepositoryException {
  log.info(() -> String.format("Processing item: %s ", item.getName()));
  Object githubObject;
  try {
    // Retrieve the item from GitHub
    githubObject = getGithubObject(item.getName());
    if (githubObject instanceof GHRepository) {
      return indexItem((GHRepository) githubObject, item);
    } else if (githubObject instanceof GHPullRequest) {
      return indexItem((GHPullRequest) githubObject, item);
    } else if (githubObject instanceof GHIssue) {
      return indexItem((GHIssue) githubObject, item);
    } else if (githubObject instanceof GHContent) {
      return indexItem((GHContent) githubObject, item);
    } else {
      String errorMessage = String.format("Unexpected item received: %s",
          item.getName());
      throw new RepositoryException.Builder()
          .setErrorMessage(errorMessage)
          .setErrorType(RepositoryException.ErrorType.UNKNOWN)
          .build();
    }
  } catch (FileNotFoundException e) {
    log.info(() -> String.format("Deleting item: %s ", item.getName()));
    return ApiOperations.deleteItem(item.getName());
  } catch (IOException e) {
    String errorMessage = String.format("Unable to retrieve item: %s",
        item.getName());
    throw toRepositoryError(e, Optional.of(errorMessage));
  }
}

לכל אחד מהאובייקטים ב-GitHub שהמחבר מבצע עליהם אינדוקס, השיטה המתאימה indexItem() מטפלת בבניית הייצוג של הפריט ב-Cloud Search. לדוגמה, כדי ליצור את הייצוג של פריטי תוכן:

GithubRepository.java
/**
 * Build the ApiOperation to index a content item (file).
 *
 * @param content      Content item to index
 * @param previousItem Previous item state in the index
 * @return ApiOperation (RepositoryDoc if indexing,  PushItem if not modified)
 * @throws IOException if unable to create operation
 */
private ApiOperation indexItem(GHContent content, Item previousItem)
    throws IOException {
  String metadataHash = content.getSha();

  // If previously indexed and unchanged, just requeue as unmodified
  if (canSkipIndexing(previousItem, metadataHash)) {
    return notModified(previousItem.getName());
  }

  String resourceName = new URL(content.getHtmlUrl()).getPath();
  FieldOrValue<String> title = FieldOrValue.withValue(content.getName());
  FieldOrValue<String> url = FieldOrValue.withValue(content.getHtmlUrl());

  String containerName = content.getOwner().getHtmlUrl().getPath();
  String programmingLanguage = FileExtensions.getLanguageForFile(content.getName());

  // Structured data based on the schema
  Multimap<String, Object> structuredData = ArrayListMultimap.create();
  structuredData.put("organization", content.getOwner().getOwnerName());
  structuredData.put("repository", content.getOwner().getName());
  structuredData.put("path", content.getPath());
  structuredData.put("language", programmingLanguage);

  Item item = IndexingItemBuilder.fromConfiguration(resourceName)
      .setTitle(title)
      .setContainerName(containerName)
      .setSourceRepositoryUrl(url)
      .setItemType(IndexingItemBuilder.ItemType.CONTAINER_ITEM)
      .setObjectType("file")
      .setValues(structuredData)
      .setVersion(Longs.toByteArray(System.currentTimeMillis()))
      .setHash(content.getSha())
      .build();

  // Index the file content too
  String mimeType = FileTypeMap.getDefaultFileTypeMap()
      .getContentType(content.getName());
  AbstractInputStreamContent fileContent = new InputStreamContent(
      mimeType, content.read())
      .setLength(content.getSize())
      .setCloseInputStream(true);
  return new RepositoryDoc.Builder()
      .setItem(item)
      .setContent(fileContent, IndexingService.ContentFormat.RAW)
      .setRequestMode(IndexingService.RequestMode.SYNCHRONOUS)
      .build();
}

לאחר מכן, פורסים את ממשק החיפוש.

הקודם הבא