פריסת המחבר

בדף הזה במדריך של 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 ובוחרים חשבון שירות. האפשרות 'יצירת חשבון שירות' מופיעה.
  4. בשדה Service account name, מזינים 'tutorial'.
  5. שימו לב לערך של מזהה חשבון השירות (מיד אחרי השם של חשבון השירות). ייעשה שימוש בערך הזה מאוחר יותר.
  6. לוחצים על יצירה. העמודה 'הרשאות חשבון שירות (אופציונלי)' תופיע תיבת דו-שיח.
  7. לוחצים על המשך. השדה 'נותנים למשתמשים גישה לחשבון השירות הזה (אופציונלי)" תופיע תיבת דו-שיח.
  8. לוחצים על סיום. השדות 'פרטי כניסה' מופיעה.
  9. בקטע 'חשבונות שירות', לוחצים על כתובת האימייל של חשבון השירות. "השירות" פרטי החשבון" הצעות מחיר.
  10. בקטע 'מפתחות', לוחצים על הרשימה הנפתחת הוספת מפתח ובוחרים יצירת מפתח חדש. הלחצן 'יצירת מפתח פרטי' תופיע תיבת דו-שיח.
  11. לוחצים על יצירה.
  12. (אופציונלי) אם ההודעה 'האם לאפשר הורדות ב: 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. לוחצים על סגירה.
    4. בשדה 'היקפים', מקלידים 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. הדף 'הגדרות ב-Google Workspace' דף מופיעה.
  5. לוחצים על מקורות נתונים של צד שלישי. מקורות הנתונים מופיעה.
  6. לוחצים על הסמל הצהוב + העגול. האפשרות 'הוספה של מקור נתונים חדש' תופיע תיבת דו-שיח.
  7. בשדה Display name, מקלידים 'tutorial'.
  8. בשדה Service account email addresses, מזינים את כתובת האימייל של חשבון השירות שיצרתם בקטע הקודם. אם אתם לא יודעים כתובת האימייל של חשבון השירות, מחפשים את הערך ה חשבונות שירות הדף הזה.
  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. רושמים או זוכרים את האסימון שנוצר. המחבר משתמש בו כדי לקרוא ל-GitHub ממשקי API ומספקת מכסת 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 שמייצגים את הפריטים שיש להעביר אותם לתור. פריטים נדחפים כ- שם משאב וערך גיבוב (hash) שמייצג את המצב הנוכחי של הפריט.

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

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

הקודם הבא