콘텐츠 커넥터 만들기

콘텐츠 커넥터는 엔터프라이즈 저장소의 데이터를 순회하고 데이터 소스를 채우는 소프트웨어 프로그램입니다. Google은 콘텐츠 커넥터 개발을 위해 다음과 같은 옵션을 제공합니다.

  • 콘텐츠 커넥터 SDK Java 프로그래머에게 적합한 옵션입니다. SDK는 커넥터를 빠르게 만들 수 있는 REST API를 둘러싸는 래퍼입니다. SDK를 사용하여 콘텐츠 커넥터를 만들려면 콘텐츠 커넥터 SDK를 사용하여 콘텐츠 커넥터 만들기를 참고하세요.

  • 하위 수준 REST API 또는 API 라이브러리: Java를 사용하지 않거나 코드베이스가 REST API나 라이브러리에 더 적합한 경우 이 옵션을 사용하세요. REST API를 사용하여 콘텐츠 커넥터를 만들려면 REST API를 사용하여 콘텐츠 커넥터 만들기를 참고하세요.

콘텐츠 커넥터는 일반적으로 다음의 작업을 수행합니다.

  1. 구성 매개변수를 읽고 처리합니다.
  2. 서드 파티 저장소에서 '항목'이라는 색인 생성이 가능한 데이터의 개별 청크를 가져옵니다.
  3. ACL, 메타데이터, 콘텐츠 데이터를 색인 생성이 가능한 항목으로 결합합니다.
  4. 항목의 색인을 Cloud Search 데이터 소스로 생성합니다.
  5. (선택사항) 저장소의 변경 알림을 수신합니다. 변경 알림은 색인 생성 요청으로 변환되어 Cloud Search 데이터 소스를 동기화된 상태로 유지합니다. 커넥터는 저장소가 변경 감지를 지원하는 경우에만 이 작업을 실행합니다.

콘텐츠 커넥터 SDK를 사용하여 콘텐츠 커넥터 만들기

다음 섹션에서는 콘텐츠 커넥터 SDK를 사용하여 콘텐츠 커넥터를 만드는 방법을 설명합니다.

종속 항목 설정

빌드 파일에 이러한 종속 항목을 포함합니다.

Maven

xml <dependency> <groupId>com.google.enterprise.cloudsearch</groupId> <artifactId>google-cloudsearch-indexing-connector-sdk</artifactId> <version>v1-0.0.3</version> </dependency>

Gradle

groovy compile group: 'com.google.enterprise.cloudsearch', name: 'google-cloudsearch-indexing-connector-sdk', version: 'v1-0.0.3'

커넥터 구성 만들기

모든 커넥터는 저장소 ID와 같은 매개변수에 구성 파일을 사용합니다. api.sourceId=1234567890abcdef와 같은 키-값 쌍으로 매개변수를 정의합니다.

Google Cloud Search SDK에는 모든 커넥터의 Google 제공 매개변수가 포함되어 있습니다. 구성 파일에서 다음을 선언해야 합니다.

  • 콘텐츠 커넥터: api.sourceIdapi.serviceAccountPrivateKeyFile을 선언합니다. 이러한 매개변수는 저장소와 액세스에 필요한 비공개 키를 식별합니다.
  • ID 커넥터: api.identitySourceId를 선언하여 외부 ID 소스를 식별합니다. 사용자 동기화의 경우 api.customerId (Google Workspace 계정의 고유 ID)도 선언합니다.

다른 Google 제공 매개변수는 기본값을 재정의하는 경우에만 선언합니다. ID 및 키 생성에 관한 자세한 내용은 Google 제공 매개변수를 참고하세요.

구성 파일에서 저장소별 매개변수를 정의할 수도 있습니다.

커넥터에 구성 파일 전달

config 시스템 속성을 설정하여 구성 파일을 전달합니다. 커넥터를 시작할 때 -D 인수를 사용합니다. 예를 들면 다음과 같습니다.

java -classpath myconnector.jar -Dconfig=MyConfig.properties MyConnector

이 인수를 생략하면 SDK는 로컬 디렉터리에서 connector-config.properties라는 파일을 사용하려고 시도합니다.

