نشر الموصِّل

تعرض هذه الصفحة من برنامج Cloud Search التعليمي كيفية إعداد مصدر بيانات وموصِّل محتوى لفهرسة البيانات. للبدء من بداية هذا البرنامج التعليمي، راجِع الدليل التعليمي حول بدء استخدام Cloud Search

بناء الموصل

غيِّر دليل العمل إلى دليل cloud-search-samples/end-to-end/connector وشغِّل الأمر التالي:

mvn package -DskipTests

يقوم الأمر بتنزيل التبعيات المطلوبة اللازمة لإنشاء موصل المحتوى وتجميع التعليمات البرمجية.

إنشاء بيانات اعتماد لحساب الخدمة

يتطلب الموصِّل بيانات اعتماد حساب الخدمة لطلب واجهات برمجة تطبيقات Cloud Search. لإنشاء بيانات الاعتماد:

  1. ارجِع إلى وحدة تحكُّم Google Cloud.
  2. في شريط التنقل الأيمن، انقر على بيانات الاعتماد. ستظهر لك صفحة "بيانات الاعتماد".
  3. انقر على القائمة المنسدلة + إنشاء بيانات الاعتماد واختَر حساب الخدمة. ستظهر لك صفحة "إنشاء حساب خدمة".
  4. في الحقل اسم حساب الخدمة، أدخِل "البرنامج التعليمي".
  5. دوِّن قيمة رقم تعريف حساب الخدمة (بعد اسم حساب الخدمة مباشرةً). يتم استخدام هذه القيمة لاحقًا.
  6. انقر على إنشاء. سيظهر مربّع الحوار "أذونات حساب الخدمة (اختيارية)".
  7. انقر على متابعة. سيظهر مربّع الحوار "منح المستخدمين إذن الوصول إلى حساب الخدمة هذا (اختياري)".
  8. انقر على تم. ستظهر شاشة "بيانات الاعتماد".
  9. ضِمن "حسابات الخدمة"، انقر على البريد الإلكتروني لحساب الخدمة. تظهر صفحة "تفاصيل حساب الخدمة".
  10. ضمن "المفاتيح"، انقر على القائمة المنسدلة إضافة مفتاح واختَر إنشاء مفتاح جديد. سيظهر مربع الحوار "إنشاء مفتاح خاص".
  11. انقر على إنشاء.
  12. (اختياري) إذا ظهر مربع الحوار "هل تريد السماح بعمليات التنزيل على console.cloud.google.com؟"، انقر على السماح.
  13. يتم حفظ ملف مفتاح خاص على جهاز الكمبيوتر. لاحظ موقع الملف الذي تم تنزيله. يُستخدم هذا الملف لإعداد موصِّل المحتوى حتى يمكنه مصادقة نفسه عند استدعاء واجهات برمجة تطبيقات Google Cloud Search.

تهيئة دعم الجهات الخارجية

قبل أن تتمكن من طلب أي واجهات برمجة تطبيقات أخرى في 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 وانقر على تفويض. تعرض واجهة OAuth 2 رمز تفويض.
    5. انقر على رمز تفويض Exchange للرموز المميّزة. يتم إرجاع رمز مميّز.
  3. لإعداد دعم الجهات الخارجية لـ Cloud Search، استخدم أمر curl التالي. احرص على استبدال [YOUR_ACCESS_TOKEN] بالرمز المميّز الذي تم الحصول عليه في الخطوة الثانية.

    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. انقر على رمز التطبيقات. تظهر صفحة "إدارة التطبيقات".
  3. انقر على Google Workspace. ستظهر لك صفحة "إدارة Google Workspace".
  4. انتقِل للأسفل وانقر على Cloud Search. تظهر صفحة "إعدادات Google Workspace".
  5. انقر على مصادر البيانات التابعة لجهات خارجية. ستظهر لك صفحة "مصادر البيانات".
  6. انقر على المربّع الأصفر المستدير +، وسيظهر مربّع الحوار "إضافة مصدر بيانات جديد".
  7. في الحقل الاسم المعروض، اكتب "فيديو تعليمي".
  8. في حقل عناوين البريد الإلكتروني لحساب الخدمة، أدخِل عنوان البريد الإلكتروني لحساب الخدمة الذي أنشأته في القسم السابق. إذا كنت لا تعرف عنوان البريد الإلكتروني لحساب الخدمة، ابحث عن القيمة في صفحة حسابات الخدمة.
  9. انقر على إضافة. سيظهر مربّع الحوار "تم إنشاء مصدر البيانات بنجاح".
  10. انقر على *حسنًا. دوِّن معرّف المصدر لمصدر البيانات الذي تمّ إنشاؤه حديثًا. يُستخدم معرّف المصدر في ضبط موصِّل المحتوى.

إنشاء رمز دخول شخصي لواجهة GitHub API

يتطلب الموصل وصولاً مصادقًا إلى واجهة برمجة تطبيقات GitHub للحصول على حصة كافية. للتبسيط، يستفيد الموصل من رموز الدخول الشخصية بدلاً من OAuth. تتيح الرموز المميزة الشخصية إجراء المصادقة كمستخدم لديه مجموعة محدودة من الأذونات المشابهة لـ OAuth.

  1. سجِّل الدخول إلى GitHub.
  2. في أعلى يسار الصفحة، انقر على صورة ملفك الشخصي. تظهر قائمة منسدلة.
  3. انقر على الإعدادات.
  4. انقر على إعدادات المطوِّر.
  5. انقر على رموز الدخول الشخصية.
  6. انقر على إنشاء رمز دخول شخصي.
  7. في الحقل ملاحظة، أدخِل "الدليل التوجيهي حول Cloud Search".
  8. تحقَّق من النطاق public_repo.
  9. انقر على إنشاء رمز مميّز.
  10. سجِّل الرمز المميّز الذي تم إنشاؤه. ويستخدمه الموصل لاستدعاء واجهات برمجة تطبيقات GitHub وتوفّر حصة لواجهة برمجة التطبيقات لإجراء الفهرسة.

ضبط الموصل

بعد إنشاء بيانات الاعتماد ومصدر البيانات، يمكنك تحديث تهيئة الموصل لتضمين القيم التالية:

  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 تمثل العناصر المراد دفعها إلى قائمة الانتظار. يتم دفع العناصر كاسم مورد وقيمة تجزئة تمثل الحالة الحالية للعنصر.

يتم استخدام قيمة التجزئة في عمليات التمرير اللاحقة لمستودعات 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();
}

بعد ذلك، انشر واجهة البحث.

السابق التالي