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 dan jalankan perintah ini:

mvn package -DskipTests

Perintah ini akan 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 Google Cloud Console.
  2. Di navigasi sebelah kiri, klik Credentials. Halaman "Kredensial" akan muncul.
  3. Klik menu drop-down + CREATE KREDENTIALS dan pilih Service account. Halaman "Create service account" akan muncul.
  4. Di kolom Nama akun layanan, masukkan "tutorial".
  5. Catat nilai ID akun Layanan (tepat setelah nama akun Layanan). Nilai ini digunakan nanti.
  6. Klik CREATE. Dialog "Izin akun layanan (opsional)" akan muncul.
  7. Klik LANJUTKAN. Dialog "Beri pengguna akses ke akun layanan ini (opsional)" akan muncul.
  8. Klik SELESAI. Layar "Credentials" akan muncul.
  9. Di bagian Akun Layanan, klik email akun layanan. Halaman "detail akun layanan" akan ditampilkan.
  10. Di bagian Keys, klik menu drop-down ADD KEY dan 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 disimpan ke komputer Anda. Catat lokasi file yang didownload. File ini digunakan untuk mengonfigurasi konektor konten sehingga dapat mengautentikasi dirinya sendiri saat memanggil API Google Cloud Search.

Menginisialisasi dukungan pihak ketiga

Sebelum dapat memanggil API Cloud Search lainnya, Anda harus melakukan inisialisasi dukungan pihak ketiga untuk Google Cloud Search.

Guna melakukan inisialisasi dukungan pihak ketiga untuk Cloud Search:

  1. Project platform Cloud Search Anda berisi kredensial akun layanan. Namun, untuk menginisialisasi dukungan pihak ketiga, Anda harus membuat kredensial aplikasi web. Untuk mengetahui petunjuk cara membuat kredensial aplikasi web, lihat Membuat kredensial. Setelah menyelesaikan langkah ini, Anda akan memiliki file client ID dan rahasia klien.

  2. Gunakan Google's OAuth 2 playground untuk mendapatkan token akses:

    1. Klik setelan dan centang User your own auth credentials.
    2. Masukkan client ID dan rahasia klien dari langkah 1.
    3. Klik Close.
    4. Di kolom cakupan, ketik https://www.googleapis.com/auth/cloud_search.settings, lalu klik Authorize. Playground OAuth 2 menampilkan kode otorisasi.
    5. Klik Exchange otorisasi kode untuk token. Token ditampilkan.
  3. Guna melakukan inisialisasi dukungan pihak ketiga untuk Cloud Search, gunakan perintah curl berikut. Pastikan untuk mengganti [YOUR_ACCESS_TOKEN] dengan token yang diperoleh pada langkah 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
    

    Jika berhasil, isi respons berisi instance operation. Contoh:

    {
    name: "operations/customers/01b3fqdm/lro/AOIL6eBv7fEfiZ_hUSpm8KQDt1Mnd6dj5Ru3MXf-jri4xK6Pyb2-Lwfn8vQKg74pgxlxjrY"
    }
    

    Jika tidak berhasil, hubungi dukungan Cloud Search.

  4. Gunakan operations.get untuk memverifikasi bahwa dukungan pihak ketiga telah diinisialisasi:

    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
    

    Setelah inisialisasi pihak ketiga selesai, inisialisasi akan berisi kolom done yang ditetapkan ke true. Contoh:

    {
    name: "operations/customers/01b3fqdm/lro/AOIL6eBv7fEfiZ_hUSpm8KQDt1Mnd6dj5Ru3MXf-jri4xK6Pyb2-Lwfn8vQKg74pgxlxjrY"
    done: 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 "Administrasi aplikasi" akan muncul.
  3. Klik Google Workspace. Halaman "Administrasi Google Workspace aplikasi" akan muncul.
  4. Scroll ke bawah, lalu klik Cloud Search. Halaman "Setelan untuk Google Workspace" akan muncul.
  5. Klik Sumber data pihak ketiga. Halaman "Sumber Data" akan muncul.
  6. Klik lingkaran kuning +. Dialog "Tambahkan sumber data baru" akan muncul.
  7. Di kolom Nama tampilan, ketik "tutorial".
  8. Di kolom Alamat email akun layanan, masukkan alamat email akun layanan yang dibuat di bagian sebelumnya. Jika Anda tidak tahu alamat email akun layanan, cari nilai di halaman akun layanan.
  9. Klik TAMBAHKAN. Dialog "Sumber data berhasil dibuat" akan muncul.
  10. Klik *OK. Perhatikan ID Sumber untuk sumber data yang baru dibuat. ID Sumber digunakan untuk mengonfigurasi konektor konten.

Membuat token akses pribadi untuk GitHub API

Konektor memerlukan akses terautentikasi ke GitHub API agar memiliki kuota yang cukup. Untuk memudahkan, konektor memanfaatkan token akses pribadi, bukan OAuth. Token pribadi memungkinkan otentikasi sebagai pengguna dengan sekumpulan izin terbatas yang mirip dengan OAuth.

  1. Login ke GitHub.
  2. Di pojok kanan atas, klik foto profil Anda. Sebuah menu {i>drop-down <i}akan muncul.
  3. Klik Setelan.
  4. Klik Setelan developer.
  5. Klik Token akses pribadi.
  6. Klik Buat token akses pribadi.
  7. Di kolom Catatan, masukkan "Tutorial Cloud Search".
  8. Periksa cakupan public_repo.
  9. Klik Generate Token.
  10. Catat token yang dibuat. Digunakan oleh konektor untuk memanggil GitHub API dan memberikan kuota API untuk melakukan pengindeksan.

Mengonfigurasi konektor

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

  1. Dari command line, ubah direktori menjadi 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. Setel 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 dalam organisasi googleworkspace. Mengindeks repositori memerlukan waktu sekitar 1 menit. Setelah pengindeksan awal, konektor akan terus melakukan polling untuk perubahan pada repositori yang perlu ditampilkan dalam indeks Cloud Search.

Meninjau kode

Bagian yang tersisa memeriksa cara konektor dibuat.

Memulai aplikasi

Titik entri ke konektor adalah class GithubConnector. Metode main membuat instance IndexingApplication SDK 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();
}

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

Melintasi 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 dilalui pada satu waktu. Sebuah 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 memulai 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 repo GitHub. Metode ini menampilkan kumpulan ApiOperations yang mewakili item yang akan dikirim ke antrean. Item dikirim sebagai nama resource dan nilai hash yang mewakili status item saat ini.

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

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 mulai mengumpulkan 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.

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

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 oleh konektor, metode indexItem() yang sesuai menangani pembuatan representasi item untuk Cloud Search. Misalnya, untuk membangun 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