순회 전략 결정

콘텐츠 커넥터의 기본 기능은 저장소를 순회하고 데이터의 색인을 생성하는 것입니다. 저장소의 크기와 레이아웃을 기반으로 전략을 구현해야 합니다. 직접 설계하거나 SDK에서 전략을 선택할 수 있습니다.

전체 순회 전략
전체 저장소를 검사하고 모든 항목의 색인을 생성합니다. 이 전략은 각 색인 생성 중에 전체 순회의 오버헤드를 감당할 수 있는 소규모 저장소에 가장 적합합니다. 주로 정적이고 비계층적인 데이터가 있는 소규모 저장소나 변경 감지가 어려운 경우에 사용합니다.
목록 순회 전략
전체 저장소를 검사하여 각 항목의 상태를 확인한 다음 새로 추가되거나 업데이트된 항목만 색인합니다. 변경 감지가 지원되지 않는 경우 대규모 비계층 색인의 증분 업데이트에 사용합니다.
그래프 순회
상위 노드를 검사하여 항목의 상태를 확인한 다음 해당 노드에서 신규 또는 업데이트된 항목을 색인화합니다. 그런 다음 하위 노드를 재귀적으로 처리합니다. 디렉터리 구조나 웹사이트와 같이 모든 ID를 나열하는 것이 실용적이지 않은 계층 구조 저장소에 사용합니다.

SDK는 템플릿 커넥터 클래스에서 이러한 전략을 구현합니다. 이러한 템플릿을 사용하면 개발 속도를 높일 수 있습니다. 템플릿을 사용하려면 해당 섹션을 참고하세요.

템플릿 클래스를 사용하여 전체 순회 커넥터 만들기

이 섹션에서는 FullTraversalSample의 코드를 참조합니다.

커넥터 진입점 구현

진입점은 main() 메서드입니다. Application 인스턴스를 만들고 start()을 호출하여 커넥터를 실행합니다.

application.start()를 호출하기 전에 IndexingApplication.Builder 클래스를 사용하여 FullTraversalConnector 템플릿을 인스턴스화합니다. 이 템플릿은 Repository 객체를 허용합니다.

