

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 透過連線至結構化資料存放區來建立知識庫
<a name="knowledge-base-build-structured"></a>

Amazon Bedrock 知識庫可讓您連線至結構化資料存放區，其中包含符合預先定義結構描述的資料。結構化資料的範例包括資料表和資料庫。Amazon Bedrock 知識庫可以將使用者查詢轉換為適合從支援的結構化資料存放區擷取資料的語言。然後，它可以使用轉換後的查詢來擷取與查詢相關的資料，並產生適當的回應。這可讓您直接使用現有的結構化資料，而無需將其轉換為不同的格式或產生您自己的 SQL 查詢。

設定知識庫之後，您可以透過 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Retrieve.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Retrieve.html) 操作提交查詢以從中擷取資料，或透過 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrieveAndGenerate.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrieveAndGenerate.html) 操作從擷取的資料產生回應。這些操作基本上會將使用者查詢轉換為適用於連線至知識庫的結構化資料存放區。

您也可以選擇使用 [GenerateQuery](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_GenerateQuery.html) API 操作，在獨立於擷取資料的情況下轉換查詢。此操作會將自然語言查詢轉換為適合所查詢資料來源的 SQL 查詢。您可以獨立使用此操作，並將其插入您的工作流程。

選取主題，以了解將知識庫連線至結構化資料存放區的先決條件和程序。

**Topics**
+ [設定查詢引擎和建立具有結構化資料存放區之知識庫的許可](knowledge-base-prereq-structured.md)
+ [建立連線至結構化資料存放區的知識庫](knowledge-base-structured-create.md)
+ [將結構化資料存放區與您的 Amazon Bedrock 知識庫同步](kb-data-source-structured-sync-ingest.md)

# 設定查詢引擎和建立具有結構化資料存放區之知識庫的許可
<a name="knowledge-base-prereq-structured"></a>

本主題說明將知識庫連線至結構化資料存放區時所需的許可。如果您計劃將 Amazon Bedrock 知識庫連線至結構化資料存放區，則需要滿足先決條件。如需要滿足的一般許可要求，請參閱 [設定使用者或角色的許可，以建立和管理知識庫](knowledge-base-prereq-permissions-general.md)。

**重要**  
執行任意 SQL 查詢可能是任何文字轉 SQL 應用程式的安全風險。我們建議您視需要採取預防措施，例如使用受限的角色、唯讀資料庫和沙盒。

Amazon Bedrock 知識庫支援使用 Amazon Redshift 作為查詢引擎來查詢您的資料存放區。查詢引擎會從結構化資料存放區存取中繼資料，並使用中繼資料協助產生 SQL 查詢。Amazon Redshift 是一項資料倉儲服務，使用 SQL 來分析跨資料倉儲、資料庫和資料湖的結構化資料。

## 建立 Amazon Redshift 查詢引擎
<a name="kb-query-engine-setup-create"></a>

您可以根據您的使用案例使用 Amazon Redshift Serverless 或 Amazon Redshift 佈建，並連線至資料倉儲的工作群組或叢集。Amazon Redshift 引擎可以查詢的基礎資料可以原生存放在 Amazon Redshift 叢集中的資料，或位於預設值下的資料 AWS Glue Data Catalog （例如 Amazon S3 等）。

如果您已建立查詢引擎，則可以略過此先決條件。否則，請執行下列步驟來設定 Amazon Redshift 佈建或 Amazon Redshift Serverless 查詢引擎：

**在佈建的 Amazon Redshift 中設定查詢引擎**

