部署連接器

這個頁面的 Cloud Search 教學課程說明如何設定資料來源 和內容連接器來建立索引 如要從這個教學課程開始著手,請參閱 Cloud Search 入門教學課程

建構連接器

將工作目錄變更為 cloud-search-samples/end-to-end/connector ,然後執行下列指令:

mvn package -DskipTests

這個指令會下載建構映像檔所需的依附元件 並編譯程式碼。

建立服務帳戶憑證

連接器需要服務帳戶憑證才能呼叫 Cloud Search 相互整合如要建立憑證,請按照下列指示操作:

  1. 返回 Google Cloud 控制台
  2. 在左側導覽列中,按一下「Credentials」。「憑證」出現。
  3. 按一下「+ 建立憑證」下拉式清單,然後選取 服務帳戶。「建立服務帳戶」出現。
  4. 在「服務帳戶名稱」欄位中輸入「tutorial」。
  5. 記下服務帳戶 ID 值 (緊接在服務帳戶名稱後方)。 這個值稍後會用到。
  6. 按一下「建立」。「服務帳戶權限 (選用)」對話方塊。
  7. 點選「繼續」。「將存取權授予使用者 (選答)對話方塊。
  8. 點按「完成」。「憑證」畫面上會顯示提示訊息。
  9. 在「服務帳戶」下方,按一下服務帳戶電子郵件。「service」 帳戶詳細資料」套用頁面設計
  10. 按一下「金鑰」下方的「新增金鑰」下拉式清單,然後選取 建立新的金鑰。「建立私密金鑰」對話方塊。
  11. 按一下 [建立]
  12. (選用) 如果「您要允許在 console.cloud.google.com”對話方塊中,按一下 [Allow] (允許)
  13. 私密金鑰檔案會儲存至您的電腦。記下這個位置 。這個檔案可用來設定內容連接器 就能在呼叫 Google Cloud Search API 時自行驗證

初始化第三方支援

您必須先將第三方初始化,才能呼叫任何其他 Cloud Search API Google Cloud Search 支援服務

如何初始化 Cloud Search 的第三方支援:

  1. 您的 Cloud Search 平台專案含有服務帳戶憑證。 不過,為了初始化第三方支援,您必須建立網路 應用程式憑證如需如何建立網頁應用程式的說明 憑證,請參考 建立憑證。 完成這個步驟後,您應該擁有用戶端 ID 和用戶端密鑰檔案。

  2. 使用 Google 的 OAuth 2 Playground 取得存取權杖:

    1. 按一下「設定」,然後勾選「使用您自己的驗證憑證」
    2. 輸入步驟 1 的用戶端 ID 和用戶端密鑰。
    3. 按一下「關閉」
    4. 在範圍欄位中輸入 https://www.googleapis.com/auth/cloud_search.settings 然後按一下「授權」。OAuth 2 Playground 會傳回授權碼。
    5. 按一下「Exchange License code for token」。傳回權杖。
  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
    }
    

建立資料來源

接下來,請在管理控制台中建立資料來源。資料來源 提供使用連接器,以便建立內容索引的命名空間。

  1. 開啟 Google 管理控制台
  2. 按一下「應用程式」圖示。「Apps 管理」出現。
  3. 點按「Google Workspace」。「Google Workspace 管理應用程式」出現。
  4. 向下捲動,然後按一下「Cloud Search」。「Google Workspace 設定」第 頁 出現。
  5. 按一下「第三方資料來源」。「資料來源」出現。
  6. 按一下黃色圓形的 +。「新增資料來源」對話方塊。
  7. 在「顯示名稱」欄位中輸入「tutorial」。
  8. 在「服務帳戶電子郵件地址」欄位中,輸入 建立在上一節建立的服務帳戶如果您不知道 電子郵件地址,請前往 這個 服務帳戶 頁面。
  9. 點選「新增」。「已成功建立資料來源」對話方塊。
  10. 按一下 *「確定」。記下新建資料來源的「來源 ID」。 來源 ID 可用來設定內容連接器。

產生 GitHub API 的個人存取權杖

連接器需要通過 GitHub API 驗證的存取權 才能擁有足夠的配額為簡單起見,連接器會使用 存取權杖,而非 OAuth。個人權杖可讓系統以下列身分進行驗證: 並授予類似 OAuth 的有限權限集合使用者

  1. 登入 GitHub。
  2. 按一下右上角的個人資料相片。下拉式選單 出現。
  3. 按一下 [設定]。
  4. 按一下「開發人員設定」
  5. 按一下「Personal access token」
  6. 按一下「產生個人存取權杖」
  7. 在「附註」欄位中,輸入「Cloud Search 教學課程」。
  8. 檢查 public_repo 範圍。
  9. 按一下「產生權杖」
  10. 請記下系統產生的權杖。連接器會透過該連結呼叫 GitHub 並提供可執行索引的 API 配額。

設定連接器

建立憑證和資料來源後,請更新連接器 包括這些值:

  1. 在指令列中,將目錄變更為 cloud-search-samples/end-to-end/connector/
  2. 使用文字編輯器開啟 sample-config.properties 檔案。
  3. api.serviceAccountPrivateKeyFile 參數設為 先前下載的 Service 憑證
  4. api.sourceId 參數設為您資料來源的 ID 先前建立的物件
  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」組織。為存放區建立索引大約需要 1 分鐘。 首次建立索引後,連接器會持續輪詢,持續輪詢 需要反映在 Cloud Search 索引中的存放區。

查看程式碼

以下各節將說明連接器的建構方式。

啟動應用程式

連接器的進入點為 GithubConnector 類別。 main 方法會將 SDK 的 IndexingApplication 執行個體化 並開始啟動

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 導入這項週遊策略 運用 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() 方法會處理單一 存取 Cloud Bigtable 或 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() 方法會對從佇列提取的每個項目呼叫方法。此方法會讀取 將該項目轉換為適當的表示法 建立索引。

由於連接器正在針對即時資料執行,因此隨時可能變更 時間,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();
}

接下來,請部署搜尋介面。

返回 繼續