FullTraversalSample.java
/**
 * This sample connector uses the Cloud Search SDK template class for a full
 * traversal connector.
 *
 * @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 SampleRepository();
  IndexingConnector connector = new FullTraversalConnector(repository);
  IndexingApplication application = new IndexingApplication.Builder(connector, args).build();
  application.start();
}

SDK는 main() 메서드가 Application.build()를 호출한 후 initConfig()를 호출합니다. initConfig() 메서드:

  1. Configuration이 이미 초기화되지 않았는지 확인합니다.
  2. Google에서 제공하는 키-값 쌍으로 Configuration 객체를 초기화합니다.

저장소 인터페이스 구현

Repository 객체는 저장소 항목을 순회하고 색인을 생성합니다. 템플릿을 사용하는 경우 Repository 인터페이스에서 특정 메서드만 재정의하면 됩니다. FullTraversalConnector의 경우 다음을 재정의합니다.

  • init(): 저장소 설정 및 초기화
  • getAllDocs(): 모든 항목을 순회하고 색인을 생성합니다. 이 메서드는 예약된 각 순회에 한 번씩 호출됩니다.
  • (선택사항) getChanges(): 저장소가 변경 감지를 지원하는 경우 수정된 항목을 가져오고 색인을 생성하도록 이를 재정의합니다.
  • (선택사항) close(): 종료 시 저장소 정리

각 메서드는 IndexingService.indexItem()를 사용하여 색인 생성을 실행하는 ApiOperation 객체를 반환합니다.

커스텀 구성 매개변수 가져오기

커넥터의 구성을 처리하려면 Configuration 객체에서 맞춤 매개변수를 가져와야 합니다. Repository 클래스의 init() 메서드에서 이 작업을 실행하세요.

Configuration 클래스에는 다양한 데이터 유형을 검색하는 메서드가 포함되어 있습니다. 각 메서드는 ConfigValue 객체를 반환합니다. ConfigValue 객체의 get() 메서드를 사용하여 값을 가져옵니다. FullTraversalSample의 이 스니펫은 맞춤 정수 값을 가져오는 방법을 보여줍니다.

FullTraversalSample.java
@Override
public void init(RepositoryContext context) {
  log.info("Initializing repository");
  numberOfDocuments = Configuration.getInteger("sample.documentCount", 10).get();
}

값이 여러 개인 매개변수를 가져오고 파싱하려면 Configuration 클래스의 유형 파서 중 하나를 사용합니다. 가이드 커넥터의 이 스니펫은 getMultiValue를 사용하여 GitHub 저장소 이름의 목록을 가져옵니다.

GithubRepository.java
ConfigValue<List<String>> repos = Configuration.getMultiValue(
    "github.repos",
    Collections.emptyList(),
    Configuration.STRING_PARSER);

전체 순회 수행

getAllDocs()를 재정의하여 전체 순회를 실행합니다. 이 메서드는 중단된 경우 색인 생성을 재개할 체크포인트를 허용합니다. 각 항목에 대해 다음을 수행합니다.

  1. 권한을 설정합니다.
  2. 메타데이터를 설정합니다.
  3. RepositoryDoc로 결합합니다.
  4. 각 항목을 getAllDocs()에서 반환된 반복자에 패키징합니다.

항목 집합이 너무 커서 한 번의 호출로 처리할 수 없는 경우 체크포인트를 사용하고 hasMore(true)를 호출합니다.

항목에 대한 권한 설정

저장소는 액세스 제어 목록 (ACL)을 사용하여 항목에 액세스할 수 있는 사용자 또는 그룹을 식별합니다. ACL은 승인된 사용자 또는 그룹의 ID를 나열합니다.

사용자에게 액세스 권한이 있는 검색 결과만 표시되도록 하려면 저장소의 ACL을 복제해야 합니다. Google Cloud Search가 올바른 액세스 수준을 제공할 수 있도록 항목의 색인을 생성할 때 ACL을 포함합니다.

콘텐츠 커넥터 SDK에는 대부분의 저장소의 ACL을 모델링하기 위한 클래스와 메서드가 포함되어 있습니다. 색인 생성 시 저장소의 ACL을 분석하고 Cloud Search에 해당하는 ACL을 만듭니다. 상속을 사용하는 것과 같은 복잡한 ACL을 모델링하려면 신중한 계획이 필요합니다. 자세한 내용은 Cloud Search ACL을 참고하세요.

Acl.Builder 클래스를 사용하여 액세스를 설정합니다. 전체 순회 샘플의 이 스니펫을 사용하면 모든 도메인 사용자 (getCustomerPrincipal())가 모든 항목 (setReaders())을 읽을 수 있습니다.

FullTraversalSample.java
// Make the document publicly readable within the domain
Acl acl = new Acl.Builder()
    .setReaders(Collections.singletonList(Acl.getCustomerPrincipal()))
    .build();

저장소 ACL, 특히 상속 모델을 사용하는 ACL을 적절하게 모델링하려면 Cloud Search ACL의 정보가 필요합니다.

항목의 메타데이터 설정

메타데이터는 Item 객체에 저장됩니다. Item을 만들려면 고유한 ID, 항목 유형, ACL, URL, 버전이 필요합니다. IndexingItemBuilder 도우미 클래스를 사용합니다.

FullTraversalSample.java
// Url is required. Use google.com as a placeholder for this sample.
String viewUrl = "https://www.google.com";

// Version is required, set to current timestamp.
byte[] version = Longs.toByteArray(System.currentTimeMillis());

// Using the SDK item builder class to create the document with appropriate attributes
// (this can be expanded to include metadata fields etc.)
Item item = IndexingItemBuilder.fromConfiguration(Integer.toString(id))
    .setItemType(IndexingItemBuilder.ItemType.CONTENT_ITEM)
    .setAcl(acl)
    .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl))
    .setVersion(version)
    .build();
색인 생성이 가능한 항목 만들기

RepositoryDoc.Builder 클래스를 사용합니다.

FullTraversalSample.java
// For this sample, content is just plain text
String content = String.format("Hello world from sample doc %d", id);
ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content);

// Create the fully formed document
RepositoryDoc doc = new RepositoryDoc.Builder()
    .setItem(item)
    .setContent(byteContent, IndexingService.ContentFormat.TEXT)
    .build();

RepositoryDocIndexingService.indexItem() 요청을 실행하는 ApiOperation입니다.

RepositoryDoc.Builder 클래스의 setRequestMode() 메서드를 사용하여 색인 요청을 ASYNCHRONOUS 또는 SYNCHRONOUS로 설정합니다.

ASYNCHRONOUS
이 모드는 색인 생성에서 제공까지의 지연 시간이 더 길지만 더 큰 처리량 할당량을 수용합니다. 전체 저장소의 초기 색인 생성 (백필)에는 비동기 모드를 사용하세요.
SYNCHRONOUS
이 모드는 색인 생성에서 제공까지의 지연 시간이 더 짧지만 처리량 할당량이 더 작습니다. 저장소 업데이트 및 변경사항을 색인 생성할 때는 동기 모드를 사용하세요. 요청 모드의 값을 지정하지 않으면 기본값은 SYNCHRONOUS입니다.
색인 생성 가능한 각 항목을 반복자에 패키징

getAllDocs() 메서드는 RepositoryDoc 객체의 CheckpointCloseableIterable를 반환합니다. CheckpointCloseableIterableImpl.Builder 클래스를 사용합니다.

FullTraversalSample.java
CheckpointCloseableIterable<ApiOperation> iterator =
  new CheckpointCloseableIterableImpl.Builder<>(allDocs).build();

다음 단계

템플릿 클래스를 사용하여 목록 순회 커넥터 만들기

Cloud Search 색인 생성 큐는 저장소 항목의 ID와 선택적 해시를 보유합니다. 목록 순회 커넥터는 ID를 이 큐로 푸시하고 색인 생성을 위해 가져옵니다. Cloud Search는 삭제와 같은 항목 상태를 확인하기 위해 이러한 큐를 유지합니다. Cloud Search 색인 생성 큐를 참고하세요.

이 섹션에서는 ListTraversalSample을 참조합니다.

커넥터 진입점 구현

main() 메서드는 Application 인스턴스를 만들고 start()를 호출합니다. IndexingApplication.Builder를 사용하여 ListingConnector 템플릿을 인스턴스화합니다.

ListTraversalSample.java
/**
 * This sample connector uses the Cloud Search SDK template class for a
 * list traversal connector.
 *
 * @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 SampleRepository();
  IndexingConnector connector = new ListingConnector(repository);
  IndexingApplication application = new IndexingApplication.Builder(connector, args).build();
  application.start();
}

저장소 인터페이스 구현

ListingConnector의 다음 메서드를 재정의합니다.

  • init(): 저장소 설정
  • getIds(): 모든 레코드의 ID와 해시를 가져옵니다.
  • getDoc(): 색인에서 항목을 추가, 업데이트 또는 삭제합니다.
  • (선택사항) getChanges(): 변경 감지를 사용한 증분 업데이트용입니다.
  • (선택사항) close(): 저장소 정리용입니다.

목록 순회 수행

getIds()를 재정의하여 ID와 해시를 검색합니다. Cloud Search 색인 생성 큐의 각 항목을 처리하려면 getDoc()을 재정의합니다.

항목 ID 및 해시 값 푸시

ID와 콘텐츠 해시를 가져오도록 getIds() 재정의 색인 생성 대기열에 대한 PushItems 요청으로 패키징합니다.

ListTraversalSample.java
PushItems.Builder allIds = new PushItems.Builder();
for (Map.Entry<Integer, Long> entry : this.documents.entrySet()) {
  String documentId = Integer.toString(entry.getKey());
  String hash = this.calculateMetadataHash(entry.getKey());
  PushItem item = new PushItem().setMetadataHash(hash);
  log.info("Pushing " + documentId);
  allIds.addPushItem(documentId, item);
}

PushItems.Builder를 사용하여 ID와 해시를 패키징합니다.

ListTraversalSample.java
ApiOperation pushOperation = allIds.build();
CheckpointCloseableIterable<ApiOperation> iterator =
  new CheckpointCloseableIterableImpl.Builder<>(
      Collections.singletonList(pushOperation))
  .build();
return iterator;
각 항목 검색 및 처리

색인 생성 큐의 항목을 처리하려면 getDoc()을 재정의합니다. 항목은 신규, 수정, 변경되지 않음 또는 삭제될 수 있습니다.

  1. 저장소에 상품 ID가 있는지 확인합니다. 그렇지 않으면 삭제합니다.
  2. 상태를 위해 색인을 폴링합니다. 변경되지 않은 경우 (ACCEPTED)에는 아무 것도 하지 않습니다.
  3. 변경되거나 새로운 항목의 색인을 생성합니다. 권한을 설정하고, 메타데이터를 설정하고, RepositoryDoc로 결합하고, 반환합니다.
삭제된 항목 처리

이 스니펫은 항목이 있는지 확인하고 없는 경우 삭제하는 방법을 보여줍니다.

ListTraversalSample.java
String resourceName = item.getName();
int documentId = Integer.parseInt(resourceName);

if (!documents.containsKey(documentId)) {
  // Document no longer exists -- delete it
  log.info(() -> String.format("Deleting document %s", item.getName()));
  return ApiOperations.deleteItem(resourceName);
}
변경되지 않은 항목 처리

색인 생성 대기열을 폴링하여 변경되지 않은 항목을 처리합니다.

ListTraversalSample.java
String currentHash = this.calculateMetadataHash(documentId);
if (this.canSkipIndexing(item, currentHash)) {
  // Document neither modified nor deleted, ack the push
  log.info(() -> String.format("Document %s not modified", item.getName()));
  PushItem pushItem = new PushItem().setType("NOT_MODIFIED");
  return new PushItems.Builder().addPushItem(resourceName, pushItem).build();
}

이 예에서는 해시를 사용하여 변경사항을 감지합니다.

ListTraversalSample.java
/**
 * Checks to see if an item is already up to date
 *
 * @param previousItem Polled item
 * @param currentHash  Metadata hash of the current github object
 * @return PushItem operation
 */
