Menerapkan konektor

Halaman tutorial Cloud Search ini menunjukkan cara menyiapkan sumber data dan konektor konten untuk mengindeks data. Untuk memulai dari awal tutorial ini, lihat tutorial memulai Cloud Search

Membuat konektor

Ubah direktori kerja Anda ke direktori cloud-search-samples/end-to-end/connector, lalu jalankan perintah ini:

mvn package -DskipTests

Perintah ini mendownload dependensi yang diperlukan untuk membuat konektor konten dan mengompilasi kode.

Membuat kredensial akun layanan

Konektor memerlukan kredensial akun layanan untuk memanggil Cloud Search API. Untuk membuat kredensial:

  1. Kembali ke Konsol Google Cloud.
  2. Di navigasi sebelah kiri, klik Credentials. Halaman "Credential" akan muncul.
  3. Klik menu drop-down + CREATE CREDENTIALS , lalu pilih Akun layanan. Halaman "Buat akun layanan" akan muncul.
  4. Di kolom Nama akun layanan, masukkan "tutorial".
  5. Catat nilai ID akun layanan (tepat setelah nama akun layanan). Nilai ini akan digunakan nanti.
  6. Klik CREATE. Dialog "Izin akun layanan (opsional)" akan muncul.
  7. Klik CONTINUE. Dialog "Grant users access to this service account (optional)" akan muncul.
  8. Klik DONE. Layar "Credentials" akan muncul.
  9. Di bagian Akun Layanan, klik email akun layanan. Halaman "service account details" akan muncul.
  10. Di bagian Keys, klik menu drop-down ADD KEY , lalu pilih Create new key. Dialog "Create private key" akan muncul.
  11. Klik CREATE.
  12. (opsional) Jika dialog "Do you want to allow downloads on console.cloud.google.com?” muncul, klik Allow.
  13. File kunci pribadi akan disimpan ke komputer Anda. Catat lokasi file yang didownload. File ini digunakan untuk mengonfigurasi konektor konten sehingga dapat mengautentikasi dirinya sendiri saat memanggil Google Cloud Search API.

Menginisialisasi dukungan pihak ketiga

Inisialisasi dukungan pihak ketiga untuk Google Cloud Search sebelum Anda memanggil Cloud Search API lainnya.

Untuk menginisialisasi dukungan pihak ketiga:

  1. Buat kredensial aplikasi web di project platform Cloud Search Anda. Lihat Membuat kredensial. Anda memerlukan client ID dan rahasia klien.
  2. Dapatkan token akses menggunakan OAuth 2.0 Playground:
    1. Klik OAuth 2.0 Configuration (ikon setelan) dan centang Use your own OAuth credentials.
    2. Masukkan client ID dan rahasia klien Anda.
    3. Di kolom cakupan, masukkan https://www.googleapis.com/auth/cloud_search.settings, lalu klik Authorize APIs.
    4. Klik Exchange authorization code for tokens.
  3. Jalankan perintah curl ini, dengan mengganti [YOUR_ACCESS_TOKEN] dengan token Anda:

    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
    

    Jika berhasil, isi respons akan menyertakan operation. Jika gagal, hubungi dukungan Cloud Search.

  4. Gunakan operations.get untuk memverifikasi inisialisasi:

    curl 'https://cloudsearch.googleapis.com/v1/operations/<var>operation_name</var>?key=[YOUR_API_KEY]' \
    --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
    --header 'Accept: application/json' \
    --compressed
    

    Inisialisasi selesai jika done adalah true.

Membuat sumber data

Selanjutnya, buat sumber data di konsol admin. Sumber data menyediakan namespace untuk mengindeks konten menggunakan konektor.

  1. Buka konsol Google Admin.
  2. Klik ikon Aplikasi. Halaman "Apps administration" akan muncul.
  3. Klik Google Workspace. Halaman "Apps Google Workspace administration" akan muncul.
  4. Scroll ke bawah, lalu klik Cloud Search. Halaman "Settings for Google Workspace" akan muncul.
  5. Klik Third-party data sources. Halaman "Data Sources" akan muncul.
  6. Klik + berwarna kuning bulat. Dialog "Add new data source" akan muncul.
  7. Di kolom Display name, ketik "tutorial".
  8. Di kolom Service account email addresses, masukkan alamat email akun layanan yang Anda buat di bagian sebelumnya. Jika Anda tidak mengetahui alamat email akun layanan, cari nilainya di halaman akun layanan.
  9. Klik ADD. Dialog "Successfully created data source" akan muncul.
  10. Klik *OK. Catat Source ID untuk sumber data yang baru dibuat. Source ID digunakan untuk mengonfigurasi konektor konten.

Membuat token akses pribadi untuk GitHub API

