פריסת המחבר

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

בניית המחבר

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

mvn package -DskipTests

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

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

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

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

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

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

להפעלת תמיכה של צד שלישי ב-Cloud Search:

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

  2. משתמשים במגרש המשחקים של OAuth 2 של Google כדי לקבל אסימון גישה:

    1. לוחצים על 'הגדרות' ומסמנים את האפשרות שימוש בפרטי הכניסה שלך לאימות.
    2. מזינים את מזהה הלקוח ואת סוד הלקוח משלב 1.
    3. לוחצים על Close.
    4. בשדה ההיקפים, מקלידים https://www.googleapis.com/auth/cloud_search.settings ולוחצים על Authorize. מגרש המשחקים של OAuth 2 מחזיר קוד הרשאה.
    5. לוחצים על החלפת קוד ההרשאה באסימונים. מוחזר אסימון.
  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. בשדה שם תצוגה, מקלידים 'מדריך'.
  8. בשדה Service account email addresses, מזינים את כתובת האימייל של חשבון השירות שיצרתם בקטע הקודם. אם לא יודעים את כתובת האימייל של חשבון השירות, אפשר לחפש את הערך בדף חשבון שירות.
  9. לוחצים על ADD. מופיעה תיבת הדו-שיח 'מקור הנתונים נוצר בהצלחה'.
  10. לוחצים על *אישור. חשוב לזכור את מזהה המקור של מקור הנתונים החדש שנוצר. מזהה המקור משמש להגדרת מחבר התוכן.

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

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

  1. מתחברים ל-GitHub.
  2. בפינה השמאלית העליונה, לוחצים על תמונת הפרופיל. יופיע תפריט נפתח.
  3. לוחצים על הגדרות.
  4. לוחצים על הגדרות למפתחים.
  5. לוחצים על אסימוני גישה אישית.
  6. לוחצים על יצירת אסימון גישה אישי.
  7. בשדה הערה, מזינים 'מדריך Cloud Search'.
  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. השיטה 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 שמייצג את הפריטים שיש לדחוף אותם לתור. הפריטים נשלחים כשם המשאב וערך גיבוב שמייצג את המצב הנוכחי של הפריט.

ערך הגיבוב משמש במעברים הבאים של מאגרי 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();
}

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

הקודם הבא