private boolean canSkipIndexing(Item previousItem, String currentHash) {
  if (previousItem.getStatus() == null || previousItem.getMetadata() == null) {
    return false;
  }
  String status = previousItem.getStatus().getCode();
  String previousHash = previousItem.getMetadata().getHash();
  return "ACCEPTED".equals(status)
      && previousHash != null
      && previousHash.equals(currentHash);
}
항목에 대한 권한 설정

저장소는 액세스 제어 목록 (ACL)을 사용하여 항목에 액세스할 수 있는 사용자 또는 그룹을 식별합니다. ACL은 승인된 사용자 또는 그룹의 ID를 나열합니다.

사용자에게 액세스 권한이 있는 검색 결과만 표시되도록 하려면 저장소의 ACL을 복제해야 합니다. Google Cloud Search가 올바른 액세스 수준을 제공할 수 있도록 항목의 색인을 생성할 때 ACL을 포함합니다.

콘텐츠 커넥터 SDK에는 대부분의 저장소의 ACL을 모델링하기 위한 클래스와 메서드가 포함되어 있습니다. 색인 생성 시 저장소의 ACL을 분석하고 Cloud Search에 해당하는 ACL을 만듭니다. 상속을 사용하는 것과 같은 복잡한 ACL을 모델링하려면 신중한 계획이 필요합니다. 자세한 내용은 Cloud Search ACL을 참고하세요.