Konektor memerlukan akses yang diautentikasi ke GitHub API agar memiliki kuota yang memadai. Untuk mempermudah, konektor memanfaatkan token akses pribadi, bukan OAuth. Token pribadi memungkinkan autentikasi sebagai pengguna dengan serangkaian izin terbatas yang mirip dengan OAuth.

  1. Login ke GitHub.
  2. Di sudut kanan atas, klik foto profil Anda. Menu drop-down akan muncul.
  3. Klik Settings.
  4. Klik Developer settings.
  5. Klik Personal access tokens.
  6. Klik Generate personal access token.
  7. Di kolom Note, masukkan "Cloud Search tutorial".
  8. Centang cakupan public_repo.
  9. Klik Generate token.
  10. Catat token yang dihasilkan. Token ini digunakan oleh konektor untuk memanggil GitHub API dan menyediakan kuota API untuk melakukan pengindeksan.

Mengonfigurasi konektor

Setelah membuat kredensial dan sumber data, perbarui konfigurasi konektor untuk menyertakan nilai ini:

  1. Dari command line, ubah direktori ke cloud-search-samples/end-to-end/connector/.
  2. Buka file sample-config.properties dengan editor teks.
  3. Tetapkan parameter api.serviceAccountPrivateKeyFile ke jalur file kredensial layanan yang Anda download sebelumnya.
  4. Tetapkan parameter api.sourceId ke ID sumber data yang Anda buat sebelumnya.
  5. Tetapkan parameter github.user ke nama pengguna GitHub Anda.
  6. Tetapkan parameter github.token ke token akses yang Anda buat sebelumnya.
  7. Simpan file.

Memperbarui skema

Konektor mengindeks konten terstruktur dan tidak terstruktur. Sebelum mengindeks data, Anda harus memperbarui skema untuk sumber data. Jalankan perintah berikut untuk memperbarui skema:

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

Menjalankan konektor

Untuk menjalankan konektor dan mulai mengindeks, jalankan perintah:

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

Konfigurasi default untuk konektor adalah mengindeks satu repositori di organisasi googleworkspace. Pengindeksan repositori memerlukan waktu sekitar 1 menit. Setelah pengindeksan awal, konektor akan terus melakukan polling untuk mengetahui perubahan pada repositori yang perlu ditampilkan dalam indeks Cloud Search.

Meninjau kode

Bagian yang tersisa akan membahas cara konektor dibuat.

Memulai aplikasi

Titik entri ke konektor adalah class GithubConnector. Metode main membuat instance SDK's IndexingApplication dan memulainya.

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();
}

The ListingConnector yang disediakan oleh SDK menerapkan strategi traversal yang memanfaatkan antrean Cloud Search untuk melacak status item dalam indeks. Konektor ini mendelegasikan ke GithubRepository, yang diimplementasikan oleh konektor contoh, untuk mengakses konten dari GitHub.

Melakukan traversal repositori GitHub

Selama traversal penuh, metode getIds() dipanggil untuk mendorong item yang mungkin perlu diindeks ke dalam antrean.

Konektor dapat mengindeks beberapa repositori atau organisasi. Untuk meminimalkan dampak kegagalan, satu repositori GitHub akan di-traverse dalam satu waktu. Checkpoint ditampilkan dengan hasil traversal yang berisi daftar repositori yang akan diindeks dalam panggilan berikutnya ke getIds(). Jika terjadi error, pengindeksan akan dilanjutkan di repositori saat ini, bukan dimulai dari awal.

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));
  }
}

Metode collectRepositoryItems() menangani traversal satu repositori GitHub. Metode ini menampilkan kumpulan ApiOperations yang mewakili item yang akan didorong ke dalam antrean. Item didorong sebagai nama resource dan nilai hash yang mewakili status item saat ini.

Nilai hash digunakan dalam traversal repositori GitHub berikutnya. Nilai ini memberikan pemeriksaan ringan untuk menentukan apakah konten telah berubah tanpa harus mengupload konten tambahan. Konektor mengantrekan semua item secara otomatis. Jika item baru atau nilai hash telah berubah, item tersebut akan tersedia untuk polling dalam antrean. Jika tidak, item akan dianggap tidak diubah.

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

Memproses antrean

Setelah traversal penuh selesai, konektor akan mulai melakukan polling antrean untuk item yang perlu diindeks. Metode getDoc() dipanggil untuk setiap item yang diambil dari antrean. Metode ini membaca item dari GitHub dan mengonversinya menjadi representasi yang tepat untuk pengindeksan.

Karena konektor berjalan terhadap data aktif yang dapat diubah kapan saja, getDoc() juga memverifikasi bahwa item dalam antrean masih valid dan menghapus item apa pun dari indeks yang tidak lagi ada.

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));
  }
}

Untuk setiap objek GitHub yang diindeks konektor, metode indexItem() yang sesuai akan menangani pembuatan representasi item untuk Cloud Search. Misalnya, untuk membuat representasi item konten:

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();
}

Selanjutnya, deploy antarmuka penelusuran.

Sebelumnya Berikutnya