1. 遵循《Amazon Redshift 入門指南》中[步驟 1：建立範例 Amazon Redshift 叢集](https://docs.aws.amazon.com/redshift/latest/gsg/new-user.html#rs-gsg-launch-sample-cluster)中的程序。

1. 請記下叢集 ID。

1. (選用) 如需 Amazon Redshift 佈建叢集的詳細資訊，請參閱《Amazon Redshift 管理指南》中的 [Amazon Redshift 佈建叢集](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html)。

**在 Amazon Redshift Serverless 中設定查詢引擎**

1. 僅遵循《Amazon Redshift 入門指南》中的[使用 Amazon Redshift Serverless 建立資料倉儲](https://docs.aws.amazon.com/redshift/latest/gsg/new-user-serverless.html#serverless-console-resource-creation)中的設定程序，並使用預設設定進行設定。

1. 請注意工作群組 ARN。

1. (選用) 如需 Amazon Redshift Serverless 工作群組的詳細資訊，請參閱《Amazon Redshift 管理指南》中的[工作群組和命名空間](https://docs.aws.amazon.com/redshift/latest/mgmt/serverless-workgroup-namespace.html)。

## 設定 Amazon Redshift 查詢引擎許可
<a name="kb-query-engine-setup-redshift-permissions"></a>

根據您選擇的 Amazon Redshift 查詢引擎，您可以設定特定許可。您設定的許可取決於身分驗證方法。下表顯示可用於不同查詢引擎的身分驗證方法：


****  

| 身分驗證方法 | Amazon Redshift 佈建 | Amazon Redshift Serverless | 
| --- | --- | --- | 
| IAM | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | 
| 資料庫使用者名稱 | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | ![\[Red circular icon with an X symbol, indicating cancellation or denial.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-no.png)否 | 
| AWS Secrets Manager | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | 

Amazon Bedrock 知識庫會使用[服務角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)將知識庫連線至結構化資料存放區、從這些資料存放區擷取資料，並根據使用者查詢和資料存放區的結構產生 SQL 查詢。

**注意**  
如果您打算使用 AWS 管理主控台 來建立知識庫，您可以略過此先決條件。主控台將建立具有適當許可的 Amazon Bedrock 知識庫服務角色。

若要建立具有適當許可的自訂 IAM 服務角色，請遵循[建立角色以將許可委派給 AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)中的步驟，並連接 [信任關係](kb-permissions.md#kb-permissions-trust) 中定義的信任關係。

然後，為您的知識庫新增存取 Amazon Redshift 查詢引擎和資料庫的許可。展開適用於您的使用案例的區段：

### 您的查詢引擎已佈建 Amazon Redshift
<a name="w2aac28c10c27c13c11c15b1"></a>

將下列政策連接至您的自訂服務角色，以允許其存取您的資料並使用其產生查詢：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "RedshiftDataAPIStatementPermissions",
            "Effect": "Allow",
            "Action": [
                "redshift-data:GetStatementResult",
                "redshift-data:DescribeStatement",
                "redshift-data:CancelStatement"
            ],
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringEquals": {
                    "redshift-data:statement-owner-iam-userid": "${aws:userid}"
                }
            }
        },
        {
            "Sid": "RedshiftDataAPIExecutePermissions",
            "Effect": "Allow",
            "Action": [
                "redshift-data:ExecuteStatement"
            ],
            "Resource": [
                "arn:aws:redshift:us-east-1:123456789012:cluster:${Cluster}"
            ]
        },
        {
            "Sid": "SqlWorkbenchAccess",
            "Effect": "Allow",
            "Action": [
                "sqlworkbench:GetSqlRecommendations",
                "sqlworkbench:PutSqlGenerationContext",
                "sqlworkbench:GetSqlGenerationContext",
                "sqlworkbench:DeleteSqlGenerationContext"
            ],
            "Resource": "*"
        },
        {
            "Sid": "GenerateQueryAccess",
            "Effect": "Allow",
            "Action": [
                "bedrock:GenerateQuery"
            ],
            "Resource": "*"
        }
    ]
}
```

------

您也需要新增許可，以允許您的服務角色向查詢引擎進行身分驗證。展開區段以查看該方法的許可。

------
#### [ IAM ]

若要讓您的服務角色使用 IAM 驗證您的 Amazon Redshift 佈建查詢引擎，請將下列政策連接至您的自訂服務角色：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "GetCredentialsWithFederatedIAMCredentials",
            "Effect": "Allow",
            "Action": "redshift:GetClusterCredentialsWithIAM",
            "Resource": [
                "arn:aws:redshift:us-east-1:123456789012:dbname:Cluster/database"
            ]
        }
    ]
}
```

------

------
#### [ Database user ]

若要驗證 Amazon Redshift 資料庫使用者身分，請將下列政策連接至服務角色：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "GetCredentialsWithClusterCredentials",
            "Effect": "Allow",
            "Action": [
                "redshift:GetClusterCredentials"
            ],
            "Resource": [
                "arn:aws:redshift:us-east-1:123456789012:dbuser:${cluster}/${dbuser}",
                "arn:aws:redshift:us-east-1:123456789012:dbname:${cluster}/${database}"
            ]
        }
    ]
}
```

------

------
#### [ AWS Secrets Manager ]

若要讓您的服務角色使用 AWS Secrets Manager 秘密向 Amazon Redshift 佈建查詢引擎進行身分驗證，請執行下列動作：
+ 將下列政策連接至該角色：

  ```
  {
      "Version": "2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "GetSecretPermissions",
              "Effect": "Allow",
              "Action": [
                  "secretsmanager:GetSecretValue"
              ],
              "Resource": [
                  "arn:aws:secretsmanager:${region}:${account}:secret:${secretName}"
              ]
          }
      ]
  }
  ```

------

### 您的查詢引擎是 Amazon Redshift Serverless
<a name="w2aac28c10c27c13c11c15b3"></a>

連接的許可取決於您的身分驗證方法。展開區段以查看方法的許可。

------
#### [ IAM ]

若要讓您的服務角色使用 IAM 驗證您的 Amazon Redshift Serverless 查詢引擎，請將下列政策連接至您的自訂服務角色：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "RedshiftServerlessGetCredentials",
            "Effect": "Allow",
            "Action": "redshift-serverless:GetCredentials",
            "Resource": [
                "arn:aws:redshift-serverless:us-east-1:123456789012:workgroup/WorkgroupId"
            ]
        }
    ]
}
```

------

------
#### [ AWS Secrets Manager ]