Acl.Builder 클래스를 사용하여 액세스를 설정합니다. 전체 순회 샘플의 이 스니펫을 사용하면 모든 도메인 사용자 (getCustomerPrincipal())가 모든 항목 (setReaders())을 읽을 수 있습니다.

FullTraversalSample.java
// Make the document publicly readable within the domain
Acl acl = new Acl.Builder()
    .setReaders(Collections.singletonList(Acl.getCustomerPrincipal()))
    .build();

저장소 ACL, 특히 상속 모델을 사용하는 ACL을 적절하게 모델링하려면 Cloud Search ACL의 정보가 필요합니다.

항목의 메타데이터 설정
ListTraversalSample.java
// Url is required. Use google.com as a placeholder for this sample.
String viewUrl = "https://www.google.com";

// Version is required, set to current timestamp.
byte[] version = Longs.toByteArray(System.currentTimeMillis());

// Set metadata hash so queue can detect changes
String metadataHash = this.calculateMetadataHash(documentId);

// Using the SDK item builder class to create the document with
// appropriate attributes. This can be expanded to include metadata
// fields etc.
Item item = IndexingItemBuilder.fromConfiguration(Integer.toString(documentId))
    .setItemType(IndexingItemBuilder.ItemType.CONTENT_ITEM)
    .setAcl(acl)
    .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl))
    .setVersion(version)
    .setHash(metadataHash)
    .build();
