

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 지식 기반에서 문서 내용 검색
<a name="kb-test-get-document-content"></a>

`GetDocumentContent` API를 사용하면 Amazon Bedrock 지식 기반에 수집된 문서의 콘텐츠를 검색할 수 있습니다. 이 API는 문서의 원본 또는 추출된 콘텐츠를 다운로드하거나 볼 수 있는 임시 보안 액세스를 제공하는 미리 서명된 URL을 반환합니다.

이는 다음과 같은 경우에 유용합니다.
+ `Retrieve` API 응답에서 참조되는 소스 문서에 액세스
+ 지식 기반에서 원본 파일(PDF, Word, HTML 등) 다운로드
+ 문서의 추출/파싱된 텍스트 콘텐츠를 JSON 형식으로 검색합니다.
+ 사용자가 `Retrieve` API 응답 뒤에 있는 소스 문서를 보거나 다운로드할 수 있는 애플리케이션 구축

## 작동 방식
<a name="kb-get-doc-content-how-it-works"></a>

1. 지식 기반 ID, 데이터 소스 ID 및 문서 ID를 `GetDocumentContent` 사용하여를 호출합니다.

1. 서비스는 액세스 권한(지식 기반에 구성된 ACL 기반 액세스 제어 포함)을 검증합니다.

1. API는 미리 서명된 URL과 문서의 MIME 유형을 반환합니다.

1. 미리 서명된 URL을 사용하여 문서 콘텐츠를 다운로드합니다. URL은 **5분** 후에 만료됩니다.

## IAM 권한
<a name="kb-get-doc-content-iam"></a>

를 호출하려면 지식 기반 리소스에 대한 `bedrock:Retrieve` 및 `bedrock:GetDocumentContent` IAM 작업이 모두 `GetDocumentContent` 필요합니다. 이는 API가 문서 콘텐츠를 반환하기 전에 검색 수준 액세스를 내부적으로 검증하기 때문입니다. IAM 정책에 두 작업이 모두 포함되어 있는지 확인합니다.

```
{
    "Effect": "Allow",
    "Action": [
        "bedrock:Retrieve",
        "bedrock:GetDocumentContent"
    ],
    "Resource": "arn:aws:bedrock:{{region}}:{{account-id}}:knowledge-base/{{kb-id}}"
}
```

## 사용 예제
<a name="kb-get-doc-content-examples"></a>

### ACL이 활성화된 동일한 계정
<a name="kb-get-doc-content-same-account-acl"></a>

지식 기반에 ACL 기반 액세스 제어가 활성화된 경우 문서 수준 권한 확인을 위해 사용자의 자격 증명과 `userContext` 함께를 전달합니다.

```
import boto3
import requests

client = boto3.client('bedrock-agent-runtime')

# Step 1: Retrieve relevant documents
retrieve_response = client.retrieve(
    knowledgeBaseId='{{KBID1234567}}',
    retrievalQuery={'text': 'What is the refund policy?'}
)

# Step 2: Get the full document content for the top result
result = retrieve_response['retrievalResults'][0]

doc_response = client.get_document_content(
    knowledgeBaseId='{{KBID1234567}}',
    dataSourceId=result['metadata']['_data_source_id'],
    documentId=result['documentId'],
    outputFormat='RAW',
    userContext={
        'userId': '{{user-email}}',
        'groups': [
            {'id': '{{group-engineering}}'},
            {'id': '{{group-project-alpha}}'}
        ]
    }
)

# Step 3: Download the document
download = requests.get(doc_response['presignedUrl'])
with open('document.pdf', 'wb') as f:
    f.write(download.content)
```

### ACL이 활성화되지 않은 동일한 계정
<a name="kb-get-doc-content-same-account-no-acl"></a>

ACLs이 구성되지 않은 경우를 생략합니다`userContext`.

```
import boto3
import requests

client = boto3.client('bedrock-agent-runtime')

# Step 1: Retrieve relevant documents
retrieve_response = client.retrieve(
    knowledgeBaseId='{{KBID1234567}}',
    retrievalQuery={'text': 'What is the refund policy?'}
)

# Step 2: Get the full document content
result = retrieve_response['retrievalResults'][0]

doc_response = client.get_document_content(
    knowledgeBaseId='{{KBID1234567}}',
    dataSourceId=result['metadata']['_data_source_id'],
    documentId=result['documentId'],
    outputFormat='RAW'
)

# Step 3: Download the document
download = requests.get(doc_response['presignedUrl'])
with open('document.pdf', 'wb') as f:
    f.write(download.content)
```

### ACL이 활성화되지 않은 교차 계정
<a name="kb-get-doc-content-cross-account"></a>

교차 계정 액세스의 경우 지식 기반 소유자는 호출자의 계정 권한을 부여하는 **리소스 정책을** 지식 기반에 연결해야 합니다. 그런 다음 호출자는 전체 지식 기반 ARN을 사용합니다.

**1단계: KB 소유자가 지식 기반에 리소스 정책 연결**

지식 기반을 소유한 계정(예: `999999999999`)은 호출자 계정(예: `111111111111`)에 액세스 권한을 부여하는 리소스 정책을 연결해야 합니다.

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "111111111111"
            },
            "Action": [
                "bedrock:Retrieve",
                "bedrock:GetDocumentContent"
            ],
            "Resource": "arn:aws:bedrock:us-east-1:999999999999:knowledge-base/{{KBID1234567}}"
        }
    ]
}
```

이는 `PutKnowledgeBaseResourcePolicy` API 또는 Amazon Bedrock 콘솔을 통해 수행됩니다.

**2단계: 호출자 계정에 API를 호출할 수 있는 IAM 권한이 있음**

호출자의 IAM 역할/사용자(계정 `111111111111`)에는 교차 계정 KB ARN에 대한 작업을 허용하는 IAM 정책이 필요합니다.

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:Retrieve",
                "bedrock:GetDocumentContent"
            ],
            "Resource": "arn:aws:bedrock:us-east-1:999999999999:knowledge-base/{{KBID1234567}}"
        }
    ]
}
```

**3단계: 전체 KB ARN을 사용하여 API 호출**

```
import boto3
import requests

client = boto3.client('bedrock-agent-runtime')

CROSS_ACCOUNT_KB_ARN = 'arn:aws:bedrock:us-east-1:999999999999:knowledge-base/{{KBID1234567}}'

# Step 1: Retrieve relevant documents using the KB ARN
retrieve_response = client.retrieve(
    knowledgeBaseId=CROSS_ACCOUNT_KB_ARN,
    retrievalQuery={'text': 'What is the refund policy?'}
)

# Step 2: Get the full document content using the same ARN
result = retrieve_response['retrievalResults'][0]

doc_response = client.get_document_content(
    knowledgeBaseId=CROSS_ACCOUNT_KB_ARN,
    dataSourceId=result['metadata']['_data_source_id'],
    documentId=result['documentId'],
    outputFormat='RAW'
)

# Step 3: Download the document
download = requests.get(doc_response['presignedUrl'])
with open('document.pdf', 'wb') as f:
    f.write(download.content)
```

리소스 정책(KB 소유자 측)과 IAM 정책(발신자 측)이 모두 있어야 합니다. 둘 중 하나가 누락된 경우 액세스가 거부됩니다.