פריסת המחבר

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

יצירת המחבר

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

mvn package -DskipTests

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

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

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

  1. חוזרים למסוף Google Cloud.
  2. בחלונית הניווט השמאלית, לוחצים על Credentials (פרטי כניסה). יופיע הדף 'פרטי כניסה'.
  3. לוחצים על הרשימה הנפתחת + CREATE CREDENTIALS ובוחרים באפשרות Service account. יופיע הדף 'יצירת חשבון שירות'.
  4. בשדה Service account name, מזינים "tutorial".
  5. שימו לב לערך של מזהה חשבון השירות (מיד אחרי השם של חשבון השירות). ייעשה שימוש בערך הזה מאוחר יותר.
  6. לוחצים על יצירה. תיבת הדו-שיח 'הרשאות חשבון שירות (אופציונלי)' מופיעה.
  7. לוחצים על המשך. מופיעה תיבת הדו-שיח 'Grant users access to this service account (optional)'.
  8. לוחצים על סיום. המסך 'פרטי כניסה' יופיע.
  9. בקטע 'חשבונות שירות', לוחצים על כתובת האימייל של חשבון השירות. הקישורים הדף 'פרטי חשבון שירות'
  10. בקטע Keys (מפתחות), לוחצים על הרשימה הנפתחת ADD KEY ובוחרים באפשרות Create new key. מופיעה תיבת הדו-שיח 'יצירת מפתח פרטי'.
  11. לוחצים על יצירה.
  12. (אופציונלי) אם מופיעה תיבת הדו-שיח 'Do you want toAllow Download 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. בשדה Scopes, מקלידים https://www.googleapis.com/auth/cloud_search.settings ולוחצים על Authorize. ה-Playground של 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. הדף Settings for Google Workspace יופיע.
  5. לוחצים על מקורות נתונים של צד שלישי. הדף 'מקורות נתונים' יופיע.
  6. לוחצים על העיגול הצהוב +. מופיעה תיבת הדו-שיח 'הוספת מקור נתונים חדש'.
  7. בשדה Display name, מקלידים 'tutorial'.
  8. בשדה Service account email addresses, מזינים את כתובת האימייל של חשבון השירות שיצרתם בקטע הקודם. אם לא יודעים מה כתובת האימייל של חשבון השירות, אפשר לחפש אותו בדף service accounts.
  9. לוחצים על ADD. תופיע תיבת הדו-שיח 'מקור הנתונים נוצר בהצלחה'.
  10. לוחצים על *אישור. שימו לב למזהה המקור של מקור הנתונים החדש שנוצר. מזהה המקור משמש להגדרה של מחבר התוכן.

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

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

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

ה-method 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;
}

מתבצע עיבוד של התור

לאחר השלמת המעבר המלא, המחבר מתחיל לדגום את התור לפריטים שצריך להוסיף לאינדקס. מתבצעת קריאה ל-method getDoc() לכל פריט שנשלף מהתור. ה-method קוראת את הפריט מ-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();
}

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

הקודם הבא