색인 생성이 가능한 항목 만들기
ListTraversalSample.java
// For this sample, content is just plain text
String content = String.format("Hello world from sample doc %d", documentId);
ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content);

// Create the fully formed document
RepositoryDoc doc = new RepositoryDoc.Builder()
    .setItem(item)
    .setContent(byteContent, IndexingService.ContentFormat.TEXT)
    .build();

RepositoryDoc.Builder 클래스의 setRequestMode() 메서드를 사용하여 색인 요청을 ASYNCHRONOUS 또는 SYNCHRONOUS로 설정합니다.

ASYNCHRONOUS
이 모드는 색인 생성에서 제공까지의 지연 시간이 더 길지만 더 큰 처리량 할당량을 수용합니다. 전체 저장소의 초기 색인 생성 (백필)에는 비동기 모드를 사용하세요.
SYNCHRONOUS
이 모드는 색인 생성에서 제공까지의 지연 시간이 더 짧지만 처리량 할당량이 더 작습니다. 저장소 업데이트 및 변경사항을 색인 생성할 때는 동기 모드를 사용하세요. 요청 모드의 값을 지정하지 않으면 기본값은 SYNCHRONOUS입니다.

다음 단계

그 다음으로는 아래와 같은 옵션도 고려해 볼 수 있습니다.

  • (선택사항) close() 메서드를 구현하여 종료 전에 리소스를 해제합니다.
  • (선택사항) 콘텐츠 커넥터 SDK를 사용하여 ID 커넥터를 만듭니다.

템플릿 클래스를 사용하여 그래프 순회 커넥터 만들기

Cloud Search 색인 생성 큐는 저장소의 각 항목에 대한 ID와 선택적 해시 값을 저장합니다. 그래프 순회 커넥터는 항목 ID를 Google Cloud Search 색인 생성 큐로 푸시하고 색인 생성을 위해 한 번에 하나씩 가져옵니다. Google Cloud Search는 큐를 유지하고 큐 콘텐츠를 비교하여 항목 상태(예: 항목이 저장소에서 삭제되었는지 여부)를 확인합니다. Cloud Search 색인 생성 큐에 대한 자세한 내용은 Google Cloud Search 색인 생성 큐를 참고하세요.

색인을 생성하는 동안 데이터 저장소에서 항목 콘텐츠를 가져오고 하위 항목 ID가 큐로 푸시됩니다. 커넥터는 모든 항목이 처리될 때까지 상위 및 하위 ID를 반복적으로 처리합니다.

커넥터의 진입점 구현

커넥터의 진입점은 main() 메서드입니다. 이 메서드는 Application 클래스의 인스턴스를 만들고 start() 메서드를 호출하여 커넥터를 실행합니다.

application.start()를 호출하기 전에 IndexingApplication.Builder 클래스를 사용하여 ListingConnector 템플릿을 인스턴스화합니다. ListingConnector는 메서드를 구현하는 Repository 객체를 받습니다.

저장소 인터페이스 구현

init(), getIds(), getDoc()를 재정의하고 선택적으로 getChanges() 또는 close()를 재정의합니다.

그래프 순회 수행

getIds()를 재정의하여 초기 ID를 가져오고 getDoc()를 재정의하여 항목을 처리하고 하위 ID를 큐에 푸시합니다.