若要讓您的服務角色使用 AWS Secrets Manager 秘密向 Amazon Redshift 佈建查詢引擎進行身分驗證，請執行下列動作：
+ 將下列政策連接至該角色：

  ```
  {
      "Version": "2012-10-17",		 	 	 
      "Statement": [
          {
              "Sid": "GetSecretPermissions",
              "Effect": "Allow",
              "Action": [
                  "secretsmanager:GetSecretValue"
              ],
              "Resource": [
                  "arn:aws:secretsmanager:${region}:${account}:secret:${secretName}"
              ]
          }
      ]
  }
  ```

------

## 允許知識庫服務角色存取您的資料存放區
<a name="knowledge-base-prereq-structured-db-access"></a>

請確定您的資料存放在下列其中一個[支援的結構化資料存放區](knowledge-base-structured-create.md)中：
+ Amazon Redshift
+ AWS Glue Data Catalog (AWS Lake Formation)

下表摘要說明查詢引擎可用的身分驗證方法，視您的資料存放區而定：


****  

| 身分驗證方法 | Amazon Redshift | AWS Glue Data Catalog (AWS Lake Formation) | 
| --- | --- | --- | 
| IAM | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | 
| 資料庫使用者名稱 | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | ![\[Red circular icon with an X symbol, indicating cancellation or denial.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-no.png)否 | 
| AWS Secrets Manager | ![\[Green circular icon with a white checkmark symbol inside.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-yes.png)是 | ![\[Red circular icon with an X symbol, indicating cancellation or denial.\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/images/icons/icon-no.png)否 | 

若要了解如何設定 Amazon Bedrock 知識庫服務角色的許可，以存取資料存放區並根據其產生查詢，請展開對應至資料存放區所在服務的區段：

### Amazon Redshift
<a name="w2aac28c10c27c13c13c13b1"></a>

若要授予 Amazon Bedrock 知識庫服務角色存取 Amazon Redshift 資料庫的權限，請使用 [Amazon Redshift 查詢編輯器 v2](https://docs.aws.amazon.com/redshift/latest/mgmt/query-editor-v2.html) 並執行下列 SQL 命令：

1. (如果您使用 IAM 進行身分驗證，且尚未為資料庫建立使用者) 執行下列命令，該命令使用 [CREATE USER](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_USER.html) 來建立資料庫使用者，並允許它透過 IAM 進行身分驗證，以您建立的自訂 Amazon Bedrock 知識庫服務角色名稱取代 *\$1\$1service-role\$1*：

   ```
   CREATE USER "IAMR:${service-role}" WITH PASSWORD DISABLE;
   ```
**重要**  
如果您使用在主控台中為您建立的 Amazon Bedrock 知識庫服務角色，然後在執行此步驟之前[同步資料存放區](kb-data-source-structured-sync-ingest.md)，則會為您建立使用者，但同步會失敗，因為使用者尚未獲得存取資料存放區的許可。您必須在同步之前執行下列步驟。

1. 執行 [GRANT](https://docs.aws.amazon.com/redshift/latest/dg/r_GRANT.html) 命令，授予身分許可以從資料庫擷取資訊。

------
#### [ IAM ]

   ```
   GRANT SELECT ON ALL TABLES IN SCHEMA ${schemaName} TO "IAMR:${serviceRole}";
   ```

------
#### [ Database user ]

   ```
   GRANT SELECT ON ALL TABLES IN SCHEMA ${schemaName} TO "${dbUser}";
   ```

------
#### [ AWS Secrets Manager username ]

   ```
   GRANT SELECT ON ALL TABLES IN SCHEMA ${schemaName} TO "${secretsUsername}";
   ```

------
**重要**  
請勿授予 `CREATE`、`UPDATE` 或 `DELETE` 存取權。授予這些動作可能會導致資料的意外修改。

   若要更精細地控制可存取的資料表，您可以使用下列表示法取代 `ALL TABLES` 特定資料表名稱：*\$1\$1schemaName\$1**\$1\$1tableName\$1*。如需此表示法的詳細資訊，請參閱[跨資料庫查詢](https://docs.aws.amazon.com/redshift/latest/dg/cross-database-overview.html)中的**查詢物件**區段。

------
#### [ IAM ]

   ```
   GRANT SELECT ON ${schemaName}.${tableName} TO "IAMR:${serviceRole}";
   ```

------
#### [ Database user ]

   ```
   GRANT SELECT ON ${schemaName}.${tableName} TO "${dbUser}";
   ```

------
#### [ AWS Secrets Manager username ]

   ```
   GRANT SELECT ON ${schemaName}.${tableName} TO "${secretsUsername}";
   ```

------

1. 如果您在 Redshift 資料庫中建立了新的結構描述，請執行下列命令來授予對新結構描述的身分許可。

   ```
   GRANT USAGE ON SCHEMA ${schemaName} TO "IAMR:${serviceRole}";
   ```

### AWS Glue Data Catalog
<a name="w2aac28c10c27c13c13c13b3"></a>

若要授予 Amazon Bedrock Knowledge Bases 服務角色存取 AWS Glue Data Catalog 資料存放區的權限，請使用 [Amazon Redshift 查詢編輯器 v2](https://docs.aws.amazon.com/redshift/latest/mgmt/query-editor-v2.html) 並執行下列 SQL 命令：

1. 執行下列命令，該命令使用 [CREATE USER](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_USER.html) 來建立資料庫使用者，並允許它透過 IAM 進行身分驗證，以您建立的自訂 Amazon Bedrock 知識庫服務角色名稱取代 *\$1\$1service-role\$1*：

   ```
   CREATE USER "IAMR:${service-role}" WITH PASSWORD DISABLE;
   ```
**重要**  
如果您使用在主控台中為您建立的 Amazon Bedrock 知識庫服務角色，然後在執行此步驟之前[同步資料存放區](kb-data-source-structured-sync-ingest.md)，則會為您建立使用者，但同步會失敗，因為使用者尚未獲得存取資料存放區的許可。您必須在同步之前執行下列步驟。

1. 執行下列 [GRANT](https://docs.aws.amazon.com/redshift/latest/dg/r_GRANT.html) 命令，授予服務角色從資料庫擷取資訊的許可：

   ```
   GRANT USAGE ON DATABASE awsdatacatalog TO "IAMR:${serviceRole}";
   ```
**重要**  
請勿授予 `CREATE`、`UPDATE` 或 `DELETE` 存取權。授予這些動作可能會導致資料的意外修改。

1. 若要允許存取您的 AWS Glue Data Catalog 資料庫，請將下列許可連接至 服務角色：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "VisualEditor0",
               "Effect": "Allow",
               "Action": [
                   "glue:GetDatabases",
                   "glue:GetDatabase",
                   "glue:GetTables",
                   "glue:GetTable",
                   "glue:GetPartitions",
                   "glue:GetPartition",
                   "glue:SearchTables"
               ],
               "Resource": [
                   "arn:aws:glue:us-east-1:123456789012:table/${DatabaseName}/${TableName}",
                   "arn:aws:glue:us-east-1:123456789012:database/${DatabaseName}",
                   "arn:aws:glue:us-east-1:123456789012:catalog"
               ]
           }
       ]
   }
   ```

------

1. 透過 將許可授予您的服務角色 AWS Lake Formation （若要進一步了解 Lake Formation 及其與 Amazon Redshift 的關係，請參閱 [Redshift 的資料來源](https://docs.aws.amazon.com/redshift/latest/dg/copy-parameters-data-source.html))，請執行下列動作：

   1. 登入 AWS 管理主控台，並在 https：//[https://console.aws.amazon.com/lakeformation/](https://console.aws.amazon.com/lakeformation/) 開啟 Lake Formation 主控台。

   1. 從左側導覽窗格中選取**資料許可**。

   1. 將許可授予您用於 Amazon Bedrock 知識庫的服務角色。

   1. 授予**描述**和**選取**資料庫和資料表的許可。

1. 根據您在 中使用的資料來源 AWS Glue Data Catalog，您可能需要新增存取該資料來源的許可 （如需詳細資訊，請參閱[AWS Glue 其他 的相依性 AWS 服務](https://docs.aws.amazon.com/glue/latest/dg/dependency-on-other-services.html))。例如，如果您的資料來源位於 Amazon S3 位置，則需要將下列陳述式新增至上述政策。

   ```
   {
       "Sid": "Statement1",
       "Effect": "Allow",
       "Action": [
           "s3:ListBucket",
           "s3:GetObject"
       ],
       "Resource": [
           "arn:aws:s3:::${BucketName}",
           "arn:aws:s3:::${BucketName}/*"
       ]
   }
   ```

1. （選用） 如果您使用 AWS KMS 來加密 Amazon S3 或 中的資料 AWS Glue Data Catalog，則需要將許可新增至角色，以解密 KMS 金鑰上的資料。

   ```
   {
       "Action": [
           "kms:Decrypt"
       ],
       "Resource": [
           "arn:aws:kms:${Region}:${Account}:key/{KmsId}",
           "arn:aws:kms:${Region}:${Account}:key/{KmsId}"
       ],
       "Effect": "Allow"
   }
   ```

# 建立連線至結構化資料存放區的知識庫
<a name="knowledge-base-structured-create"></a>

若要將知識庫連線至結構化資料存放區，請指定下列元件：
+ 

**查詢引擎組態**  
將執行所產生 SQL 查詢之運算服務的組態。查詢引擎用於將自然語言使用者查詢轉換為 SQL 查詢，可用於從資料存放區擷取資料。您可以選擇 Amazon Redshift 作為查詢引擎。選擇此組態時，您必須指定：
  + 運算連線中繼資料，例如叢集 ID 或工作群組 ARN，視選擇的查詢引擎而定。
  + 使用查詢引擎的身分驗證方法，可使用具有適當許可的 IAM 服務角色、查詢引擎資料庫使用者或連結至資料庫憑證的 AWS Secrets Manager 秘密。
+ 

**儲存組態**  
包含您資料的資料存放區的組態。您可以連線至 Amazon Redshift Provisioned 或 Amazon Redshift Serverless，並使用 Amazon Redshift 或 AWS Glue Data Catalog 做為您的資料存放區。
+ 

**(選用) 查詢組態**  
您可以使用選用的查詢組態來提高 SQL 生成的準確性：
  + **查詢時間上限** – 經過這段時間後，查詢就會逾時。
  + **說明** – 提供有關表格或欄的中繼資料或補充資訊。您可以包括表格或資料欄的說明、使用情形附註，或任何其他屬性。您新增的說明可透過提供有關表格或資料欄結構的額外內容和資訊，來改善 SQL 查詢生成。
  + **包含項目和排除項目** – 指定要針對 SQL 生成包含或排除的一組表格或資料欄。如果您想要將 SQL 查詢的範圍限於一組定義的可用表格或資料欄的子集，則此欄位會非常重要。此選項可透過減少不必要的表格或資料欄參考，協助最佳化生成過程。

    如果您指定包含項目，則會忽略所有其他表格和資料欄。如果您指定排除項目，則會忽略您指定的表格和資料欄。
**注意**  
包含項目和排除項目無法替代防護機制，僅用於提高模型準確性。
  + **策劃的查詢** – 一組預先定義的問題和答案範例。問題會編寫成自然語言查詢 (NLQ)，答案則是對應的 SQL 查詢。這些範例透過提供應生成的查詢類型範例，來協助 SQL 生成過程。這些範例可作為參考點來提高生成式 SQL 輸出的準確性和相關性。

展開與使用案例對應的區段：

## 使用主控台
<a name="knowledge-base-structured-create-console"></a>

若要使用 連線至結構化資料存放區 AWS 管理主控台，請執行下列動作：

1.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock) 的 Amazon Bedrock 主控台。

1. 在左側導覽窗格中選擇**知識庫**。

1. 在**知識庫**區段中，選擇**建立**，然後選取**具有結構化資料存放區的知識庫**。

1. 設定知識庫的下列詳細資訊：

   1. (選用) 變更預設名稱並提供知識庫的描述。

   1. 選取要用於從資料存放區擷取資料的查詢引擎。

   1. 選擇具有適當許可的 IAM 服務角色，以建立和管理此知識庫。您可以讓 Amazon Bedrock 建立服務角色，或選擇已建立的自訂角色。如需建立自訂角色的詳細資訊，請參閱 [設定查詢引擎和建立具有結構化資料存放區之知識庫的許可](knowledge-base-prereq-structured.md)。

   1. (選用) 新增標籤以與您的知識庫建立關聯。如需詳細資訊，請參閱[標記 Amazon Bedrock 資源](tagging.md)。

   1. 選擇**下一步**。

1. 設定您的查詢引擎：

   1. 選取您在其中建立叢集或工作群組的服務。然後選擇要使用的叢集或工作群組。

   1. 選取身分驗證方法，並提供必要的欄位。

   1. 選取要存放中繼資料的資料存放區。然後，選擇或輸入資料庫的名稱。

   1. (選用) 視需要修改查詢組態。如需不同組態的詳細資訊，請參閱本主題的開頭。

   1. 選擇**下一步**。

1. 檢閱您的知識庫組態，並視需要編輯任何區段。確認以建立您的知識庫。

## 使用 API
<a name="knowledge-base-structured-create-api"></a>

若要使用 Amazon Bedrock API 連線至結構化資料存放區，請使用 [Amazon Bedrock 代理人建置時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)搭配下列一般請求內文來傳送 [CreateKnowledgeBase](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CreateKnowledgeBase.html) 請求：

```
{
    "name": "string",
    "roleArn": "string",
    "knowledgeBaseConfiguration": {
        "type": "SQL",
        "sqlKnowledgeBaseConfiguration": [SqlKnowledgeBaseConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_SqlKnowledgeBaseConfiguration.html)
    },
    "description": "string",
    "clientToken": "string",
    "tags": {
        "string": "string"
    }
}
```

下列是必要欄位。


****  

| 欄位 | 基本描述 | 
| --- | --- | 
| 名稱 | 知識庫的名稱 | 
| roleArn | 具有適當許可的[知識庫服務角色](kb-permissions.md)。您可以使用主控台自動建立具有適當許可的服務角色。 | 
| knowledgeBaseConfiguration | 包含知識庫的組態。對於結構化資料庫，指定 SQL 為 type 並包含 sqlKnowledgeBaseConfiguration 欄位。 | 

以下是選填欄位。


****  

| 欄位 | 使用 | 
| --- | --- | 
| description | 包含知識庫的描述。 | 
| clientToken | 為確保 API 請求，僅完成一次。如需詳細資訊，請參閱[確保冪等性](https://docs.aws.amazon.com/ec2/latest/devguide/ec2-api-idempotency.html)。 | 
| 標籤 | 將標籤與流程建立關聯。如需詳細資訊，請參閱[標記 Amazon Bedrock 資源](tagging.md)。 | 

`SQLKnowledgeBaseConfiguration` 取決於您使用的查詢引擎。對於 Amazon Redshift，將 `type` 欄位指定為 `REDSHIFT`，並包含 `redshiftConfiguration` 欄位，該欄位會對應至 [RedshiftConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftConfiguration.html)。對於 [RedshiftConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftConfiguration.html)，您可以設定下列欄位：

### queryEngineConfiguration
<a name="w2aac28c10c27c15b9b3c17b1"></a>

您可以設定下列類型的查詢引擎：

#### Amazon Redshift 佈建
<a name="w2aac28c10c27c15b9b3c17b1b5b1"></a>

如果您的 Amazon Redshift 資料庫佈建在專用運算節點上，`queryEngineConfiguration` 欄位的值應為 [RedshiftQueryEngineConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftQueryEngineConfiguration.html)，格式如下：

```
{
    "type": "PROVISIONED",
    "provisionedConfiguration": {
        "clusterIdentifier": "string",
        "authConfiguration": [RedshiftProvisionedAuthConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftProvisionedAuthConfiguration.html)
    },
}
```

在 `clusterIdentifier` 欄位中指定叢集的 ID。[RedshiftProvisionedAuthConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftProvisionedAuthConfiguration.html) 取決於您使用的授權類型。選取符合您授權方法的標籤：

------
#### [ IAM role ]

如果您使用 IAM 角色授權，則只需要在 [RedshiftProvisionedAuthConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftProvisionedAuthConfiguration.html) 中指定 `IAM` 類型，而不需要其他欄位。

```
{
    "type": "IAM"
}
```

------
#### [ Temporary credentials user name ]

如果您使用資料庫使用者名稱授權，請將 `type` 指定為 `USERNAME`，並在 `RedshiftProvisionedAuthConfig` 中的 `databaseUser` 欄位中指定使用者名稱：

```
{
    "type": "USERNAME",
    "databaseUser": "string"
}
```

------
#### [ AWS Secrets Manager ]

如果您使用 授權 AWS Secrets Manager，請將 指定`type`為 ，`USERNAME_PASSWORD`並在 的 `usernamePasswordSecretArn` 欄位中指定秘密的 ARN`RedshiftProvisionedAuthConfig`：

```
{
    "type": "USERNAME_PASSWORD",
    "usernamePasswordSecretArn": "string"
}
```

------

#### Amazon Redshift Serverless
<a name="w2aac28c10c27c15b9b3c17b1b5b3"></a>

如果您使用的是 Amazon Redshift Serverless，`queryConfiguration` 欄位的值應為 [RedshiftQueryEngineConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftQueryEngineConfiguration.html)，格式如下：

```
{
    "type": "SERVERLESS",
    "serverlessConfiguration": {
        "workgroupArn": "string",
        "authConfiguration": 
    }
}
```

在 `workgroupArn` 欄位中指定工作群組的 ARN。[RedshiftServerlessAuthConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftServerlessAuthConfiguration.html) 取決於您使用的授權類型。選取符合您授權方法的標籤：

------
#### [ IAM role ]

如果您使用 IAM 角色授權，則只需要在 `RedshiftServerlessAuthConfiguration` 中指定 `IAM` 類型，而不需要其他欄位。

```
{
    "type": "IAM"
}
```

------
#### [ AWS Secrets Manager ]

如果您使用 授權 AWS Secrets Manager，請將 指定`type`為 ，`USERNAME_PASSWORD`並在 的 `usernamePasswordSecretArn` 欄位中指定秘密的 ARN`RedshiftServerlessAuthConfiguration`：

```
{
    "type": "USERNAME_PASSWORD",
    "usernamePasswordSecretArn": "string"
}
```

------

### storageConfigurations
<a name="w2aac28c10c27c15b9b3c17b3"></a>

此欄位會對應至包含單一 [RedshiftQueryEngineStorageConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_RedshiftQueryEngineStorageConfiguration.html) 的陣列，其格式取決於資料的存放位置。

#### AWS Glue Data Catalog
<a name="w2aac28c10c27c15b9b3c17b3b5b1"></a>

如果您的資料存放在 中 AWS Glue Data Catalog， `RedshiftQueryEngineStorageConfiguration`應該採用下列格式：

```
{
    "type": "AWS_DATA_CATALOG",
    "awsDataCatalogConfiguration": {
        "tableNames": ["string"]
    }
}
```

在 `tableNames` 要對應到的陣列中，新增您要將知識庫連線至的每個資料表的名稱。

**注意**  
以[跨資料庫查詢](https://docs.aws.amazon.com/redshift/latest/dg/cross-database-overview.html) (`${databaseName}.${tableName}`) 中所述的模式輸入資料表名稱。您可以透過指定 `${databaseName.*}` 來包含所有資料表。

#### Amazon Redshift 資料庫
<a name="w2aac28c10c27c15b9b3c17b3b5b3"></a>

如果您的資料存放在 Amazon Redshift 資料庫中，`RedshiftQueryEngineStorageConfiguration` 應該採用下列格式：

```
{
    "type": "string",
    "redshiftConfiguration": {
        "databaseName": "string"
    }
}
```

在 `databaseName` 欄位中指定 Amazon Redshift 資料庫的名稱。

**注意**  
以[跨資料庫查詢](https://docs.aws.amazon.com/redshift/latest/dg/cross-database-overview.html) (`${databaseName}.${tableName}`) 中所述的模式輸入資料表名稱。您可以透過指定 `${databaseName.*}` 來包含所有資料表。

如果您的資料庫是透過 Amazon SageMaker AI 資料湖倉掛載，則資料庫名稱的格式為 *\$1\$1db\$1@\$1\$1schema\$1*。

### queryGenerationConfiguration
<a name="w2aac28c10c27c15b9b3c17b5"></a>

此欄位會對應至下列 [QueryGenerationConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationConfiguration.html)，您可以用來設定查詢資料的方式：

```
{
    "executionTimeoutSeconds": number,
    "generationContext": {
        "tables": [
            {
                "name": "string",
                "description": "string",
                "inclusion": "string",
                "columns": [
                    {
                        "name": "string",
                        "description": "string",
                        "inclusion": "string"
                    },
                    ...
                ]
            },
            ...
        ],
        "curatedQueries": [
            {
                "naturalLanguage": "string",
                "sql": "string"
            },
            ...
        ]
    }
}
```

如果您希望查詢逾時，請在 `executionTimeoutSeconds` 欄位中以秒為單位指定逾時持續時間。

`generationContext` 欄位會對應至 [QueryGenerationContext](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationContext.html) 物件，您可以在其中視需要設定下列任意數量的選項。

**重要**  
如果您包含產生內容，查詢引擎會盡可能在產生 SQL 時嘗試套用內容。產生內容是非確定性的，僅用於改善模型準確性。為了確保準確性，請驗證產生的 SQL 查詢。

如需有關您可以包含的產生內容的資訊，請展開下列區段：

#### 新增資料庫中資料表或資料欄的描述
<a name="w2aac28c10c27c15b9b3c17b5c15b1"></a>

若要改善查詢資料庫的 SQL 產生準確性，您可以提供資料表或資料欄的描述，以提供比簡短資料表或資料欄名稱更多的內容。您可以執行下列動作：
+ 若要新增資料表的描述，請在 `tables` 陣列中包含 [QueryGenerationTable](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationTable.html) 物件。在該物件中，指定 `name` 欄位中的資料表名稱和 `description` 欄位中的描述，如下列範例所示：

  ```
  {
      "name": "database.schema.tableA",
      "description": "Description for Table A"
  }
  ```
+ 若要新增資料欄的描述，請在 `tables` 陣列中包含 [QueryGenerationTable](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationTable.html) 物件。在該物件中，在 `name` 欄位中指定資料表的名稱，並包含 `columns` 欄位，該欄位會對應至 [QueryGenerationColumn](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationColumn.html) 的陣列。在 `QueryGenerationColumn` 物件中，在 `name` 欄位中包含資料欄的名稱，並在 `description` 欄位中包含描述，如下列範例所示：

  ```
  {
      "name": "database.schema.tableA",
      "columns": [
          {
              "name": "Column A",
              "description": "Description for Column A"
          }
      ]
  }
  ```
+ 您可以新增資料表和其中資料欄的描述，如下列範例所示：

  ```
  {
      "name": "database.schema.tableA",
      "description": "Description for Table A",
      "columns": [
          {
              "name": "columnA",
              "description": "Description for Column A"
          }
      ]
  }
  ```
**注意**  
以[跨資料庫查詢](https://docs.aws.amazon.com/redshift/latest/dg/cross-database-overview.html)中所述的模式輸入資料表和資料欄名稱。如果您的資料庫位於 AWS Glue Data Catalog，則格式為 `awsdatacatalog.gluedatabase.table`。

#### 在資料庫中包含或排除資料表或資料欄
<a name="w2aac28c10c27c15b9b3c17b5c15b3"></a>

您可以使用 [QueryGenerationTable](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationTable.html) 和 [QueryGenerationColumn](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationColumn.html) 物件中的 `inclusion` 欄位，建議在產生 SQL 時包含或排除的資料表或資料欄。您可以在 `inclusion` 欄位中指定下列其中一個值：
+ INCLUDE – 產生 SQL 時，只會包含您指定的資料表或資料欄作為內容。
+ EXCLUDE – 產生 SQL 時，會將您指定的資料表或資料欄排除為內容。

您可以透過以下方式指定是否包含或排除資料表或資料欄：
+ 若要包含或排除資料表，請在 `tables` 陣列中包含 [QueryGenerationTable](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationTable.html) 物件。在該物件中，指定 `name` 欄位中資料表的名稱，以及是否要在 `inclusion` 欄位中包含或排除，如下列範例所示：

  ```
  {
      "name": "database.schema.tableA",
      "inclusion": "EXCLUDE"
  }
  ```

  查詢引擎不會在用於產生 SQL 的其他內容中新增 `Table A`。
+ 若要包含或排除資料欄，請在 `tables` 陣列中包含 [QueryGenerationTable](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationTable.html) 物件。在該物件中，在 `name` 欄位中指定資料表的名稱，並包含 `columns` 欄位，該欄位會對應至 [QueryGenerationColumn](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationColumn.html) 的陣列。在 `QueryGenerationColumn` 物件中，在 `name` 欄位中包含資料欄的名稱，以及是否要在 `inclusion` 欄位中包含或排除，如下列範例所示：

  ```
  {
      "name": "database.schema.tableA",
      "columns": [
          {
              "name": "database.schema.tableA.columnA",
              "inclusion": "EXCLUDE"
          }
      ]
  }
  ```

  產生 SQL 時，SQL 產生會在內容的 `Table A` 中忽略 `Column A`。
+ 您可以在指定包含或排除項目時合併資料表和資料欄，如下列範例所示：

  ```
  {
      "name": "database.schema.tableA",
      "inclusion": "INCLUDE",
      "columns": [
          {
              "name": "database.schema.tableA.columnA",
              "inclusion": "EXCLUDE"
          }
      ]
  }
  ```

  SQL 產生包含 `Table A`，但在新增產生 SQL 的內容時會在其中排除 `Column A`。

**重要**  
資料表和資料欄排除無法取代防護機制。這些資料表和資料欄包含和排除會用作模型在產生 SQL 時要考慮的其他內容。

#### 將自然語言的查詢引擎範例對應提供給 SQL 查詢
<a name="w2aac28c10c27c15b9b3c17b5c15b5"></a>

若要改善查詢引擎將使用者查詢轉換為 SQL 查詢的準確性，您可以在 [QueryGenerationContext](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_QueryGenerationContext.html) 物件的 `curatedQueries` 欄位中提供範例，其會對應至 [CuratedQuery](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_CuratedQuery.html) 物件的陣列。每個物件皆包含下列欄位：
+ naturalLanguage – 自然語言查詢的範例。
+ sql – 對應至自然語言查詢的 SQL 查詢。

# 將結構化資料存放區與您的 Amazon Bedrock 知識庫同步
<a name="kb-data-source-structured-sync-ingest"></a>

將知識庫連接到結構化資料存放區之後，您可以執行同步以啟動中繼資料擷取程序，以便擷取資料。中繼資料可讓 Amazon Bedrock 知識庫將使用者提示轉譯為已連線資料庫的查詢。

每當您修改資料庫結構描述時，都需要同步變更。

若要了解如何將中繼資料擷取至知識庫並與最新資料同步，請選擇您偏好方法的索引標籤，然後遵循下列步驟：

------
#### [ Console ]

**將資料擷取到您的知識庫，並與最新的資料同步**

1. 開啟位於 [https://console.aws.amazon.com/bedrock/](https://console.aws.amazon.com/bedrock/) Amazon Bedrock 主控台。

1. 從左側導覽窗格選取**知識庫**，然後選擇您的知識庫。

1. 在**資料來源**區段中，選取**同步**以開始進行中繼資料擷取程序。若要停止目前正在同步的資料來源，請選取**停止**。資料來源必須目前正在進行同步，才能停止同步資料來源。您可以再次選取**同步**，以擷取剩餘的資料。

1. 資料擷取完成時若顯示成功，就會出現綠色的成功橫幅。

1. 您可以選擇資料來源以檢視其**同步歷史記錄**。選取**檢視警告**，查看資料擷取作業失敗的原因。

------
#### [ API ]

若要將資料擷取到您的知識庫並與最新資料同步，請使用 [Amazon Bedrock 代理程式建置時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)來傳送 [StartIngestionJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_StartIngestionJob.html) 請求。

使用透過 [Amazon Bedrock 代理程式建置時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)的 [GetIngestionJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_GetIngestionJob.html) 請求中傳回的 `ingestionJobId`，以追蹤擷取任務的狀態。

您也可以使用 [Amazon Bedrock 代理程式建置時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)傳送 [ListIngestionJobs](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_ListIngestionJobs.html) 請求，來查看資料來源所有擷取任務的資訊。

若要停止目前正在執行的資料擷取任務，請使用 [Amazon Bedrock 代理程式建置時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-bt)傳送 [StopIngestionJobs](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent_StopIngestionJob.html) 請求。當您準備好時，可以再次傳送 `StartIngestionJob` 請求，以擷取您的其餘資料。

------

**重要**  
如果您使用在主控台中為您建立的 Amazon Bedrock 知識庫服務角色，然後在向身分驗證角色授予資料庫存取權之前同步資料存放區，則同步會失敗，因為使用者尚未獲得存取資料存放區的許可。如需授予角色存取資料存放區許可的相關資訊，請參閱 [允許知識庫服務角色存取您的資料存放區](knowledge-base-prereq-structured.md#knowledge-base-prereq-structured-db-access)。