نشر الموصِّل

تعرض هذه الصفحة من دليل 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، يمكنك استخدام الحلقة التالية الأمر. تأكَّد من استبدال [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 API للترتيب للحصول على حصة كافية. ولتبسيط الأمر، يستفيد الموصل من البيانات الشخصية بدلاً من 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

خلال عمليات الاجتياز الكاملة، تعرض سمة getIds() لدفع العناصر التي قد تحتاج إلى فهرستها في قائمة الانتظار.

يمكن للموصل فهرسة مستودعات أو مؤسسات متعددة. لتقليد تأثير الإخفاق، يتم اجتياز مستودع جيت هب واحد في كل مرة. نقطة تفتيش مع نتائج الاجتياز التي تحتوي على قائمة المستودعات التي ستتم فهرستها في عمليات الاستدعاء اللاحقة إلى 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));
  }
}

يقوم فهارس الموصل الخاصة بكل من كائنات جيت هب، تعالج الطريقة 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();
}

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

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