항목 ID 및 해시 값 푸시
GraphTraversalSample.java
PushItems.Builder allIds = new PushItems.Builder();
PushItem item = new PushItem();
allIds.addPushItem("root", item);
각 항목 검색 및 처리
  1. ID가 저장소에 있는지 확인합니다. 그렇지 않으면 항목을 삭제합니다.
  2. 기존 항목의 경우 권한과 메타데이터를 설정하고 이를 RepositoryDoc로 결합합니다.
  3. 하위 ID를 색인 생성 큐에 푸시합니다.
  4. RepositoryDoc를 반환합니다.
삭제된 항목 처리
GraphTraversalSample.java
String resourceName = item.getName();
if (documentExists(resourceName)) {
  return buildDocumentAndChildren(resourceName);
}
// Document doesn't exist, delete it
log.info(() -> String.format("Deleting document %s", resourceName));
return ApiOperations.deleteItem(resourceName);
메타데이터를 설정하고 항목 만들기
GraphTraversalSample.java
// Url is required. Use google.com as a placeholder for this sample.
String viewUrl = "https://www.google.com";

// Version is required, set to current timestamp.
byte[] version = Longs.toByteArray(System.currentTimeMillis());

// Using the SDK item builder class to create the document with
// appropriate attributes. This can be expanded to include metadata
// fields etc.
Item item = IndexingItemBuilder.fromConfiguration(documentId)
    .setItemType(IndexingItemBuilder.ItemType.CONTENT_ITEM)
    .setAcl(acl)
    .setSourceRepositoryUrl(IndexingItemBuilder.FieldOrValue.withValue(viewUrl))
    .setVersion(version)
    .build();
GraphTraversalSample.java
// For this sample, content is just plain text
String content = String.format("Hello world from sample doc %s", documentId);
ByteArrayContent byteContent = ByteArrayContent.fromString("text/plain", content);

RepositoryDoc.Builder docBuilder = new RepositoryDoc.Builder()
    .setItem(item)
    .setContent(byteContent, IndexingService.ContentFormat.TEXT);
색인 생성 큐에 하위 ID 배치
GraphTraversalSample.java
// Queue the child nodes to visit after indexing this document
Set<String> childIds = getChildItemNames(documentId);
for (String id : childIds) {
  log.info(() -> String.format("Pushing child node %s", id));
  PushItem pushItem = new PushItem();
  docBuilder.addChildId(id, pushItem);
}

RepositoryDoc doc = docBuilder.build();

REST API를 사용하여 콘텐츠 커넥터 만들기

다음 섹션에서는 REST API를 사용하여 콘텐츠 커넥터를 만드는 방법을 설명합니다.

순회 전략 결정

전략 (전체, 목록, 그래프)은 SDK와 개념적으로 동일합니다. REST API를 사용하여 선택한 전략을 구현합니다.

순회 전략 구현 및 항목의 색인 생성

스키마를 등록한 다음 다음을 사용하여 색인을 채웁니다.

  1. (선택사항) 100KiB보다 큰 파일의 경우 items.upload
  2. (선택사항) 미디어 파일의 경우 media.upload
  3. items.index를 사용하여 항목의 색인을 생성합니다.

    색인 요청 예시:

    {
      "name": "datasource/<data_source_id>/items/titanic",
      "acl": {
        "readers": [
          {
            "gsuitePrincipal": {
              "gsuiteDomain": true
            }
          }
        ]
      },
      "metadata": {
        "title": "Titanic",
        "viewUrl": "http://www.imdb.com/title/tt2234155/",
        "objectType": "movie"
      },
      "structuredData": {
        "object": {
          "properties": [
            {
              "name": "movieTitle",
              "textValues": { "values": ["Titanic"] }
            }
          ]
        }
      },
      "content": {
        "inlineContent": "A seventeen-year-old aristocrat falls in love...",
        "contentFormat": "TEXT"
      },
      "version": "01",
      "itemType": "CONTENT_ITEM"
    }
    
  4. (선택사항) items.get를 사용하여 색인을 확인합니다.

저장소 변경사항 처리

전체 색인 생성을 위해 전체 저장소의 색인을 주기적으로 다시 생성합니다. 목록 또는 그래프 순회의 경우 Google Cloud 색인 생성 큐를 사용하여 변경사항을 추적하고 변경된 항목만 색인을 생성합니다. items.push를 사용하여 대기열에 항목을 추가합니다.