

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

# 搜尋索引
<a name="searching"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

若要搜尋 Amazon Kendra 索引，請使用[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API。`Query` API 會傳回您在應用程式中使用之索引文件的相關資訊。本節說明如何進行查詢、執行篩選條件，以及解譯您從 `Query` API 取得的回應。

若要搜尋您已 Amazon Kendra 編製索引的文件 Amazon Lex，請使用 [AMAZON.KendraSearchIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_KendraConfiguration.html)。如需使用 設定 Amazon Kendra 的範例 Amazon Lex，請參閱[為 Amazon Kendra 索引建立常見問答集機器人](https://docs.aws.amazon.com/lexv2/latest/dg/faq-bot-kendra-search.html)。

**Topics**
+ [查詢索引](searching-example.md)
+ [擷取段落](searching-retrieve.md)
+ [瀏覽索引](browsing.md)
+ [特色為搜尋結果](featured-results.md)
+ [HTML 的表格式搜尋](searching-tables.md)
+ [查詢建議](query-suggestions.md)
+ [查詢拼字檢查程式](query-spell-check.md)
+ [篩選和面向搜尋](filtering.md)
+ [篩選使用者內容](user-context-filter.md)
+ [查詢回應和回應類型](query-responses-types.md)
+ [調校和排序回應](tuning-sorting-responses.md)
+ [收合/展開查詢結果](expand-collapse-query-results.md)

# 查詢索引
<a name="searching-example"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

當您搜尋索引時， Amazon Kendra 會使用您提供的所有文件相關資訊，來判斷與輸入的搜尋詞彙最相關的文件。 Amazon Kendra 考慮的一些項目包括：
+ 文件的文字或內文。
+ 文件的標題。
+ 您標示為可搜尋的自訂文字欄位。
+ 您指定的日期欄位應該用來判斷文件的「重新整理」。
+ 可提供相關資訊的任何其他欄位。

Amazon Kendra 也可以根據您為搜尋設定的任何欄位/屬性篩選條件來篩選回應。例如，如果您有一個名為 "department" 的自訂欄位，您可以篩選回應，只傳回名為 "legal" 的部門的文件。如需詳細資訊，請參閱[自訂欄位或屬性](https://docs.aws.amazon.com/kendra/latest/dg/custom-attributes.html)。

傳回的搜尋結果會依為每個文件 Amazon Kendra 決定的相關性進行排序。系統會分頁結果，以便您一次向使用者顯示頁面。

若要搜尋您已 Amazon Kendra 編製索引的文件 Amazon Lex，請使用 [AMAZON.KendraSearchIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_KendraConfiguration.html)。如需使用 設定 Amazon Kendra 的範例 Amazon Lex，請參閱[為 Amazon Kendra 索引建立常見問答集機器人](https://docs.aws.amazon.com/lexv2/latest/dg/faq-bot-kendra-search.html)。

下列範例示範如何搜尋 index. Amazon Kendra determine 最適合查詢的搜尋結果類型 （答案、文件、問題答案）。您無法 Amazon Kendra 將 設定為將特定類型的搜尋回應 （答案、文件、問答） 傳回至查詢。

如需查詢回應的資訊，請參閱 [查詢回應和回應類型](query-responses-types.md)。

**Topics**
+ [先決條件](#searching-prerequisites)
+ [搜尋索引 （主控台）](#searching-index-console)
+ [搜尋索引 (SDK)](#searching-index-sdk)
+ [搜尋索引 (Postman)](#searching-index-postman)
+ [使用進階查詢語法搜尋](#searching-index-query-syntax)
+ [以語言搜尋](#searching-index-languages)

## 先決條件
<a name="searching-prerequisites"></a>

使用[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 查詢索引之前：
+ 設定索引的必要許可，並連接至資料來源或批次上傳您的文件。如需詳細資訊，請參閱 [IAM 角色](https://docs.aws.amazon.com/kendra/latest/dg/iam-roles.html)。當您呼叫 API 來建立索引和資料來源連接器或批次上傳文件時，您可以使用角色的 Amazon Resource Name。
+ 設定 AWS Command Line Interface、 開發套件，或前往 Amazon Kendra 主控台。如需詳細資訊，請參閱[設定 Amazon Kendra](https://docs.aws.amazon.com/kendra/latest/dg/setup.html)。
+ 建立索引並連線到文件或批次上傳文件的資料來源。如需詳細資訊，請參閱[建立索引](https://docs.aws.amazon.com/kendra/latest/dg/create-index.html)和[建立資料來源連接器](https://docs.aws.amazon.com/kendra/latest/dg/data-source.html)。

## 搜尋索引 （主控台）
<a name="searching-index-console"></a>

您可以使用 Amazon Kendra 主控台來搜尋和測試索引。您可以進行查詢並查看結果。

**使用主控台搜尋索引**

1. 登入 AWS 管理主控台 並在 Amazon Kendra https：//[http://console.aws.amazon.com/kendra/](https://console.aws.amazon.com/kendra) 開啟 主控台。

1. 在導覽窗格中，選擇**索引**。

1. 選擇您的索引。

1. 在導覽功能表中，選擇搜尋索引的選項。

1. 在文字方塊中輸入查詢，然後按 Enter 鍵。

1. Amazon Kendra 會傳回搜尋結果。

您也可以選取側邊面板中的燈泡圖示，以取得搜尋的查詢 ID。

## 搜尋索引 (SDK)
<a name="searching-index-sdk"></a>

**使用 Python 或 Java 搜尋索引**
+ 下列範例會搜尋索引。將 的值`query`變更為您的搜尋查詢，並將 `index_id`或 `indexId` 變更為您要搜尋之索引的索引識別符。

  您也可以在呼叫查詢 API 時，取得搜尋的[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) ID 做為回應元素的一部分。

------
#### [ Python ]

  ```
  import boto3
  import pprint
  
  kendra = boto3.client("kendra")
  
  # Provide the index ID
  index_id = "index-id"
  # Provide the query text
  query = "query text"
  
  response = kendra.query(
          QueryText = query,
          IndexId = index_id)
  
  print("\nSearch results for query: " + query + "\n")        
  
  for query_result in response["ResultItems"]:
  
      print("-------------------")
      print("Type: " + str(query_result["Type"]))
          
      if query_result["Type"]=="ANSWER" or query_result["Type"]=="QUESTION_ANSWER":
          answer_text = query_result["DocumentExcerpt"]["Text"]
          print(answer_text)
  
      if query_result["Type"]=="DOCUMENT":
          if "DocumentTitle" in query_result:
              document_title = query_result["DocumentTitle"]["Text"]
              print("Title: " + document_title)
          document_text = query_result["DocumentExcerpt"]["Text"]
          print(document_text)
  
      print("------------------\n\n")
  ```

------
#### [ Java ]

  ```
  package com.amazonaws.kendra;
  
  import software.amazon.awssdk.services.kendra.KendraClient;
  import software.amazon.awssdk.services.kendra.model.QueryRequest;
  import software.amazon.awssdk.services.kendra.model.QueryResponse;
  import software.amazon.awssdk.services.kendra.model.QueryResultItem;
  
  public class SearchIndexExample {
      public static void main(String[] args) {
          KendraClient kendra = KendraClient.builder().build();
  
          String query = "query text";
          String indexId = "index-id";
  
          QueryRequest queryRequest = QueryRequest
              .builder()
              .queryText(query)
              .indexId(indexId)
              .build();
  
          QueryResponse queryResponse = kendra.query(queryRequest);
  
          System.out.println(String.format("\nSearch results for query: %s", query));
          for(QueryResultItem item: queryResponse.resultItems()) {
              System.out.println("----------------------");
              System.out.println(String.format("Type: %s", item.type()));
  
              switch(item.type()) {
                  case QUESTION_ANSWER:
                  case ANSWER:
                      String answerText = item.documentExcerpt().text();
                      System.out.println(answerText);
                      break;
                  case DOCUMENT:
                      String documentTitle = item.documentTitle().text();
                      System.out.println(String.format("Title: %s", documentTitle));
                      String documentExcerpt = item.documentExcerpt().text();
                      System.out.println(String.format("Excerpt: %s", documentExcerpt));
                      break;
                  default:
                      System.out.println(String.format("Unknown query result type: %s", item.type()));
  
              }
  
              System.out.println("-----------------------\n");
          }
      }
  }
  ```

------

## 搜尋索引 (Postman)
<a name="searching-index-postman"></a>

您可以使用 [Postman](https://www.postman.com/) 查詢和測試 Amazon Kendra 索引。

**使用 Postman 搜尋索引**

1. 在 Postman 中建立新的集合，並將請求類型設定為 **POST**。

1. 輸入端點 URL。例如，https：//*https://kendra.<region>.amazonaws.com*。

1. 選取**授權**索引標籤，然後輸入下列資訊。
   + **類型** - 選取**AWS 簽章**。
   + **AccessKey** - 輸入您建立 IAM 使用者時產生的存取金鑰。
   + **SecretKey** - 輸入建立 IAM 使用者時產生的私密金鑰。
   + **AWS 區域** - 輸入您索引的區域。例如，*us-west-2*。
   + **服務名稱** - 輸入 *kendra*。這區分大小寫，因此必須是小寫。
**警告**  
如果您輸入不正確的服務名稱或不使用小寫，當您選取**傳送**以傳送請求時，會擲回錯誤：「憑證應範圍限定為正確的服務「kendra」。」  
您也必須檢查是否已輸入正確的存取金鑰和私密金鑰。

1. 選取**標頭**索引標籤，然後輸入下列索引鍵和值資訊。
   + 金鑰：*X-Amz-Target*

     值：*com.amazonaws.kendra.AWSKendraFrontendService.Query*
   + 金鑰：*內容編碼*

     值：*amz-1.0*

1. 選取**內文**索引標籤，然後執行下列動作。
   + 選擇請求內文的**原始** JSON 類型。
   + 輸入包含索引 ID 和查詢文字的 JSON。

     ```
     {
         "IndexId": "index-id",
         "QueryText": "enter a query here"
     }
     ```
**警告**  
如果您的 JSON 未使用正確的推論，則會擲回錯誤：「SerializationException」。檢查 JSON 中的推論。

1. 選取**傳送** （靠近右上角）。

## 使用進階查詢語法搜尋
<a name="searching-index-query-syntax"></a>

您可以使用進階查詢語法或運算子，建立比簡單關鍵字或自然語言查詢更具體的查詢。這包括範圍、布林值、萬用字元等。透過使用運算子，您可以為查詢提供更多內容，並進一步精簡搜尋結果。

Amazon Kendra 支援下列運算子。
+ 布林值：限制或擴展搜尋的邏輯。例如， 會將搜尋`amazon AND sports`限制為僅搜尋包含兩個詞彙的文件。
+ 括號：依優先順序讀取巢狀查詢詞彙。例如， 會在 `(amazon AND sports)`之前`(amazon AND sports) NOT rainforest`讀取`NOT rainforest`。
+ 範圍：日期或數值範圍值。範圍可以是包含、獨佔或無限制。例如，您可以搜尋上次在 2020 年 1 月 1 日至 2020 年 12 月 31 日期間更新的文件，包括這些日期。
+ 欄位：使用特定欄位來限制搜尋。例如，您可以在「位置」欄位中搜尋具有「美國」的文件。
+ 萬用字元：部分符合文字字串。例如， `Cloud*`可以比對 CloudFormation。 Amazon Kendra 目前僅支援結尾萬用字元。
+ 確切引號：完全符合文字字串。例如，包含 的文件`"Amazon Kendra" "pricing"`。

您可以使用上述任一運算子的組合。

請注意，過度使用運算子或高度複雜的查詢可能會影響查詢延遲。萬用字元是延遲方面一些最昂貴的運算子。一般規則是您使用的詞彙和運算子越多，對延遲的潛在影響就越大。影響延遲的其他因素包括編製索引的文件平均大小、索引大小、搜尋結果的任何篩選，以及 Amazon Kendra 索引的整體負載。

### Boolean
<a name="query-syntax-boolean"></a>

您可以使用布林運算子 `AND`、`OR`、 來合併或排除單字`NOT`。

以下是使用布林值運算子的範例。

 **`amazon AND sports`** 

傳回搜尋結果，其中包含文字中的「amazon」和「sports」，例如 Amazon Prime 影片運動或其他類似內容。

 **`sports OR recreation`** 

在文字中傳回包含 'sports' 或 'recreation' 或兩者的搜尋結果。

 **`amazon NOT rainforest`** 

傳回搜尋結果，其中包含文字中的「amazon」一詞，但不包含「rainforest」一詞。這是為了搜尋有關公司 Amazon 而非 Amazon Rainforest 的文件。

### 括號
<a name="query-syntax-parentheses"></a>

您可以使用括號，依優先順序查詢巢狀單字。括號指出應 Amazon Kendra 如何讀取查詢。

以下是使用括號運算子的範例。

 **`(amazon AND sports) NOT rainforest`** 

傳回包含文字中 'amazon' 和 'sports' 兩個詞彙的文件，但不包含 'rainforest' 一詞。這是為了搜尋 Amazon Prime 影片運動或其他類似的內容，而不是 Amazon Rainforest 中的冒險運動。括號有助於指出 `amazon AND sports` 應該在 之前讀取`NOT rainforest`。查詢不應讀取為 `amazon AND (sports NOT rainforest)`。

 **`(amazon AND (sports OR recreation)) NOT rainforest`** 

傳回包含 'sports' 或 'recreation' 或兩者，以及 'amazon' 一詞的文件。但不包含「rainforest」一詞。這是搜尋 Amazon Prime 影片運動或娛樂，而不是 Amazon Rainforest 中的冒險運動。括號有助於指出 `sports OR recreation` 應該在與 之前讀取的 'amazon' 結合之前讀取`NOT rainforest`。查詢不應讀取為 `amazon AND (sports OR (recreation NOT rainforest))`。

### 範圍
<a name="query-syntax-ranges"></a>

您可以使用一系列的值來篩選搜尋結果。您可以指定屬性和範圍值。這可以是日期或數字類型。

日期範圍必須採用下列格式：
+ Epoch
+ YYYY
+ YYYY-mm
+ YYYY-mm-dd
+ YYYY-mm-dd'T'HH

您也可以指定是否包含或排除範圍的較低和較高值。

以下是使用範圍運算子的範例。

 **`_processed_date:>2019-12-31 AND _processed_date:<2021-01-01`** 

傳回 2020 年處理的文件，大於 2019 年 12 月 31 日且小於 2021 年 1 月 1 日。

 **`_processed_date:>=2020-01-01 AND _processed_date:<=2020-12-31`** 

傳回在 2020 年處理的文件，大於或等於 2020 年 1 月 1 日，以及小於或等於 2020 年 12 月 31 日。

 **`_document_likes:<1`** 

傳回零喜歡或沒有使用者意見回饋的文件，少於 1 個類似。

您可以指定是否應將範圍視為包含或排除指定範圍值。

 **包含** 

 **`_last_updated_at:[2020-01-01 TO 2020-12-31]`** 

傳回上次在 2020 年更新的文件，包括 2020 年 12 月 1 日至 2020 年 12 月 31 日的日期。

 **獨家** 

 **`_last_updated_at:{2019-12-31 TO 2021-01-01}`** 

傳回上次在 2020 年更新的文件 - 不包括 2019 年 12 月 31 日和 2021 年 1 月 1 日的日期。

對於不包含或獨佔的未限制範圍，只需使用 < 和 > 運算子。例如 `_last_updated_at:>2019-12-31 AND _last_updated_at:<2021-01-01` 

#### 欄位
<a name="query-syntax-fields"></a>

您可以將搜尋限制為僅傳回符合特定欄位中值的文件。欄位可以是任何類型的欄位。

以下是使用欄位層級內容運算子的範例。

 **`status:"Incomplete" AND financial_year:2021`** 

傳回 2021 會計年度的文件，其狀態為不完整。

 **`(sports OR recreation) AND country:"United States" AND level:"professional"`** 

傳回討論美國職業運動或重建的文件。

#### 萬用字元
<a name="query-syntax-wildcards"></a>

您可以使用萬用字元運算子擴大搜尋範圍，以考量字詞和片語的變體。這在搜尋名稱變體時非常有用。 Amazon Kendra 目前僅支援結尾萬用字元。結尾萬用字元的字首字元數必須大於 2。

以下是使用萬用字元運算子的範例。

 **`Cloud*`** 

傳回包含 CloudFormation 和 CloudWatch 等變體的文件。

 **`kendra*aws`** 

傳回包含 kendra.amazonaws 等變體的文件。

 **`kendra*aws*`** 

傳回包含變體的文件，例如 kendra.amazonaws.com

#### 精確引號
<a name="query-syntax-exact-quote"></a>

您可以使用引號來搜尋一段文字的完全相符項目。

以下是使用引號的範例。

 **`"Amazon Kendra" "pricing"`** 

傳回同時包含片語 'Amazon Kendra' 和術語 'pricing' 的文件。文件必須同時包含 'Amazon Kendra' 和 'pricing'，才能傳回結果。

 **`"Amazon Kendra" "pricing" cost`** 

傳回同時包含片語 'Amazon Kendra' 和術語 'pricing'，以及選用術語 'cost' 的文件。文件必須同時包含 'Amazon Kendra' 和 'pricing'，才能傳回結果，但不一定包含 'cost'。

#### 無效的查詢語法
<a name="query-syntax-invalid"></a>

Amazon Kendra 如果您的查詢語法發生問題或目前不支援您的查詢， 會發出警告 Amazon Kendra。如需詳細資訊，請參閱 [API 文件以取得查詢警告](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Warning.html)。

下列查詢是無效的查詢語法範例。

 **`_last_updated_at:<2021-12-32`** 

無效的日期。Gregorian 行事曆中不存在第 32 天，由 使用 Amazon Kendra。

 **`_view_count:ten`** 

無效的數值。必須使用數字來表示數值。

 **`nonExistentField:123`** 

欄位搜尋無效。欄位必須存在才能使用欄位搜尋。

 **`Product:[A TO D]`** 

無效的範圍。範圍必須使用數值或日期。

 **`OR Hello`** 

布林值無效。運算子必須與術語搭配使用，並放置在術語之間。

## 以語言搜尋
<a name="searching-index-languages"></a>

您可以搜尋支援語言的文件。您可以在 [AttributeFilter](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeFilter.html) 中傳遞語言代碼，以您選擇的語言傳回篩選的文件。您可以使用支援的語言輸入查詢。

如果您未指定語言， 預設會以英文 Amazon Kendra 查詢文件。如需支援語言的詳細資訊，包括其代碼，請參閱[新增英文以外語言的文件](https://docs.aws.amazon.com/kendra/latest/dg/in-adding-languages.html)。

若要在 主控台中搜尋支援語言的文件，請選取您的索引，然後從導覽功能表中選取搜尋索引的選項。選擇搜尋設定，然後從下拉式清單語言中選取語言，以選擇要傳回文件**的語言**。

下列範例示範如何搜尋西班牙文文件。

**在 主控台中以西班牙文搜尋索引**

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

1. 在導覽功能表中，選擇**索引**，然後選擇您的索引。

1. 在導覽功能表中，選擇搜尋索引的選項。

1. 在搜尋設定中，選取**語言**下拉式清單，然後選擇西班牙文。

1. 在文字方塊中輸入查詢，然後按 Enter 鍵。

1. Amazon Kendra 會以西班牙文傳回搜尋結果。

**使用 CLI、Python 或 Java 搜尋西班牙文索引**
+ 下列範例會搜尋西班牙文的索引。將值變更為`searchString`您的搜尋查詢，並將值`indexID`變更為您要搜尋之索引的識別符。西班牙文的語言代碼為 `es`。您可以將此取代為您自己的語言代碼。

------
#### [ CLI ]

  ```
  {
    "EqualsTo":{      
      "Key": "_language_code",
      "Value": {
      "StringValue": "es"
      }
    }
  }
  ```

------
#### [ Python ]

  ```
  import boto3
  import pprint
  
  kendra = boto3.client("kendra")
  
  # Provide the index ID
  index_id = "index-id"
  # Provide the query text
  query = "search-string"
  
  # Includes the index ID, query text, and language attribute filter
  response = kendra.query(
          QueryText = query,
          IndexId = index_id,
          AttributeFilter = {
              "EqualsTo": {      
                  "Key": "_language_code",
                  "Value": {
                      "StringValue": "es"
                      }
                  }
              })
  
  print ("\nSearch results|Resultados de la búsqueda: " + query + "\n")        
  
  for query_result in response["ResultItems"]:
  
      print("-------------------")
      print("Type: " + str(query_result["Type"]))
          
      if query_result["Type"]=="ANSWER" or query_result["Type"]=="QUESTION_ANSWER":
          answer_text = query_result["DocumentExcerpt"]["Text"]
          print(answer_text)
  
      if query_result["Type"]=="DOCUMENT":
          if "DocumentTitle" in query_result:
              document_title = query_result["DocumentTitle"]["Text"]
              print("Title: " + document_title)
          document_text = query_result["DocumentExcerpt"]["Text"]
          print(document_text)
  
      print("------------------\n\n")
  ```

------
#### [ Java ]

  ```
  package com.amazonaws.kendra;
  
  import software.amazon.awssdk.services.kendra.KendraClient;
  import software.amazon.awssdk.services.kendra.model.QueryRequest;
  import software.amazon.awssdk.services.kendra.model.QueryResponse;
  import software.amazon.awssdk.services.kendra.model.QueryResultItem;
  
  public class SearchIndexExample {
      public static void main(String[] args) {
          KendraClient kendra = KendraClient.builder().build();
  
          String query = "searchString";
          String indexId = "indexID";
  
          QueryRequest queryRequest = QueryRequest.builder()
              .queryText(query)
              .indexId(indexId)
              .attributeFilter(
                   AttributeFilter.builder()
                       .withEqualsTo(
                           DocumentAttribute.builder()
                               .withKey("_language_code")
                               .withValue("es")
                               .build())
                       .build())
              .build();
  
          QueryResponse queryResponse = kendra.query(queryRequest);
  
          System.out.println(String.format("\nSearch results|
                                            Resultados de la búsqueda: %s", query));
          for(QueryResultItem item: queryResponse.resultItems()) {
              System.out.println("----------------------");
              System.out.println(String.format("Type: %s", item.type()));
  
              switch(item.type()) {
                  case QUESTION_ANSWER:
                  case ANSWER:
                      String answerText = item.documentExcerpt().text();
                      System.out.println(answerText);
                      break;
                  case DOCUMENT:
                      String documentTitle = item.documentTitle().text();
                      System.out.println(String.format("Title: %s", documentTitle));
                      String documentExcerpt = item.documentExcerpt().text();
                      System.out.println(String.format("Excerpt: %s", documentExcerpt));
                      break;
                  default:
                      System.out.println(String.format("Unknown query result type: %s", item.type()));
  
              }
  
              System.out.println("-----------------------\n");
          }
      }
  }
  ```

------

# 擷取段落
<a name="searching-retrieve"></a>

您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_Retrieve.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Retrieve.html) API 做為擷取器，以擷取擴增產生 (RAG) 系統。

RAG 系統使用生成式人工智慧來建置問題回答應用程式。RAG 系統包含擷取器和大型語言模型 (LLM)。鑑於查詢，擷取器會從文件組合中識別最相關的文字區塊，並將其饋送至 LLM，以提供最有用的答案。然後，LLM 會分析相關的文字區塊或段落，並產生查詢的完整回應。

`Retrieve` API 會查看稱為*段落*的文字或摘錄區塊，並傳回與查詢最相關的前文。

如同 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API，`Retrieve`API 也會搜尋相關資訊。擷取 API 的資訊擷取會考慮查詢的內容，以及索引文件中所有可用的資訊。不過，根據預設，`Query`API 只會傳回最多 100 個字符單字的摘錄段落。使用 `Retrieve` API，您可以擷取最多 200 個字符字和最多 100 個語義相關段落的較長段落。這不包括來自您索引的問答或常見問答集類型回應。這些段落也稱為區塊，是文字摘錄，可以從同一份文件的多個文件和多個部分以語義方式擷取。Kendra 的 GenAI Enterprise Edition 索引提供高準確度的擷取結果，使用向量和關鍵字索引的混合搜尋，以及深度學習模型的排名。

您也可以使用 `Retrieve` API 執行下列動作：
+ 在索引層級覆寫提升
+ 根據文件欄位或屬性進行篩選
+ 根據使用者或其群組對文件的存取進行篩選
+ 檢視擷取段落結果的可信度分數儲存貯體。可信度儲存貯體提供相對排名，指出 Amazon Kendra 回應與查詢相關的可信度。
**注意**  
可信度分數儲存貯體目前僅適用於英文。

您也可以在回應中包含某些欄位，這些欄位可能會提供有用的額外資訊。

`Retrieve` API 目前不支援下列功能：使用[進階查詢語法](https://docs.aws.amazon.com/kendra/latest/dg/searching-example.html#searching-index-query-syntax)進行查詢、建議的查詢[拼字修正](https://docs.aws.amazon.com/kendra/latest/dg/query-spell-check.html)、[面向](https://docs.aws.amazon.com/kendra/latest/dg/filtering.html#search-facets)、自動完成搜尋查詢的[查詢建議](https://docs.aws.amazon.com/kendra/latest/dg/query-suggestions.html)，以及[增量學習](https://docs.aws.amazon.com/kendra/latest/dg/submitting-feedback.html)。任何擷取 API 查詢都不會出現在分析儀表板中。

`Retrieve` API 會共用您為索引設定的[查詢容量單位](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CapacityUnitsConfiguration.html)數量。如需單一容量單位中包含的內容和索引的預設基本容量的詳細資訊，請參閱[調整容量](https://docs.aws.amazon.com/kendra/latest/dg/adjusting-capacity.html)。

**注意**  
如果您使用 Amazon Kendra 開發人員版本，則無法新增容量；您只能在使用 Amazon Kendra Enterprise Edition 時新增容量。如需開發人員和企業版本中包含內容的詳細資訊，請參閱[Amazon Kendra 版本](https://docs.aws.amazon.com/kendra/latest/dg/what-is-kendra.html#kendra-editions)。

以下是使用 `Retrieve` API 從 索引中的文件擷取前 100 個最相關段落的範例 "how does amazon kendra work?"

------
#### [ Python ]

```
import boto3
import pprint

kendra = boto3.client("kendra")

# Provide the index ID
index_id = "index-id"
# Provide the query text
query = "how does amazon kendra work?"
# You can retrieve up to 100 relevant passages
# You can paginate 100 passages across 10 pages, for example
page_size = 10
page_number = 10

result = kendra.retrieve(
        IndexId = index_id,
        QueryText = query,
        PageSize = page_size,
        PageNumber = page_number)

print("\nRetrieved passage results for query: " + query + "\n")        

for retrieve_result in result["ResultItems"]:

    print("-------------------")
    print("Title: " + str(retrieve_result["DocumentTitle"]))
    print("URI: " + str(retrieve_result["DocumentURI"]))
    print("Passage content: " + str(retrieve_result["Content"]))
    print("------------------\n\n")
```

------
#### [ Java ]

```
package com.amazonaws.kendra;

import software.amazon.awssdk.services.kendra.KendraClient;
import software.amazon.awssdk.services.kendra.model.RetrieveRequest;
import software.amazon.awssdk.services.kendra.model.RetrieveResult;
import software.amazon.awssdk.services.kendra.model.RetrieveResultItem;

public class RetrievePassageExample {
    public static void main(String[] args) {
        KendraClient kendra = KendraClient.builder().build();
        
        String indxId = "index-id";
        String query = "how does amazon kendra work?";
        Integer pgSize = 10;
        Integer pgNumber = 10;

        RetrieveRequest retrieveRequest = retrieveRequest
            .builder()
            .indexId(indxId)
            .queryText(query)
            .pageSize(pgSize)
            .pageNumber(pgNumber)
            .build();

        RetrieveResult retrieveResult = kendra.retrieve(retrieveRequest);

        System.out.println(String.format("\nRetrieved passage results for query: %s", query));
        for(RetrieveResultItem item: retrieveResult.resultItems()) {
            System.out.println("----------------------");
            System.out.println(String.format("Title: %s", documentTitle));
            System.out.println(String.format("URI: %s", documentURI));
            System.out.println(String.format("Passage content: %s", content));
            System.out.println("-----------------------\n");
        }
    }
}
```

------

# 瀏覽索引
<a name="browsing"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

您可以依文件的屬性或面向瀏覽文件，而不必輸入搜尋查詢。 Amazon Kendra *索引瀏覽*可以透過自由瀏覽索引來協助您的使用者探索文件，而無需考慮特定的查詢。這也有助於您的使用者廣泛瀏覽索引，做為搜尋的起點。

索引瀏覽只能用於依排序類型的文件屬性或構面進行搜尋。您不能使用索引瀏覽搜尋整個索引。如果查詢文字遺失，則 Amazon Kendra 會要求文件屬性篩選條件或面向，以及排序類型。

若要使用[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 允許索引瀏覽，您必須包含 [AttributeFilter](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeFilter.html) 或 [Facet](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Facet.html) 和 [SortingConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_SortingConfiguration.html)。若要允許在主控台中瀏覽索引，請在導覽功能表中的**索引**下選取索引，然後選取搜尋索引的選項。在搜尋方塊中，按 *Enter* 鍵兩次。選取下拉式清單 **篩選搜尋結果**以選擇篩選條件，然後選取下拉式清單 **排序**以選擇排序類型。

以下是依文件建立日期的遞減順序瀏覽西班牙文文件索引的範例。

------
#### [ CLI ]

```
aws kendra query \
--index-id "index-id" \
--attribute-filter '{   
    "EqualsTo":{
      "Key": "_language_code",
      "Value": {
        "StringValue": "es"
      }
    }
  }' \
--sorting-configuration '{
    "DocumentAttributeKey": "_created_at",
    "SortOrder": "DESC"
  }'
```

------
#### [ Python ]

```
import boto3

kendra = boto3.client("kendra")

# Must include the index ID, the attribute filter, and sorting configuration
response = kendra.query(
        IndexId = "index-id",
        AttributeFilter = {
            "EqualsTo": {      
                "Key": "_language_code",
                "Value": {
                    "StringValue": "es"
                    }
                }
            },
        SortingConfiguration = {
            "DocumentAttributeKey": "_created_at",
            "SortOrder": "DESC"})

print("\nSearch results|Resultados de la búsqueda: \n")

for query_result in response["ResultItems"]:

    print("-------------------")
    print("Type: " + str(query_result["Type"]))
        
    if query_result["Type"]=="ANSWER" or query_result["Type"]=="QUESTION_ANSWER":
        answer_text = query_result["DocumentExcerpt"]["Text"]
        print(answer_text)

    if query_result["Type"]=="DOCUMENT":
        if "DocumentTitle" in query_result:
            document_title = query_result["DocumentTitle"]["Text"]
            print("Title: " + document_title)
        document_text = query_result["DocumentExcerpt"]["Text"]
        print(document_text)

    print("------------------\n\n")
```

------
#### [ Java ]

```
package com.amazonaws.kendra;

import software.amazon.awssdk.services.kendra.KendraClient;
import software.amazon.awssdk.services.kendra.model.QueryRequest;
import software.amazon.awssdk.services.kendra.model.QueryResult;
import software.amazon.awssdk.services.kendra.model.QueryResultItem;

public class SearchIndexExample {
    public static void main(String[] args) {
        KendraClient kendra = KendraClient.builder().build();
        QueryRequest queryRequest = QueryRequest.builder()
            .withIndexId("index-id")
            .withAttributeFilter(AttributeFilter.builder()
                .withEqualsTo(DocumentAttribute.builder()
                    .withKey("_language_code")
                    .withValue(DocumentAttributeValue.builder()
                        .withStringValue("es")
                        .build())
                    .build())
                .build())
            .withSortingConfiguration(SortingConfiguration.builder()
                .withDocumentAttributeKey("_created_at")
                .withSortOrder("DESC")
                .build())
            .build());
            
        QueryResult queryResult = kendra.query(queryRequest);
        for (QueryResultItem item : queryResult.getResultItems()) {
            System.out.println("----------------------");
            System.out.println(String.format("Type: %s", item.getType()));
        
            switch (item.getType()) {
                case QueryResultType.QUESTION_ANSWER:
                case QueryResultType.ANSWER:
                    String answerText = item.getDocumentExcerpt().getText();
                    System.out.println(answerText);
                    break;
                case QueryResultType.DOCUMENT:
                    String documentTitle = item.getDocumentTitle().getText();
                    System.out.println(String.format("Title: %s", documentTitle));
                    String documentExcerpt = item.getDocumentExcerpt().getText();
                    System.out.println(String.format("Excerpt: %s", documentExcerpt));
                    break;
                default:
                    System.out.println(String.format("Unknown query result type: %s", item.getType()));
            }
            System.out.println("-----------------------\n");
        }
    }
}
```

------

# 特色為搜尋結果
<a name="featured-results"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

當您的使用者發出特定查詢時，您可以在搜尋結果中特徵化特定文件。這有助於讓您的使用者更明顯可見結果。精選結果與一般結果清單分開，並顯示在搜尋頁面頂端。您可以嘗試為不同的查詢提供不同的文件，或確保某些文件獲得應得的可見性。

您可以將特定查詢映射到結果中 的 特定文件。如果查詢包含完全相符的項目，則會在搜尋結果中顯示一或多個特定文件。

例如，您可以指定，如果您的使用者發出查詢「新產品 2023」，請選取搜尋結果頁面頂端名為「最新消息」和「即將推出」的文件。這有助於確保新產品上的這些文件獲得應有的可見性。

Amazon Kendra 如果已為搜尋結果頁面頂端的 功能選取結果，則 不會複製搜尋結果。如果特徵結果已超過所有其他結果，則特徵結果不會再次排名為第一個結果。

若要特徵化特定結果，您必須使用查詢中包含的關鍵字或片語來指定完整文字查詢的完全相符項目，而非部分相符項目。例如，如果您只在特色結果集中指定查詢 'Kendra'，像是「Kendra 如何以語意排列結果？」的查詢 不會轉譯特色結果。精選結果是針對特定查詢所設計，而不是範圍太廣的查詢。 Amazon Kendra 自然處理關鍵字類型查詢，以對搜尋結果中最有用的文件進行排名，避免根據簡單關鍵字過度描述結果。

如果您的使用者經常使用某些查詢，則可以為特色結果指定這些查詢。例如，如果您使用 [Amazon Kendra Analytics](https://docs.aws.amazon.com/kendra/latest/dg/search-analytics.html) 查看您的熱門查詢，並找到特定查詢，例如「Kendra 如何以語義方式排名結果？」 和 'kendra 語意搜尋' 經常使用，因此這些查詢對於為 指定名為 'Amazon Kendra search 101' 的文件可能很有用。

Amazon Kendra 會將特色結果的查詢視為不區分大小寫。 會將查詢 Amazon Kendra 轉換為小寫，並將結尾空白字元取代為單一空格。 Amazon Kendra 當您指定特色結果的查詢時，所有其他字元會與其相同。

您可以使用 [CreateFeaturedResultsSet](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateFeaturedResultsSet.html) API，建立一組映射至特定查詢的精選結果。如果您使用 主控台，請選取您的索引，然後在導覽功能表中選取**特色結果**，以建立特色結果集。每個索引最多可以建立 50 組特色結果、每個集最多要特色化四份文件，以及每個特色結果集最多 49 個查詢文字。您可以聯絡 [Support](https://aws.amazon.com/contact-us/) 來請求提高這些限制。

您可以跨多組特色結果選取相同的文件。不過，您不得跨多個集使用相同的完全相符查詢文字。您為特徵結果指定的查詢在每個索引的特徵結果集必須是唯一的。

在選取最多四個特色文件時，您可以安排文件的順序。如果您使用 API，您列出特色文件的順序與特色結果中顯示的順序相同。如果您使用 主控台，當您在結果中選取 的 文件時，可以直接拖放文件順序。

設定特色結果時，仍會遵守某些使用者和群組可存取某些文件，而其他使用者和群組無法存取的存取控制。對於使用者內容篩選也是如此。例如，使用者 A 屬於 'Interns' 公司群組，不應存取公司秘密上的文件。如果使用者 A 輸入具有公司秘密文件的查詢，則使用者 A 不會在其結果中看到此文件。搜尋結果頁面上的任何其他結果也是如此。您也可以使用標籤來控制對特色結果集的存取，這是 Amazon Kendra 您控制存取的資源。

以下是建立一組精選結果的範例，其中包含「新產品 2023」、「新產品可用」映射至名為「最新消息」(doc-id-1) 和「即將推出」(doc-id-2) 的文件。

------
#### [ CLI ]

```
aws kendra create-featured-results-set \
 --featured-results-set-name 'New product docs to feature' \
 --description "Featuring What's new and Coming soon docs" \
 --index-id index-id \
 --query-texts 'new products 2023' 'new products available' \
 --featured-documents '{"Id":"doc-id-1", "Id":"doc-id-2"}'
```

------
#### [ Python ]

```
import boto3
from botocore.exceptions import ClientError
import pprint
import time

kendra = boto3.client("kendra")

print("Create a featured results set.")

# Provide a name for the featured results set
featured_results_name = "New product docs to feature"
# Provide an optional decription for the featured results set
description = "Featuring What's new and Coming soon docs"
# Provide the index ID for the featured results set
index = "index-id"
# Provide a list of query texts for the featured results set
queries = ['new products 2023', 'new products available']
# Provide a list of document IDs for the featured results set
featured_doc_ids = [{"Id":"doc-id-1"}, {"Id":"doc-id-2"}]

try:
    featured_results_set_response = kendra.create_featured_results_set(
        FeaturedResultsSetName = featured_results_name,
        Decription = description,
        Index = index,
        QueryTexts = queries,
        FeaturedDocuments = featured_doc_ids
    )

    pprint.pprint(featured_results_set_response)

    featured_results_set_id = featured_results_set_response["FeaturedResultsSetId"]

    while True:
        # Get the details of the featured results set, such as the status
        featured_results_set_description = kendra.describe_featured_results_set(
            Id = featured_results_set_id
        )
        status = featured_results_set_description["Status"]
        print(" Featured results set status: "+status)
            
except  ClientError as e:
        print("%s" % e)

print("Program ends.")
```

------

# HTML 的表格式搜尋
<a name="searching-tables"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

Amazon Kendra的表格搜尋功能可以從內嵌在 HTML 文件中的資料表搜尋和擷取答案。當您搜尋索引時，如果與查詢相關， 會 Amazon Kendra 包含資料表的摘錄，並提供有用的資訊。

Amazon Kendra 會查看文件內文內文中的所有資訊，包括表格中的實用資訊。例如，索引包含業務報告，其中包含營運成本、收入和其他財務資訊的相關資料表。對於查詢，「2020-2022 的年度操作成本是多少？」， Amazon Kendra 可以從包含相關資料表資料欄「操作 （百萬美元）」和「財務年度」的資料表傳回摘錄，以及包含 2020 年、2021 年和 2022 年收入值的資料表資料列。資料表摘錄包含於結果中，以及文件標題、完整文件的連結，以及您選擇包含的任何其他文件欄位。

無論是在資料表的一個儲存格或多個儲存格中找到資訊，都可以在搜尋結果中顯示資料表摘錄。例如， Amazon Kendra 可以顯示針對以下每種查詢量身打造的資料表摘錄：
+ 「2020 年最高利率信用卡」
+ 「2020-2022 的最高利率信用卡」
+ 「2020-2022 年前 3 名的最高利率信用卡」
+ 「利率低於 10% 的信用卡」
+ 「所有可用的低息信用卡」

Amazon Kendra 會反白顯示與查詢最相關的資料表儲存格。搜尋結果中會顯示最相關的儲存格及其對應的資料列、資料欄和資料欄名稱。資料表摘錄最多顯示五個資料欄和三個資料列，取決於有多少資料表儲存格與查詢相關，以及原始資料表中有多少資料欄可用。最相關的儲存格會顯示在資料表摘錄中，以及下一個最相關的儲存格。

回應包含可信度儲存貯體 (`MEDIUM`、`HIGH`、`VERY_HIGH`)，以顯示資料表答案與查詢的相關性。如果資料表儲存格值為`VERY_HIGH`可信度，則會變成「頂端答案」並反白顯示。對於`HIGH`可信的資料表儲存格值，則會反白顯示。對於`MEDIUM`可信的資料表儲存格值，則不會反白顯示。回應中會傳回資料表答案的整體可信度。例如，如果資料表大部分包含可`HIGH`信度的資料表儲存格，則資料表答案回應中傳回的整體可信度為`HIGH`可信度。

根據預設，資料表的重要性或權重不會高於文件的其他元件。在文件中，如果資料表僅稍微與查詢相關，但有高度相關的段落， 會 Amazon Kendra 傳回該段落的摘錄。搜尋結果會在相同文件或其他文件中顯示提供最佳答案和最有用資訊的內容片段。如果資料表的可信度低於可`MEDIUM`信度，則不會在回應中傳回資料表摘錄。

若要在現有索引上使用表格式搜尋，您必須重新索引內容。

Amazon Kendra 表格式搜尋支援[同義詞](https://docs.aws.amazon.com/kendra/latest/dg/index-synonyms.html) （包括自訂同義詞）。 Amazon Kendra 僅支援具有 HTML 資料表且位於資料表標籤內的英文文件。

下列範例顯示查詢結果中包含的資料表摘錄。若要檢視具有查詢回應的範例 JSON，包括資料表摘錄，請參閱[查詢回應和類型](https://docs.aws.amazon.com/kendra/latest/dg/query-responses-types.html)。

------
#### [ Python ]

```
import boto3
import pprint

kendra = boto3.client("kendra")

# Provide the index ID
index_id = <index-id>
# Provide the query text
query = "search string"

response = kendra.query(
        QueryText = query,
        IndexId = index_id)

print("\nSearch results for query: " + query + "\n")        

for query_result in response["ResultItems"]:

    print("-------------------")
    print("Type: " + str(query_result["Type"]))
    print("Type: " + str(query_result["Format"]))
        
    if query_result["Type"]=="ANSWER" and query_result["Format"]=="TABLE":
        answer_table = query_result["TableExcerpt"]
        print(answer_table)
        
    if query_result["Type"]=="ANSWER" and query_result["Format"]=="TEXT":
        answer_text = query_result["DocumentExcerpt"]
        print(answer_text)
        
    if query_result["Type"]=="QUESTION_ANSWER":
        question_answer_text = query_result["DocumentExcerpt"]["Text"]
        print(question_answer_text)

    if query_result["Type"]=="DOCUMENT":
        if "DocumentTitle" in query_result:
            document_title = query_result["DocumentTitle"]["Text"]
            print("Title: " + document_title)
        document_text = query_result["DocumentExcerpt"]["Text"]
        print(document_text)

    print("------------------\n\n")
```

------
#### [ Java ]

```
package com.amazonaws.kendra;

import software.amazon.awssdk.services.kendra.KendraClient;
import software.amazon.awssdk.services.kendra.model.QueryRequest;
import software.amazon.awssdk.services.kendra.model.QueryResponse;
import software.amazon.awssdk.services.kendra.model.QueryResultItem;

public class SearchIndexExample {
    public static void main(String[] args) {
        KendraClient kendra = KendraClient.builder().build();

        String query = "search string";
        String indexId = "index-id";

        QueryRequest queryRequest = QueryRequest
            .builder()
            .queryText(query)
            .indexId(indexId)
            .build();

        QueryResponse queryResponse = kendra.query(queryRequest);

        System.out.println(String.format("\nSearch results for query: %s", query));
        for(QueryResultItem item: queryResponse.resultItems()) {
            System.out.println("----------------------");
            System.out.println(String.format("Type: %s", item.type()));
            System.out.println(String.format("Format: %s", item.format()));
            
            switch(item.format()) {
                case TABLE:
                    String answerTable = item.TableExcerpt();
                    System.out.println(answerTable);
                    break;
            }

            switch(item.format()) {
                case TEXT:
                    String answerText = item.DocumentExcerpt();
                    System.out.println(answerText);
                    break;
            }

            switch(item.type()) {
                case QUESTION_ANSWER:
                    String questionAnswerText = item.documentExcerpt().text();
                    System.out.println(questionAnswerText);
                    break;
                case DOCUMENT:
                    String documentTitle = item.documentTitle().text();
                    System.out.println(String.format("Title: %s", documentTitle));
                    String documentExcerpt = item.documentExcerpt().text();
                    System.out.println(String.format("Excerpt: %s", documentExcerpt));
                    break;
                default:
                    System.out.println(String.format("Unknown query result type: %s", item.type()));

            }

            System.out.println("-----------------------\n");
        }
    }
}
```

------

# 查詢建議
<a name="query-suggestions"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

Amazon Kendra *查詢建議*可協助您的使用者更快輸入搜尋查詢，並引導其搜尋。

Amazon Kendra 根據下列其中一項建議與使用者相關的查詢：
+ 查詢歷史記錄或查詢日誌中的熱門查詢
+ 文件欄位/屬性的內容

您可以將 設定為 `SuggestionTypes``QUERY`或 `DOCUMENT_ATTRIBUTES`並呼叫 ，以設定使用查詢歷史記錄或文件欄位的偏好設定[https://docs.aws.amazon.com/kendra/latest/APIReference/API_GetQuerySuggestions.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_GetQuerySuggestions.html)。根據預設， Amazon Kendra 會使用查詢歷史記錄來提供建議。如果您呼叫 時同時啟用查詢歷史記錄和文件欄位，[https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsConfig.html)而且您尚未將`SuggestionTypes`偏好設定設定為使用文件欄位，則 Amazon Kendra 會使用查詢歷史記錄。

如果您使用 主控台，您可以根據查詢歷史記錄或文件欄位來提供查詢建議。您首先選取您的索引，然後在導覽功能表中**的擴充**下選取**查詢建議**。然後選取**設定查詢建議**。設定查詢建議後，系統會將您導向搜尋主控台，您可以在右側面板中選取**查詢歷史記錄**或**文件欄位**，然後在搜尋列中輸入搜尋查詢。

根據預設，使用查詢歷史記錄和文件欄位的查詢建議都會啟用，無需額外費用。您可以使用 `UpdateQuerySuggestionsConfig` API 隨時停用這些類型的查詢建議。若要根據查詢歷史記錄停用查詢建議，請在呼叫 `DISABLED`時將 `Mode`設定為 `UpdateQuerySuggestionsConfig`。若要根據文件欄位停用查詢建議，請在文件欄位組態`INACTIVE`中將 `AttributeSuggestionsMode`設定為 ，然後呼叫 `UpdateQuerySuggestionsConfig>`。如果您使用 主控台，您可以在查詢建議**設定中停用查詢建議**。

查詢建議不區分大小寫。 會將查詢字首和建議的查詢 Amazon Kendra 轉換為小寫、忽略所有單引號和雙引號，並以單一空格取代多個空格字元。 Amazon Kendra 會與所有其他特殊字元相同。如果使用者類型少於兩個字元或超過 60 個字元， Amazon Kendra 則不會顯示任何建議。

**Topics**
+ [使用查詢歷史記錄查詢建議](#query-suggestions-history)
+ [使用文件欄位查詢建議](#query-suggestions-doc-fields)
+ [從建議中封鎖特定查詢或文件欄位內容](#query-suggestions-blocklist)

## 使用查詢歷史記錄查詢建議
<a name="query-suggestions-history"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

**Topics**
+ [選取建議查詢的設定](#query-suggestions-history-settings)
+ [保留查詢歷史記錄時清除建議](#query-suggestions-history-clear)
+ [沒有可用的建議](#query-suggestions-history-none)

您可以選擇根據查詢歷史記錄或查詢日誌中的熱門查詢來建議與使用者相關的查詢。 Amazon Kendra 會使用使用者搜尋並從這些查詢中學習的所有查詢，以向您的使用者提出建議。當使用者開始輸入查詢時， Amazon Kendra 會建議使用者熱門查詢。如果查詢的字首或前幾個字元符合使用者開始輸入為查詢的內容， Amazon Kendra 則建議查詢。

例如，使用者開始輸入查詢「即將發生的事件」。 Amazon Kendra 已從查詢歷史記錄得知許多使用者多次搜尋「即將發生的事件」。使用者看到「近期事件 2050」直接顯示在搜尋列下方，自動完成其搜尋查詢。使用者選取此查詢建議，搜尋結果中會傳回文件「新事件：2050 年發生的情況」。

您可以指定 如何 Amazon Kendra 選取符合資格的查詢來建議使用者。例如，您可以指定查詢建議必須已由至少 10 個唯一使用者 （預設為 3 個） 搜尋、在過去 30 天內搜尋，而且不包含[區塊清單中](https://docs.aws.amazon.com/kendra/latest/dg/query-suggestions.html#query-suggestions-blocklist)的任何單字或片語。 Amazon Kendra 要求查詢至少有一個搜尋結果，且至少包含一個超過四個字元的單字。

### 選取建議查詢的設定
<a name="query-suggestions-history-settings"></a>

您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsConfig.html) API 設定下列設定來選取建議查詢：
+ **模式** - 使用查詢歷史記錄的查詢建議為 `ENABLED`或 `LEARN_ONLY`。 Amazon Kendra 預設會啟用查詢建議。 `LEARN_ONLY` 會關閉查詢建議。如果關閉， Amazon Kendra 請繼續學習建議，但不會向使用者提出查詢建議。
+ **查詢日誌時段** - 查詢在查詢日誌時段中的最近時間。時間範圍是從當日到過去天數的整數值。
+ **沒有使用者資訊的查詢** — 設定為 `TRUE` 以包含所有查詢，或設定為 `FALSE` 以僅包含具有使用者資訊的查詢。如果您的搜尋應用程式包含使用者資訊，例如使用者 ID，當使用者發出查詢時，您可以使用此設定。根據預設，如果沒有與查詢相關聯的特定使用者資訊，則此設定不會篩選掉查詢。不過，您可以使用此設定，僅根據包含使用者資訊的查詢提出建議。
+ **唯一使用者** — 必須搜尋查詢才有資格向您的使用者建議的唯一使用者數量下限。此數字是整數值。
+ **查詢計數** - 必須搜尋查詢才有資格向您的使用者建議之查詢的最小次數。此數字是整數值。

這些設定會影響將查詢選取為熱門查詢以向您的使用者提供建議的方式。如何調整設定將取決於您的特定需求，例如：
+ 如果您的使用者通常每月平均搜尋一次，則可以將查詢日誌時段中的天數設定為 30 天。透過使用該設定，您可以在使用者於時段過期之前擷取使用者最近的大多數查詢。
+ 如果只有少量的查詢包含使用者資訊，而且您不想根據較小的樣本大小建議查詢，則可以設定查詢以包含所有使用者。
+ 如果您將熱門查詢定義為由至少 10 個唯一使用者搜尋，且至少搜尋 100 次，則您將唯一使用者設定為 10，而查詢計數為 100。

**警告**  
您對設定所做的變更可能不會立即生效。您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html) API 追蹤設定變更。更新設定生效的時間取決於您所做的更新，以及索引中的搜尋查詢數量。 Amazon Kendra 會在您變更設定後或套用[封鎖清單](https://docs.aws.amazon.com/kendra/latest/dg/query-suggestions.html#query-suggestions-blocklist)後，每 24 小時自動更新建議。

------
#### [ CLI ]

**擷取查詢建議**

```
aws kendra get-query-suggestions \
 --index-id index-id \
 --query-text "query-text" \
 --suggestion-types '["QUERY"]' \
 --max-suggestions-count 1 // If you want to limit the number of suggestions
```

**更新查詢建議**

例如，若要變更查詢日誌時間範圍和查詢必須搜尋的最小次數：

```
aws kendra update-query-suggestions-config \
 --index-id index-id \
 --query-log-look-back-window-in-days 30 \
 --minimum-query-count 100
```

------
#### [ Python ]

**擷取查詢建議**

```
import boto3
from botocore.exceptions import ClientError

kendra = boto3.client("kendra")

print("Get query suggestions.")

# Provide the index ID
index_id = "index-id"

# Provide the query text
query_text = "query"

# Provide the query suggestions type
query_suggestions_type = "QUERY"


# If you want to limit the number of suggestions
num_suggestions = 1
 
try:
    query_suggestions_response = kendra.get_query_suggestions(
        IndexId = index_id,
        QueryText = query_text,
        SuggestionTypes = query_suggestions_type,
        MaxSuggestionsCount = num_suggestions
    )

    # Print out the suggestions you received
    if ("Suggestions" in query_suggestions_response.keys()) {
        for (suggestion: query_suggestions_response["Suggestions"]) {
            print(suggestion["Value"]["Text"]["Text"]);
        }
    }
   
except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

**更新查詢建議**

例如，若要變更查詢日誌時間範圍和查詢必須搜尋的最小次數：

```
import boto3
from botocore.exceptions import ClientError
import pprint
import time

kendra = boto3.client("kendra")

print("Updating query suggestions settings/configuration for an index.")

# Provide the index ID
index_id = "index-id"

# Configure the settings you want to update
minimum_query_count = 100
query_log_look_back_window_in_days = 30

try:
    kendra.update_query_suggestions_config(
        IndexId = index_id,
        MinimumQueryCount = minimum_query_count,
        QueryLogLookBackWindowInDays = query_log_look_back_window_in_days
    )

    print("Wait for Amazon Kendra to update the query suggestions.")

    while True:
        # Get query suggestions description of settings/configuration
        query_sugg_config_response = kendra.describe_query_suggestions_config(
            IndexId = index_id
        )
        
        # If status is not UPDATING, then quit
        status = query_sugg_config_response["Status"]
        print(" Updating query suggestions config. Status: " + status)
        if status != "UPDATING":
            break
        time.sleep(60)

except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

------

### 保留查詢歷史記錄時清除建議
<a name="query-suggestions-history-clear"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html) API 清除查詢建議。清除建議只會刪除現有的查詢建議，不會刪除查詢歷史記錄中的查詢。當您清除建議時， 會根據從您清除建議時新增至查詢日誌的新查詢 Amazon Kendra 來學習新建議。

------
#### [ CLI ]

**清除查詢建議**

```
aws  kendra clear-query-suggestions \
 --index-id index-id
```

------
#### [ Python ]

**清除查詢建議**

```
import boto3
from botocore.exceptions import ClientError

kendra = boto3.client("kendra")

print("Clearing out query suggestions for an index.")

# Provide the index ID
index_id = "index-id"

try:
    kendra.clear_query_suggestions(
        IndexId = index_id
    )

    # Confirm last cleared date-time and that there are no suggestions
    query_sugg_config_response = kendra.describe_query_suggestions_config(
        IndexId = index_id
    )
    print("Query Suggestions last cleared at: " + str(query_sugg_config_response["LastClearTime"]));
    print("Number of suggestions available from the time of clearing: " + str(query_sugg_config_response["TotalSuggestionsCount"]));
        
except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

------

### 沒有可用的建議
<a name="query-suggestions-history-none"></a>

如果您沒有看到查詢的建議，可能是下列其中一個原因：
+ 您的索引中沒有足夠的查詢 Amazon Kendra 可供 學習。
+ 您的查詢建議設定太嚴格，導致大多數查詢從建議中篩選掉。
+ 您最近已清除建議， Amazon Kendra 但仍需要時間來累積新查詢，才能學習新建議。

您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html) API 檢查目前的設定。

## 使用文件欄位查詢建議
<a name="query-suggestions-doc-fields"></a>

**Topics**
+ [選取建議欄位的設定](#query-suggestions-doc-fields-settings)
+ [文件欄位中的使用者控制](#query-suggestions-doc-fields-user-control)

您可以選擇根據文件欄位的內容，建議與使用者相關的查詢。與其使用查詢歷史記錄來建議其他熱門的相關查詢，您可以使用文件欄位中包含的資訊，這些資訊有助於自動完成 query. Amazon Kendra look 以取得設定為 `Suggestable`且與使用者查詢密切相符的相關內容。然後， Amazon Kendra 當使用者開始輸入查詢時，建議他們使用此內容。

例如，如果您指定要作為建議基礎的標題欄位，而使用者開始輸入查詢 'How amazon ken...'，則可能會建議最相關的標題 'How Amazon Kendra works' 自動完成搜尋。使用者看到「如何 Amazon Kendra 運作」直接出現在搜尋列下方，自動完成搜尋查詢。使用者選取此查詢建議，並在搜尋結果中傳回文件「如何 Amazon Kendra 運作」。

您可以使用 `String`和 `StringList`類型的任何文件欄位內容來建議查詢，方法是將欄位設定為 ，`Suggestable`做為查詢建議的欄位組態的一部分。您也可以使用[封鎖清單](https://docs.aws.amazon.com/kendra/latest/dg/query-suggestions.html#query-suggestions-blocklist)，讓包含特定單字或片語的建議文件欄位不會向您的使用者顯示。您可以使用一個區塊清單。無論您將查詢建議設定為使用查詢歷史記錄或文件欄位，都會套用封鎖清單。

### 選取建議欄位的設定
<a name="query-suggestions-doc-fields-settings"></a>

您可以使用 設定下列設定，以選取建議的文件欄位，[https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeSuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeSuggestionsConfig.html)並呼叫 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsConfig.html) API 在索引層級更新設定：
+ **欄位/屬性建議模式** - 使用文件欄位的查詢建議為 `ACTIVE`或 `INACTIVE`。 Amazon Kendra 預設會啟用查詢建議。
+ **建議欄位/屬性** - 要作為建議基礎的欄位名稱或欄位索引鍵。這些欄位必須設定為`TRUE`適用於 `Suggestable`，作為欄位組態的一部分。您可以在查詢層級覆寫欄位組態，同時在索引層級維護組態。使用 [GetQuerySuggestions](https://docs.aws.amazon.com/kendra/latest/APIReference/API_GetQuerySuggestions.html) API 在查詢層級`AttributeSuggestionConfig`進行變更。查詢層級的此組態對於快速實驗使用不同文件欄位非常有用，而無需在索引層級更新組態。
+ **其他欄位/屬性** - 您要包含在查詢建議回應中的其他欄位。這些欄位用於在回應中提供額外資訊；但是，它們不會用來作為建議的基礎。

**警告**  
您對設定所做的變更可能不會立即生效。您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsConfig.html) API 追蹤設定變更。更新設定生效的時間取決於您所做的更新。變更設定後或套用[封鎖清單](https://docs.aws.amazon.com/kendra/latest/dg/query-suggestions.html#query-suggestions-blocklist)後， 會每 24 小時 Amazon Kendra 自動更新建議。

------
#### [ CLI ]

若要擷取查詢建議並覆寫查詢層級的文件欄位組態，而不必變更索引層級的組態。

```
aws kendra get-query-suggestions \
 --index-id index-id \
 --query-text "query-text" \
 --suggestion-types '["DOCUMENT_ATTRIBUTES"]' \
 --attribute-suggestions-config '{"SuggestionAttributes":'["field/attribute key 1", "field/attribute key 2"]', "AdditionalResponseAttributes":'["response field/attribute key 1", "response field/attribute key 2"]'}' \
 --max-suggestions-count 1 // If you want to limit the number of suggestions
```

**更新查詢建議**

例如，若要變更索引層級的文件欄位組態：

```
aws kendra update-query-suggestions-config \
 --index-id index-id \
 --attribute-suggestions-config '{"SuggestableConfigList": '[{"SuggestableConfig": "_document_title", "Suggestable": true}]', "AttributeSuggestionsMode": "ACTIVE"}'
```

------
#### [ Python ]

若要擷取查詢建議並覆寫查詢層級的文件欄位組態，而不必變更索引層級的組態。

```
import boto3
from botocore.exceptions import ClientError

kendra = boto3.client("kendra")

print("Get query suggestions.")

# Provide the index ID
index_id = "index-id"

# Provide the query text
query_text = "query"

# Provide the query suggestions type
query_suggestions_type = "DOCUMENT_ATTRIBUTES"

# Override fields/attributes configuration at query level
configuration = {"SuggestionAttributes":
    '["field/attribute key 1", "field/attribute key 2"]', 
      "AdditionalResponseAttributes":
          '["response field/attribute key 1", "response field/attribute key 2"]'
          }

# If you want to limit the number of suggestions
num_suggestions = 1

try:
    query_suggestions_response = kendra.get_query_suggestions(
        IndexId = index_id,
        QueryText = query_text,
        SuggestionTypes = [query_suggestions_type],
        AttributeSuggestionsConfig = configuration,
        MaxSuggestionsCount = num_suggestions
    )

    # Print out the suggestions you received
    if ("Suggestions" in query_suggestions_response.keys()) {
        for (suggestion: query_suggestions_response["Suggestions"]) {
            print(suggestion["Value"]["Text"]["Text"]);
        }
    }
   
except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

**更新查詢建議**

例如，若要變更索引層級的文件欄位組態：

```
import boto3
from botocore.exceptions import ClientError
import pprint
import time

kendra = boto3.client("kendra")

print("Updating query suggestions settings/configuration for an index.")

# Provide the index ID
index_id = "index-id"

# Configure the settings you want to update at the index level
configuration = {"SuggestableConfigList": 
    '[{"SuggestableConfig": "_document_title", "Suggestable": true}]', 
       "AttributeSuggestionsMode": "ACTIVE"
       }

try:
    kendra.update_query_suggestions_config(
        IndexId = index_id,
        AttributeSuggestionsConfig = configuration
    )

    print("Wait for Amazon Kendra to update the query suggestions.")

    while True:
        # Get query suggestions description of settings/configuration
        query_sugg_config_response = kendra.describe_query_suggestions_config(
            IndexId = index_id
        )
        
        # If status is not UPDATING, then quit
        status = query_sugg_config_response["Status"]
        print(" Updating query suggestions config. Status: " + status)
        if status != "UPDATING":
            break
        time.sleep(60)

except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

------

### 文件欄位中的使用者控制
<a name="query-suggestions-doc-fields-user-control"></a>

您可以將使用者內容篩選套用至要作為查詢建議基礎的文件欄位。此篩選條件會根據使用者或其群組對文件的存取來篩選文件欄位資訊。例如， 端點會搜尋公司的入口網站，而且無法存取最機密的公司文件。因此，根據最機密文件的標題或任何其他建議欄位的建議查詢，不會向整數顯示。

您可以使用存取控制清單 (ACL) 為文件編製索引，定義哪些使用者和群組被指派存取哪些文件。然後，您可以將使用者內容篩選套用至文件欄位，以取得查詢建議。目前為您的索引設定的使用者內容篩選，與套用至文件欄位組態的查詢建議相同的使用者內容篩選。使用者內容篩選是文件欄位組態的一部分。您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeSuggestionsConfig.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeSuggestionsConfig.html)並呼叫 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_GetQuerySuggestions.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_GetQuerySuggestions.html)。

## 從建議中封鎖特定查詢或文件欄位內容
<a name="query-suggestions-blocklist"></a>

*封鎖清單* Amazon Kendra 會停止向您的使用者建議特定查詢。封鎖清單是您要從查詢建議中排除的單字或片語清單。 Amazon Kendra 排除包含完全符合封鎖清單中單字或片語的查詢。

您可以使用封鎖清單來防止攻擊性單字或片語，這些單字或片語通常出現在您的查詢歷史記錄或文件欄位中， Amazon Kendra 並且可以選取 做為建議。封鎖清單也可以 Amazon Kendra 防止 建議包含尚未準備好公開發佈或宣布之資訊的查詢。例如，您的使用者經常查詢潛在新產品即將發行的版本。不過，您不想建議產品，因為您尚未準備好發佈。您可以從建議封鎖包含產品名稱和產品資訊的查詢。

您可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateQuerySuggestionsBlockList.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateQuerySuggestionsBlockList.html) API 建立查詢的封鎖清單。您可以將每個區塊字或片語放在文字檔案中的個別行上。然後，您將文字檔案上傳至 Amazon S3 儲存貯體，並提供檔案的路徑或位置 Amazon S3 in. Amazon Kendra currently 僅支援建立一個封鎖清單。

您可以取代儲存 Amazon S3 貯體中已封鎖單字和片語的文字檔案。若要更新 中的封鎖清單 Amazon Kendra，請使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsBlockList.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateQuerySuggestionsBlockList.html) API。

使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsBlockList.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DescribeQuerySuggestionsBlockList.html) API 取得封鎖清單的狀態。 `DescribeQuerySuggestionsBlockList`也可以為您提供其他有用的資訊，例如：
+ 您的封鎖清單上次更新的時間
+ 您目前的封鎖清單中有多少個單字或片語
+ 建立封鎖清單時的實用錯誤訊息

您也可以使用 [https://docs.aws.amazon.com/kendra/latest/APIReference/API_ListQuerySuggestionsBlockLists.html](https://docs.aws.amazon.com/kendra/latest/APIReference/API_ListQuerySuggestionsBlockLists.html) API 來取得索引的封鎖清單摘要清單。

若要刪除封鎖清單，請使用 [DeleteQuerySuggestionsBlockList](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DeleteQuerySuggestionsBlockList.html) API。

您對封鎖清單的更新可能不會立即生效。您可以使用 `DescribeQuerySuggestionsBlockList` API 追蹤更新。

------
#### [ CLI ]

**建立封鎖清單**

```
aws kendra create-query-suggestions-block-list \
 --index-id index-id \
 --name "block-list-name" \
 --description "block-list-description" \
 --source-s3-path "Bucket=bucket-name,Key=query-suggestions/block_list.txt" \
 --role-arn role-arn
```

**更新封鎖清單**

```
aws kendra update-query-suggestions-block-list \
 --index-id index-id \
 --name "new-block-list-name" \
 --description "new-block-list-description" \
 --source-s3-path "Bucket=bucket-name,Key=query-suggestions/new_block_list.txt" \
 --role-arn role-arn
```

**刪除封鎖清單**

```
aws kendra delete-query-suggestions-block-list \
 --index-id index-id \
 --id block-list-id
```

------
#### [ Python ]

**建立封鎖清單**

```
import boto3
from botocore.exceptions import ClientError
import pprint
import time

kendra = boto3.client("kendra")

print("Create a query suggestions block list.")

# Provide a name for the block list
block_list_name = "block-list-name"
# Provide an optional description for the block list
block_list_description = "block-list-description"
# Provide the IAM role ARN required for query suggestions block lists
block_list_role_arn = "role-arn"

# Provide the index ID
index_id = "index-id"

s3_bucket_name = "bucket-name"
s3_key = "query-suggestions/block_list.txt"
source_s3_path = {
    'Bucket': s3_bucket_name,
    'Key': s3_key
}

try:
    block_list_response = kendra.create_query_suggestions_block_list(
        Description = block_list_description,
        Name = block_list_name,
        RoleArn = block_list_role_arn,
        IndexId = index_id,
        SourceS3Path = source_s3_path
    )

    print(block_list_response)

    block_list_id = block_list_response["Id"]

    print("Wait for Amazon Kendra to create the block list.")

    while True:
        # Get block list description
        block_list_description = kendra.describe_query_suggestions_block_list(
            Id = block_list_id,
            IndexId = index_id
        )
        # If status is not CREATING, then quit
        status = block_list_description["Status"]
        print("Creating block list. Status: " + status)
        if status != "CREATING":
            break
        time.sleep(60)
        
except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

**更新封鎖清單**

```
import boto3
from botocore.exceptions import ClientError
import pprint
import time
                        
kendra = boto3.client("kendra")
                        
print("Update a block list for query suggestions.")

# Provide the block list name you want to update
block_list_name = "new-block-list-name"
# Provide the block list description you want to update
block_list_description = "new-block-list-description"
# Provide the IAM role ARN required for query suggestions block lists
block_list_role_arn = "role-arn"

# Provide the block list ID
block_list_id = "block-list-id"
# Provide the index ID
index_id = "index-id"
                        
s3_bucket_name = "bucket-name"
s3_key = "query-suggestions/new_block_list.txt"
source_s3_path = {
'Bucket': s3_bucket_name,
'Key': s3_key
}
                        
try:
    kendra.update_query_suggestions_block_list(
        Id = block_list_id,
        IndexId = index_id,
        Description = block_list_description,
        Name = block_list_name,
        RoleArn = block_list_role_arn,
        SourceS3Path = source_s3_path
    )
                        
    print("Wait for Amazon Kendra to update the block list.")
                        
    while True:
        # Get block list description
        block_list_description = kendra.describe_query_suggestions_block_list(
            Id = block_list_id,
            IndexId = index_id
        )
        # If status is not UPDATING, then the update has finished 
        status = block_list_description["Status"]
        print("Updating block list. Status: " + status)
        if status != "UPDATING":
            break
        time.sleep(60)
                        
except ClientError as e:
print("%s" % e)
                        
print("Program ends.")
```

**刪除封鎖清單**

```
import boto3
from botocore.exceptions import ClientError

kendra = boto3.client("kendra")

print("Delete a block list for query suggestions.")

# provide the block list ID
query_suggestions_block_list_id = "query-suggestions-block-list-id"
# Provide the index ID
index_id = "index-id"

try:
    kendra.delete_query_suggestions_block_list(
        Id = query_suggestions_block_list_id,
        IndexId = index_id
    )

except ClientError as e:
        print("%s" % e)

print("Program ends.")
```

------

# 查詢拼字檢查程式
<a name="query-spell-check"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

Amazon Kendra *拼寫檢查程式*建議對查詢進行拼寫更正。這可協助您將零搜尋結果的出現次數降至最低，並傳回相關結果。您的使用者可能會在沒有相符[結果或沒有傳回文件的拼寫錯誤查詢中收到零個搜尋結果](https://docs.aws.amazon.com/kendra/latest/dg/search-analytics.html#search-analytics-metrics)。或者，您的使用者可能會從拼寫錯誤的查詢中收到[不相關的搜尋結果](https://docs.aws.amazon.com/kendra/latest/dg/search-analytics.html#search-analytics-metrics)。

拼寫檢查程式旨在根據索引文件中出現的單字以及更正後的單字符合拼寫錯誤單字的程度，建議更正拼寫錯誤單字。例如，如果 'statements' 一詞出現在您的索引文件中，則這可能會與查詢 'year-end financial statments' 中的拼寫錯誤單詞 'statments' 緊密相符。

拼寫檢查程式會傳回預期或修正的單字，以取代原始查詢文字中的拼寫錯誤單字。例如，'depoing kendre search' 可能會傳回 'deploying Kendra search' 您也可以使用 API 中提供的位移位置，在前端應用程式中的查詢中反白或斜體化傳回的更正字詞。在主控台中，已更正的單字預設會反白顯示或斜體。例如，「*部署* *Kendra* 搜尋」。

對於索引文件中出現的業務特定或專業術語，Spell Checker 不會誤認為查詢中的拼字錯誤。例如，'amazon macie' 不會更正為 'amazon mace'。

對於連字號，例如 'year-end'，Spell Checker 會將這些單字視為個別單字，以建議更正這些單字。例如，「yaer-end」的建議更正可以是「year-end」。

對於 `DOCUMENT`和 `QUESTION_ANSWER`查詢回應類型，拼字檢查程式會根據文件內文中的單字，建議更正拼寫錯誤的單字。文件內文比建議最符合拼寫錯誤單字的更正標題更可靠。對於`ANSWER`查詢回應類型，拼寫檢查程式會根據索引中預設問題和答案文件中的單字來建議更正。

您可以使用 [SpellCorrectionConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_SpellCorrectionConfiguration.html) 物件來啟用 Spell Checker。您將 `IncludeQuerySpellCheckSuggestions`設定為 `TRUE`。根據預設，拼字檢查程式會在主控台中啟用。根據預設，它會內建在 主控台中。

拼字檢查程式也可以建議對多種語言的查詢進行拼字修正，而不只是英文。如需 Spell Checker 支援的語言清單，請參閱[Amazon Kendra 支援的語言](https://docs.aws.amazon.com/kendra/latest/dg/in-adding-languages.html)。

## 使用具有預設限制的查詢拼字檢查程式
<a name="query-spell-check-defaults"></a>

拼寫檢查程式的設計具有特定預設值或限制。以下是啟用拼字修正建議時適用的目前限制清單。
+ 對於長度少於三個字元或超過 30 個字元的單字，無法傳回建議的拼字修正。若要允許超過 30 個字元或少於 3 個字元，請聯絡 [Support](https://aws.amazon.com/contact-us/)。
+ 建議的拼字修正無法根據使用者存取控制或存取控制清單來限制建議，以進行[使用者內容篩選](https://docs.aws.amazon.com/kendra/latest/dg/user-context-filter.html)。拼寫更正是根據索引文件中的所有單字，無論單字是否僅限於特定使用者。如果您想要避免某些單字出現在建議的查詢拼字修正中，請不要啟用 `SpellCorrectionConfiguration`。
+ 對於包含數字的單字，無法傳回建議的拼字修正。例如，'how 2 not br8k ubun2'。
+ 建議的拼字修正無法使用索引文件中未出現的單字。
+ 建議的拼字修正不能使用索引文件中頻率低於 0.01% 的單字。若要變更 0.01% 閾值，請聯絡 [Support](https://aws.amazon.com/contact-us/)。

# 篩選和面向搜尋
<a name="filtering"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

您可以使用篩選條件來改善[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 的搜尋結果或回應。篩選條件會將回應中的文件限制為直接套用至查詢的文件。若要建立面向搜尋建議，請使用布林邏輯，從回應或不符合特定條件的文件篩選出特定文件屬性。您可以使用 `Query` API 中的 `Facets` 參數來指定面向。

若要搜尋您已編製索引的文件 Amazon Lex，請使用 AMAZON Amazon Kendra .KendraSearchIntent。 [KendraSearchIntent](https://docs.aws.amazon.com/lexv2/latest/APIReference/API_KendraConfiguration.html) 如需使用 設定 Amazon Kendra 的範例 Amazon Lex，請參閱[為 Amazon Kendra 索引建立常見問答集機器人](https://docs.aws.amazon.com/lexv2/latest/dg/faq-bot-kendra-search.html)。您也可以使用 [AttributeFilter](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeFilter.html) 提供回應的篩選條件。這是設定 時 JSON 中的查詢篩選條件`AMAZON.KendraSearchIntent`。若要在主控台中設定搜尋意圖時提供屬性篩選條件，請前往意圖編輯器，然後選擇 Amazon Kendra 查詢以在 JSON 中提供查詢篩選條件。如需 的詳細資訊`AMAZON.KendraSearchIntent`，請參閱 [Amazon Lex 文件指南](https://docs.aws.amazon.com/lexv2/latest/dg/built-in-intent-kendra-search.html)。

## 面向
<a name="search-facets"></a>

面向是一組搜尋結果的範圍檢視。例如，您可以提供全球城市的搜尋結果，其中文件會依與其相關聯的特定城市進行篩選。或者，您可以建立面向來顯示特定作者的結果。

您可以使用與文件相關聯的文件屬性或中繼資料欄位做為構面，讓使用者可以依該構面內的類別或值進行搜尋。您也可以在搜尋結果中顯示巢狀面向，讓使用者不僅可以依類別或欄位進行搜尋，還可以依子類別或子欄位進行搜尋。

下列範例顯示如何取得「城市」自訂屬性的面向資訊。

```
response=kendra.query(
        QueryText = query,
        IndexId = index,
        Facets = [
            {
                "DocumentAttributeKey" : "City"
            }
        ]
        )
```

您可以使用巢狀面向來進一步縮小搜尋範圍。例如，文件屬性或構面 "City" 包含稱為 "Seattle" 的值。此外，文件屬性或構面 "CityRegion" 包含指派給 "Seattle" 的文件值 "North" 和 "South"。您可以在搜尋結果中顯示巢狀面向及其計數，以便不僅可以依城市搜尋文件，還可以依城市內的區域搜尋文件。

請注意，巢狀面向可能會影響查詢延遲。一般規則是您使用的更巢狀構面，對延遲的潛在影響更大。影響延遲的其他因素包括編製索引的文件平均大小、索引大小、高度複雜的查詢，以及索引的整體負載 Amazon Kendra 。

下列範例顯示如何取得 "CityRegion" 自訂屬性的構面資訊，做為 "City" 內的巢狀構面。

```
response=kendra.query(
        QueryText = query,
        IndexId = index,
        Facets = [
            {
                "DocumentAttributeKey" : "City",
                "Facets": [
                    {
                        "DocumentAttributeKey" : "CityRegion"
                    }
                ]
            }
        ]
        )
```

`FacetResults` 回應陣列中會傳回面向資訊，例如文件計數。您可以使用內容在應用程式中顯示面向搜尋建議。例如，如果文件屬性 "City" 包含可套用搜尋的城市，請使用該資訊顯示城市搜尋清單。使用者可以選擇城市來篩選搜尋結果。若要進行面向搜尋，請呼叫[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API，並使用選擇的文件屬性來篩選結果。

對於查詢，每個構面最多可以顯示 10 個構面值，而構面內只能顯示一個巢狀構面。如果您想要提高這些限制，請聯絡 [Support](https://aws.amazon.com/contact-us/)。如果您想要將每個構面的構面值數限制為小於 10，您可以在 `Facet` 物件中指定此值。

下列範例 JSON 回應顯示範圍為「城市」文件屬性的面向。回應包含面向值的文件計數。

```
{
    'FacetResults': [
        {
            'DocumentAttributeKey': 'City',
            'DocumentAttributeValueCountPairs': [
                {
                    'Count': 3,
                    'DocumentAttributeValue': {
                        'StringValue': 'Dubai'
                    }
                },
                {
                    'Count': 3,
                    'DocumentAttributeValue': {
                        'StringValue': 'Seattle'
                    }
                },
                {
                    'Count': 1,
                    'DocumentAttributeValue': {
                        'StringValue': 'Paris'
                    }
                }
            ]
        }
    ]
```

您也可以顯示巢狀構面的構面資訊，例如城市內的區域，以進一步篩選搜尋結果。

下列範例 JSON 回應顯示範圍為 "CityRegion" 文件屬性的構面，做為 "City" 內的巢狀構面。回應包含巢狀構面值的文件計數。

```
{
    'FacetResults': [
        {
            'DocumentAttributeKey': 'City',
            'DocumentAttributeValueCountPairs': [
                {
                    'Count': 3,
                    'DocumentAttributeValue': {
                        'StringValue': 'Dubai'
                    },
                    'FacetResults': [
                        {
                            'DocumentAttributeKey': 'CityRegion',
                            'DocumentAttributeValueCountPairs': [
                                 {
                                     'Count': 2,
                                     'DocumentAttributeValue': {
                                         'StringValue': 'Bur Dubai'
                                     }
                                 },
                                 {
                                     'Count': 1,
                                     'DocumentAttributeValue': {
                                         'StringValue': 'Deira'
                                     }
                                 }
                             ]
                        }
                    ]
                },
                {
                    'Count': 3,
                    'DocumentAttributeValue': {
                        'StringValue': 'Seattle'
                    },
                    'FacetResults': [
                        {
                            'DocumentAttributeKey': 'CityRegion',
                            'DocumentAttributeValueCountPairs': [
                                 {
                                     'Count': 1,
                                     'DocumentAttributeValue': {
                                         'StringValue': 'North'
                                     }
                                 },
                                 {
                                     'Count': 2,
                                     'DocumentAttributeValue': {
                                         'StringValue': 'South'
                                     }
                                 }
                             ]
                        }
                    ]
                },
                {
                    'Count': 1,
                    'DocumentAttributeValue': {
                        'StringValue': 'Paris'
                    },
                    'FacetResults': [
                        {
                            'DocumentAttributeKey': 'CityRegion',
                            'DocumentAttributeValueCountPairs': [
                                 {
                                     'Count': 1,
                                     'DocumentAttributeValue': {
                                         'StringValue': 'City center'
                                     }
                                 }
                             ]
                        }
                    ]
                }
        }
    ]
}
```

當您使用字串清單欄位建立面向時，傳回的面向結果會根據字串清單的內容。例如，如果您有一個包含兩個項目的字串清單欄位，一個具有「dachshund」清單、「sausage dog」清單，另一個具有「husky」值，您會`FacetResults`得到三個面向。

如需詳細資訊，請參閱[查詢回應和回應類型](query-responses-types.md)。

## 使用文件屬性篩選搜尋結果
<a name="search-filtering"></a>

根據預設， `Query`會傳回所有搜尋結果。若要篩選回應，您可以對文件屬性執行邏輯操作。例如，如果您只想要特定城市的文件，您可以篩選「城市」和「州」自訂文件屬性。您可以使用 [AttributeFilter](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeFilter.html) 在您提供的篩選條件上建立布林值操作。

大多數屬性可用來篩選所有回應[類型的回應](https://docs.aws.amazon.com/kendra/latest/dg/query-responses-types.html)。不過， `_excerpt_page_number` 屬性僅適用於篩選`ANSWER`回應時的回應類型。

下列範例顯示如何篩選特定城市、*西雅圖*和華盛頓州，以執行邏輯 AND 操作**。

```
response=kendra.query(
        QueryText = query,
        IndexId = index,
        AttributeFilter = {'AndAllFilters': 
            [ 
                {"EqualsTo": {"Key": "City","Value": {"StringValue": "Seattle"}}},
                {"EqualsTo": {"Key": "State","Value": {"StringValue": "Washington"}}}
            ]
            }
        )
```

下列範例顯示當任何 `Fileformat`、 `Author`或 `SourceURI`金鑰符合指定的值時，如何執行 的邏輯 OR 操作。

```
response=kendra.query(
        QueryText = query,
        IndexId = index,
        AttributeFilter = {'OrAllFilters': 
            [ 
                {"EqualsTo": {"Key": "Fileformat","Value": {"StringValue": "AUTO_DETECT"}}},
                {"EqualsTo": {"Key": "Author","Value": {"StringValue": "Ana Carolina"}}},
                {"EqualsTo": {"Key": "SourceURI","Value": {"StringValue": "https://aws.amazonaws.com/234234242342"}}}
            ]
            }
        )
```

對於 `StringList` 欄位，請使用 `ContainsAny`或 `ContainsAll` 屬性篩選條件來傳回具有指定字串的文件。下列範例顯示如何傳回其`Locations`自訂屬性中值為 "Seattle" 或 "Portland" 的所有文件。

```
response=kendra.query(
        QueryText = query,
        IndexId = index,
        AttributeFilter = {
                "ContainsAny": { "Key": "Locations", "Value": { "StringListValue": [ "Seattle", "Portland"] }}
            }
        )
```

## 在搜尋結果中篩選每個文件的屬性
<a name="filtering-document-attributes"></a>

Amazon Kendra 會傳回搜尋結果中每個文件的文件屬性。您可以篩選要包含在回應中的特定文件屬性，做為搜尋結果的一部分。根據預設，指派給文件的所有文件屬性都會在回應中傳回。

在下列範例中，只有 `_source_uri`和 `_author` 文件屬性包含在 文件的回應中。

```
response=kendra.query(
        QueryText = query,
        IndexId = index,
        RequestedDocumentAttributes = ["_source_uri", "_author"]
        )
```

# 篩選使用者內容
<a name="user-context-filter"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

您可以根據使用者或其群組對文件的存取來篩選使用者的搜尋結果。您可以使用使用者字符、使用者 ID 或使用者屬性來篩選文件。

使用者內容篩選是一種個人化搜尋，可控制對文件的存取。例如，並非所有搜尋公司入口網站資訊的團隊都應該存取最機密的公司文件，這些文件也與所有使用者無關。只有獲得最高機密文件存取權的特定使用者或團隊群組，才能在其搜尋結果中看到這些文件。

將文件編製索引時 Amazon Kendra，會擷取大多數文件對應的存取控制清單 (ACL)。ACL 指定允許或拒絕存取文件的使用者名稱和群組名稱。沒有 ACL 的文件是公有文件。

Amazon Kendra 可以擷取與大多數資料來源的每個文件相關聯的使用者或群組資訊。例如，Quip 中的文件可以包含特定使用者的「共用」清單，這些使用者有權存取文件。如果您使用 S3 儲存貯體做為資料來源，您可以為 ACL 提供 [JSON 檔案](https://docs.aws.amazon.com/kendra/latest/dg/s3-acl.html)，並包含此檔案的 S3 路徑做為資料來源組態的一部分。如果您直接將文件新增至索引，您可以在 [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument.html) API 中將[主體](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Principal.html)物件中的 ACL 指定為文件物件的一部分。

如果您使用的是 Amazon Kendra Enterprise 或 Developer Edition 索引，您可以使用 [CreateAccessControlConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateAccessControlConfiguration.html) API 重新設定現有的文件層級存取控制，而無需再次編製所有文件的索引。例如，您的索引包含只有特定員工或使用者應存取的最機密公司文件。其中一個使用者離開公司或切換到應該封鎖存取最高機密文件的團隊。使用者仍然可以存取最機密的文件，因為使用者在先前編製文件索引時可以存取。您可以為拒絕存取的使用者建立特定的存取控制組態。您可以稍後更新存取控制組態，以便在使用者返回公司並重新加入「最高機密」團隊時允許存取。您可以在情況變更時重新設定文件的存取控制。

若要將您的存取控制組態套用至特定文件，您可以呼叫 [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument.html) API，其中包含 [文件](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Document.html)物件`AccessControlConfigurationId`中的 。如果您使用 S3 儲存貯體做為資料來源，您可以使用 更新 `.metadata.json` `AccessControlConfigurationId`並同步資料來源。 Amazon Kendra 目前僅支援使用 `BatchPutDocument` API 編製索引之 S3 資料來源和文件的存取控制組態。

## 依使用者字符篩選
<a name="context-filter-token"></a>

**重要**  
Amazon Kendra GenAI Enterprise Edition 索引不支援字符型使用者存取控制。

當您查詢索引時，您可以使用使用者字符，根據使用者或其群組對文件的存取來篩選搜尋結果。當您發出查詢時， 會 Amazon Kendra 擷取並驗證權杖、提取和檢查使用者和群組資訊，並執行查詢。系統會傳回使用者可存取的所有文件，包括公有文件。如需詳細資訊，請參閱以[字符為基礎的使用者存取控制](https://docs.aws.amazon.com/kendra/latest/dg/create-index-access-control.html)。

您可以在 [UserContext](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UserContext.html) 物件中提供使用者權杖，並在[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 中傳遞此權杖。

以下說明如何包含使用者字符。

```
response = kendra.query(
    QueryText = query,
    IndexId = index,
    UserToken = {
        Token = "token"
    })
```

您可以將使用者映射至 群組。當您使用使用者內容篩選時，不需要在您發出查詢時包含使用者所屬的所有群組。使用 [PutPrincipalMapping](https://docs.aws.amazon.com/kendra/latest/APIReference/API_PutPrincipalMapping.html) API，您可以將使用者映射至其群組。如果您不想使用 `PutPrincipalMapping` API，則必須在發出查詢時提供使用者名稱和使用者所屬的所有群組。您也可以使用 [UserGroupResolutionConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UserGroupResolutionConfiguration.html) 物件，擷取 IAM Identity Center 身分來源中群組和使用者的存取層級。

## 依使用者 ID 和群組篩選
<a name="context-filter-user-incl-datasources"></a>

當您查詢索引時，您可以使用使用者 ID 和群組，根據使用者或其群組對文件的存取來篩選搜尋結果。當您發出查詢時， 會 Amazon Kendra 檢查使用者和群組資訊並執行查詢。系統會傳回與使用者可存取之查詢相關的所有文件，包括公有文件。

您也可以依使用者和群組可存取的資料來源來篩選搜尋結果。如果群組繫結至多個資料來源，但您只希望該群組存取特定資料來源的文件，則指定資料來源非常有用。例如，群組 "Research"、"Engineering" 和 "Sales and Marketing" 都與存放在 Confluence 和 Salesforce 資料來源中的公司文件相關聯。不過，「銷售和行銷」團隊只需要存取儲存在 Salesforce 中的客戶相關文件。因此，當銷售和行銷使用者搜尋客戶相關文件時，他們可以在結果中看到 Salesforce 的文件。不在銷售和行銷部門工作的使用者在搜尋結果中看不到 Salesforce 文件。

您可以在 [UserContext](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UserContext.html) 物件中提供使用者、群組和資料來源資訊，並在[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 中傳遞此資訊。使用者 ID 和群組和資料來源清單應與您在[主體](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Principal.html)物件中指定的名稱相符，以識別使用者、群組和資料來源。使用 `Principal` 物件，您可以將使用者、群組或資料來源新增至允許清單或拒絕清單，以存取文件。

您必須提供下列其中一項：
+ 使用者和群組資訊，以及 （選用） 資料來源資訊。
+ 只有在您使用 [PutPrincipalMapping](https://docs.aws.amazon.com/kendra/latest/APIReference/API_PutPrincipalMapping.html) API 將使用者映射到群組和資料來源時，才需要使用者資訊。您也可以使用 [UserGroupResolutionConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UserGroupResolutionConfiguration.html) 物件，擷取 IAM Identity Center 身分來源中群組和使用者的存取層級。

如果此資訊不包含在查詢中， 會 Amazon Kendra 傳回所有文件。如果您提供此資訊，則只會傳回具有相符使用者 IDs、群組和資料來源的文件。

以下說明如何包含使用者 ID、群組和資料來源。

```
response = kendra.query(
    QueryText = query,
    IndexId = index,
    UserContext={'Token': 'string', 'UserId': 'string', 'Groups': [ 'string', ], 'DataSourceGroups': [ { 'GroupId': 'string', 'DataSourceId': 'string' }, ] },)
```

## 依使用者屬性篩選
<a name="context-filter-attribute"></a>

當您查詢索引時，您可以使用內建屬性 `_user_id`和 `_group_id`，根據使用者及其群組對 文件的存取來篩選搜尋結果。您最多可以設定 100 個群組識別符。當您發出查詢時， 會 Amazon Kendra 檢查使用者和群組資訊並執行查詢。系統會傳回與使用者可存取之查詢相關的所有文件，包括公有文件。

您可以在 [AttributeFilter](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AttributeFilter.html) 物件中提供使用者和群組屬性，並在[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 中傳遞此屬性。

下列範例顯示根據使用者 ID 和使用者所屬的群組 "HR" 和 "IT" 篩選查詢回應的請求。查詢將傳回允許清單中具有使用者或 "HR" 或 "IT" 群組的任何文件。如果使用者或任一群組在文件的拒絕清單中，則不會傳回文件。

```
response = kendra.query(
        QueryText = query,
        IndexId = index,
        AttributeFilter = {
            "OrAllFilters": [
                {
                    "EqualsTo": {
                        "Key": "_user_id",
                        "Value": {
                            "StringValue": "user1"
                        }
                     }
                },
                {
                    "EqualsTo": {
                        "Key": "_group_ids",
                        "Value": {
                            "StringListValue": ["HR", "IT"]
                        }
                    }
                }
            ]
        }
        )
```

您也可以指定群組可以在 `Principal` 物件中存取的資料來源。

**注意**  
使用者內容篩選不是您內容的身分驗證或授權控制。它不會對傳送至 `Query` API 的使用者和群組執行使用者身分驗證。它取決於您的應用程式，以確保傳送至 `Query` API 的使用者和群組資訊已經過身分驗證和授權。

每個資料來源都有使用者內容篩選的實作。下節說明每個實作。

**Topics**
+ [依使用者字符篩選](#context-filter-token)
+ [依使用者 ID 和群組篩選](#context-filter-user-incl-datasources)
+ [依使用者屬性篩選](#context-filter-attribute)
+ [直接新增至索引之文件的使用者內容篩選](#context-filter-batch)
+ [常見問答集的使用者內容篩選](#context-filter-faq)
+ [資料來源的使用者內容篩選](#datasource-context-filter)

## 直接新增至索引之文件的使用者內容篩選
<a name="context-filter-batch"></a>

當您使用 [BatchPutDocument](https://docs.aws.amazon.com/kendra/latest/APIReference/API_BatchPutDocument.html) API 將文件直接新增至索引時， 會從文件的 `AccessControlList` 欄位 Amazon Kendra 取得使用者和群組資訊。您可以為您的文件提供存取控制清單 (ACL)，並將 ACL 擷取到您的文件。

您可以在[主體](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Principal.html)物件中指定 ACL，做為 `BatchPutDocument` API 中[文件](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Document.html)物件的一部分。您提供以下資訊：
+ 使用者或群組應擁有的存取權。您可以說出 `ALLOW`或 `DENY`。
+ 實體類型。您可以說出 `USER`或 `GROUP`。
+ 使用者或群組的名稱。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

## 常見問答集的使用者內容篩選
<a name="context-filter-faq"></a>

當您[將常見問答集](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateFaq.html)新增至索引時， 會從常見問答集 JSON 檔案的`AccessControlList`物件/欄位 Amazon Kendra 取得使用者和群組資訊。您也可以使用具有自訂欄位或屬性的常見問答集 CSV 檔案進行存取控制。

您提供以下資訊：
+ 使用者或群組應擁有的存取權。您可以說出 `ALLOW`或 `DENY`。
+ 實體類型。您可以說出 `USER`或 `GROUP`。
+ 使用者或群組的名稱。

如需詳細資訊，請參閱[常見問答集檔案](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html)。

## 資料來源的使用者內容篩選
<a name="datasource-context-filter"></a>

Amazon Kendra 也會從支援的資料來源連接器爬取使用者和群組存取控制清單 (ACL) 資訊。這對於使用者內容篩選很有用，其中搜尋結果會根據使用者或其群組對文件的存取進行篩選。

**重要**  
Amazon Kendra GenAI Enterprise Edition 索引僅支援 v2.0 Amazon Kendra 資料來源連接器。

**Topics**
+ [Adobe Experience Manager 資料來源的使用者內容篩選](#context-filter-aem)
+ [Alfresco 資料來源的使用者內容篩選](#context-filter-alfresco)
+ [Aurora (MySQL) 資料來源的使用者內容篩選](#context-filter-aurora-mysql)
+ [Aurora (PostgreSQL) 資料來源的使用者內容篩選](#context-filter-aurora-postgresql)
+ [Amazon FSx 資料來源的使用者內容篩選](#context-filter-fsx)
+ [資料庫資料來源的使用者內容篩選](#context-filter-jdbc)
+ [Amazon RDS (Microsoft SQL Server) 資料來源的使用者內容篩選](#context-filter-rds-ms-sql-server)
+ [Amazon RDS (MySQL) 資料來源的使用者內容篩選](#context-filter-rds-mysql)
+ [Amazon RDS (Oracle) 資料來源的使用者內容篩選](#context-filter-rds-oracle)
+ [Amazon RDS (PostgreSQL) 資料來源的使用者內容篩選](#context-filter-rds-postgresql)
+ [Amazon S3 資料來源的使用者內容篩選](#context-filter-s3)
+ [Box 資料來源的使用者內容篩選](#context-filter-box)
+ [Confluence 資料來源的使用者內容篩選](#context-filter-confluence)
+ [Dropbox 資料來源的使用者內容篩選](#context-filter-dropbox)
+ [Drupal 資料來源的使用者內容篩選](#context-filter-drupal)
+ [GitHub 資料來源的使用者內容篩選](#context-filter-github)
+ [Gmail 資料來源的使用者內容篩選](#context-filter-gmail)
+ [Google Drive 資料來源的使用者內容篩選](#context-filter-google)
+ [IBM DB2 資料來源的使用者內容篩選](#context-filter-ibm-db2)
+ [Jira 資料來源的使用者內容篩選](#context-filter-jira)
+ [Microsoft Exchange 資料來源的使用者內容篩選](#context-filter-exchange)
+ [Microsoft OneDrive 資料來源的使用者內容篩選](#context-filter-onedrive)
+ [Microsoft OneDrive v2.0 資料來源的使用者內容篩選](#context-filter-onedrivev2)
+ [Microsoft SharePoint 資料來源的使用者內容篩選](#context-filter-sharepoint-online)
+ [Microsoft SQL Server 資料來源的使用者內容篩選](#context-filter-ms-sql-server)
+ [Microsoft Teams 資料來源的使用者內容篩選](#context-filter-teams)
+ [Microsoft Yammer 資料來源的使用者內容篩選](#context-filter-yammer)
+ [MySQL 資料來源的使用者內容篩選](#context-filter-mysql)
+ [Oracle 資料庫資料來源的使用者內容篩選](#context-filter-oracle-database)
+ [PostgreSQL 資料來源的使用者內容篩選](#context-filter-postgresql)
+ [Quip 資料來源的使用者內容篩選](#context-filter-quip)
+ [Salesforce 資料來源的使用者內容篩選](#context-filter-salesforce)
+ [ServiceNow 資料來源的使用者內容篩選](#context-filter-servicenow)
+ [Slack 資料來源的使用者內容篩選](#context-filter-slack)
+ [Zendesk 資料來源的使用者內容篩選](#context-filter-zendesk)

### Adobe Experience Manager 資料來源的使用者內容篩選
<a name="context-filter-aem"></a>

當您使用 Adobe Experience Manager 資料來源時， 會從 Adobe Experience Manager 執行個體 Amazon Kendra 取得使用者和群組資訊。

群組與使用者 ID 的對應方式如下：
+ `_group_ids`- 群組 IDs存在於具有設定存取許可的 Adobe Experience Manager 內容中。它們會從 Adobe Experience Manager 中的群組名稱映射。
+ `_user_id`- 使用者 IDs存在於具有設定存取許可的 Adobe Experience Manager 內容中。它們會從使用者電子郵件映射為 Adobe Experience Manager IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Alfresco 資料來源的使用者內容篩選
<a name="context-filter-alfresco"></a>

當您使用 Alfresco 資料來源時， 會從 Alfresco 執行個體 Amazon Kendra 取得使用者和群組資訊。

群組與使用者 ID 的對應方式如下：
+ `_group_ids`- IDs 存在於 Alfresco 中已設定存取許可的檔案。它們會從 Alfresco 中群組的系統名稱 （而非顯示名稱） 映射。
+ `_user_id`- IDs 存在於 Alfresco 中已設定存取許可的檔案。它們從使用者電子郵件映射為 Alfresco IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Aurora (MySQL) 資料來源的使用者內容篩選
<a name="context-filter-aurora-mysql"></a>

當您使用 a Aurora (MySQL) 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

A Aurora (MySQL) 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Aurora (PostgreSQL) 資料來源的使用者內容篩選
<a name="context-filter-aurora-postgresql"></a>

當您使用 a Aurora (PostgreSQL) 資料來源時， Amazon Kendra 會從來源資料表中的資料欄取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

A Aurora (PostgreSQL) 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Amazon FSx 資料來源的使用者內容篩選
<a name="context-filter-fsx"></a>

當您使用 Amazon FSx 資料來源時， 會從執行個體的 Amazon FSx 目錄服務 Amazon Kendra 取得使用者和群組資訊。

 Amazon FSx 群組和使用者 IDs的映射方式如下：
+ `_group_ids` — 群組 ID 會出現在 Amazon FSx 中已設定存取許可的檔案上。它們是從 目錄服務中的系統群組名稱映射 Amazon FSx。
+ `_user_id`- 具有設定存取許可的檔案 Amazon FSx 上存在使用者 IDs。它們是從 目錄服務中的系統使用者名稱映射 Amazon FSx。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### 資料庫資料來源的使用者內容篩選
<a name="context-filter-jdbc"></a>

當您使用資料庫資料來源時，例如 Amazon Aurora PostgreSQL， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 [AclConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_AclConfiguration.html) 物件中指定此欄，做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 中 [DatabaseConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_DatabaseConfiguration.html) 物件的一部分。

資料庫資料來源具有以下限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Amazon RDS (Microsoft SQL Server) 資料來源的使用者內容篩選
<a name="context-filter-rds-ms-sql-server"></a>

當您使用 Amazon RDS (Microsoft SQL Server) 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

A Amazon RDS (Microsoft SQL Server) 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Amazon RDS (MySQL) 資料來源的使用者內容篩選
<a name="context-filter-rds-mysql"></a>

當您使用 a Amazon RDS (MySQL) 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中指定此欄，或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分。

A Amazon RDS (MySQL) 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Amazon RDS (Oracle) 資料來源的使用者內容篩選
<a name="context-filter-rds-oracle"></a>

當您使用 Amazon RDS (Oracle) 資料來源時， Amazon Kendra 會從來源資料表中的資料欄取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

A Amazon RDS (Oracle) 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Amazon RDS (PostgreSQL) 資料來源的使用者內容篩選
<a name="context-filter-rds-postgresql"></a>

當您使用 Amazon RDS (PostgreSQL) 資料來源時， Amazon Kendra 會從來源資料表中的資料欄取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

A Amazon RDS (PostgreSQL) 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Amazon S3 資料來源的使用者內容篩選
<a name="context-filter-s3"></a>

您可以使用與文件相關聯的中繼資料檔案，將使用者內容篩選新增至 Amazon S3 資料來源中的文件。您可以將資訊新增至 JSON 文件中`AccessControlList`的 欄位。如需將中繼資料新增至從 Amazon S3 資料來源編製索引的文件的詳細資訊，請參閱 [S3 文件中繼資料](https://docs.aws.amazon.com/kendra/latest/dg/s3-metadata.html)。

您提供三種資訊：
+ 實體可擁有的存取權限。您可以說出 `ALLOW`或 `DENY`。
+ 實體類型。您可以說出 `USER`或 `GROUP`。
+ 實體的名稱。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Box 資料來源的使用者內容篩選
<a name="context-filter-box"></a>

當您使用 Box 資料來源時， 會從 Box 執行個體 Amazon Kendra 取得使用者和群組資訊。

Box 群組和使用者 IDs的映射方式如下：
+ `_group_ids`- 群組 IDs存在於具有設定存取許可的檔案的 Box 中。它們會從 Box 中群組的名稱映射。
+ `_user_id`- 使用者 IDs存在於具有設定存取許可的檔案的 Box 中。它們會從使用者電子郵件映射為 Box 中的使用者 IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Confluence 資料來源的使用者內容篩選
<a name="context-filter-confluence"></a>

當您使用 Confluence 資料來源時， 會從 Confluence 執行個體 Amazon Kendra 取得使用者和群組資訊。

您可透過空間許可頁面設定使用者與群組對空間的存取權。若要設定頁面與部落格的限制，請使用限制頁面。如需空間許可相關資訊，請參閱 Confluence Support 網站上的[空間許可概觀](https://confluence.atlassian.com/doc/space-permissions-overview-139521.html)。如需頁面與部落格限制的相關資訊，請參閱 Confluence Support 網站上的[頁面限制](https://confluence.atlassian.com/doc/page-restrictions-139414.html)。

Confluence 群組和使用者名稱的映射方式如下：
+ `_group_ids`- 群組名稱會出現在有限制的空格、頁面和部落格上。它們是從 Confluence 中群組的名稱映射。群組名稱一律以小寫呈現。
+ `_user_id`- 使用者名稱會出現在有限制的空間、頁面或部落格上。它們會根據您使用的 Confluence 執行個體類型進行映射。

  **針對 Confluence 連接器 v1.0**
  + 伺服器 - `_user_id`是使用者名稱。使用者名稱一律為小寫。
  + Cloud - `_user_id`是使用者的帳戶 ID。

  **針對 Confluence 連接器 v2.0**
  + 伺服器 - `_user_id`是使用者名稱。使用者名稱一律為小寫。
  + Cloud - `_user_id`是使用者的電子郵件 ID。
**重要**  
若要讓使用者內容篩選能夠正確運作於 Confluence 連接器，您需要確保授予 Confluence 頁面之使用者存取權的可見性設定為**任何人**。如需更多資訊，請參閱 Atlassian Developer 文件中的[設定您的電子郵件可見性](https://support.atlassian.com/confluence-cloud/docs/configure-user-email-visibility/)。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Dropbox 資料來源的使用者內容篩選
<a name="context-filter-dropbox"></a>

當您使用 Dropbox 資料來源時， 會從 Dropbox 執行個體 Amazon Kendra 取得使用者和群組資訊。

群組與使用者 ID 的對應方式如下：
+ `_group_ids`- 群組 IDs存在於 Dropbox 中具有設定存取許可的檔案。它們會從 Dropbox 中的群組名稱映射。
+ `_user_id`- 在具有設定存取許可的檔案上，使用者 IDs 存在於 Dropbox 中。它們會從使用者電子郵件映射為 Dropbox IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Drupal 資料來源的使用者內容篩選
<a name="context-filter-drupal"></a>

當您使用 Drupal 資料來源時， 會從 Drupalinstance Amazon Kendra 取得使用者和群組資訊。

群組與使用者 ID 的對應方式如下：
+ `_group_ids` — 群組 ID 會出現在 Drupal 中已設定存取許可的檔案。這些 ID 是根據 Drupal 的群組名稱對應而來。
+ `_user_id` — 使用者 ID 會出現在 Drupal 中已設定存取許可的檔案。在 Drupal 中，使用者的 ID 會對應自其電子郵件位址。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### GitHub 資料來源的使用者內容篩選
<a name="context-filter-github"></a>

當您使用 GitHub 資料來源時， 會從 GitHub 執行個體 Amazon Kendra 取得使用者資訊。

GitHub 使用者 IDs的映射方式如下：
+ `_user_id`- 使用者 IDs存在於 GitHub 中具有設定存取許可的檔案。它們會從使用者電子郵件映射為 GitHub IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Gmail 資料來源的使用者內容篩選
<a name="context-filter-gmail"></a>

當您使用 Gmail 資料來源時， 會從 Gmail 執行個體 Amazon Kendra 取得使用者資訊。

使用者 IDs 的映射方式如下：
+ `_user_id` – 具有設定存取許可的檔案上，Gmail 中存在使用者 IDs。它們從使用者電子郵件映射為 Gmail IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Google Drive 資料來源的使用者內容篩選
<a name="context-filter-google"></a>

Google Workspace Drive 資料來源會傳回 Google Drive 使用者和群組的使用者和群組資訊。群組和網域成員資格會對應至`_group_ids`索引欄位。Google Drive 使用者名稱會映射至 `_user_id` 欄位。

當您在 `Query` API 中提供一或多個使用者電子郵件地址時，只會傳回已與這些電子郵件地址共用的文件。下列`AttributeFilter`參數只會傳回與 "martha@example.com" 共用的文件。

```
"AttributeFilter": {
                "EqualsTo":{
                   "Key": "_user_id", 
                   "Value": {
                       "StringValue": "martha@example.com"
                   }
               }
           }
```

如果您在查詢中提供一或多個群組電子郵件地址，則只會傳回與群組共用的文件。下列`AttributeFilter`參數只會傳回與 "hr@example.com" 群組共用的文件。

```
"AttributeFilter": {
                "EqualsTo":{
                   "Key": "_group_ids", 
                   "Value": {
                       "StringListValue": ["hr@example.com"]
                   }
               }
           }
```

如果您在查詢中提供網域，則會傳回與網域共用的所有文件。下列`AttributeFilter`參數會傳回與 "example.com" 網域共用的文件。

```
"AttributeFilter": {
                "EqualsTo":{
                   "Key": "_group_ids", 
                   "Value": {
                       "StringListValue": ["example.com"]
                   }
               }
           }
```

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。



### IBM DB2 資料來源的使用者內容篩選
<a name="context-filter-ibm-db2"></a>

當您使用 IBM DB2 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

IBM DB2 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Jira 資料來源的使用者內容篩選
<a name="context-filter-jira"></a>

當您使用 Jira 資料來源時， 會從 Jira 執行個體 Amazon Kendra 取得使用者和群組資訊。

Jira 使用者 IDs的映射方式如下：
+ `_user_id`- 在具有設定存取許可的檔案中，使用者 IDs 存在於 Jira 中。它們會從使用者電子郵件映射為 Jira 中的使用者 IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Microsoft Exchange 資料來源的使用者內容篩選
<a name="context-filter-exchange"></a>

當您使用 Microsoft Exchange 資料來源時， 會從 Microsoft Exchange 執行個體 Amazon Kendra 取得使用者資訊。

Microsoft Exchange 使用者 IDs的映射方式如下：
+ `_user_id`- 使用者 IDs存在於 Microsoft Exchange 許可中，讓使用者存取特定內容。它們會從使用者名稱映射為 Microsoft Exchange IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Microsoft OneDrive 資料來源的使用者內容篩選
<a name="context-filter-onedrive"></a>

Amazon Kendra 會在將網站上的文件編製索引時，從 Microsoft OneDrive 擷取使用者和群組資訊。使用者和群組資訊取自託管 OneDrive 的基礎 Microsoft SharePoint 網站。

當您使用 OneDrive 使用者或群組來篩選搜尋結果時，請計算 ID，如下所示：

1. 取得網站名稱。例如 `https://host.onmicrosoft.com/sites/siteName.`

1. 取得網站名稱的 MD5 雜湊。例如 `430a6b90503eef95c89295c8999c7981`。

1. 建立使用者電子郵件或群組 ID，方法是將 MD5 雜湊與垂直列 (\$1) 和 ID 串連。例如，如果群組名稱為 "localGroupName"，則群組 ID 將為：

   `"430a6b90503eef95c89295c8999c7981 | localGroupName"`
**注意**  
在垂直長條前後包含空格。垂直列用於`localGroupName`識別其 MD5 雜湊。

   對於使用者名稱 "someone@host.onmicrosoft.com"，使用者 ID 如下：

   `"430a6b90503eef95c89295c8999c7981 | someone@host.onmicrosoft.com"`

當您呼叫[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 時，將使用者或群組 ID Amazon Kendra 做為 `_group_id` `_user_id`或 屬性傳送至 。例如，使用群組來篩選搜尋結果的 AWS CLI 命令如下所示：

```
aws kendra  query \
                --index-id index ID  
                --query-text "query text" 
                --attribute-filter '{
                   "EqualsTo":{
                     "Key": "_group_id", 
                     "Value": {"StringValue": "430a6b90503eef95c89295c8999c7981 | localGroupName"}
                  }}'
```

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Microsoft OneDrive v2.0 資料來源的使用者內容篩選
<a name="context-filter-onedrivev2"></a>

Microsoft OneDrive v2.0 資料來源會從 OneDrive 存取控制清單 (ACL) 實體傳回區段和頁面資訊。 Amazon Kendra 會使用 OneDrive 租用戶網域連線至 OneDrive 執行個體，然後可以根據使用者或群組對區段和檔案名稱的存取來篩選搜尋結果。

對於標準物件， `_user_id`和 `_group_id` 的使用方式如下：
+ `_user_id`— 您的 Microsoft OneDrive 使用者電子郵件 ID 會映射至 `_user_id` 欄位。
+ `_group_id`— 您的 Microsoft OneDrive 群組電子郵件會映射至 `_group_id` 欄位。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Microsoft SharePoint 資料來源的使用者內容篩選
<a name="context-filter-sharepoint-online"></a>

Amazon Kendra 當網站文件編製索引時， 會從 Microsoft SharePoint 擷取使用者和群組資訊。若要根據使用者或群組存取權篩選搜尋結果，請在呼叫 `Query` API 時提供使用者和群組資訊。

若要使用使用者名稱進行篩選，請使用使用者的電子郵件地址。例如，johnstiles@example.com。

當您使用 SharePoint 群組篩選搜尋結果時，請計算群組 ID，如下所示：

**針對本機群組**

1. 取得網站名稱。例如 `https://host.onmicrosoft.com/sites/siteName.`

1. 對網站名稱進行 SHA256 雜湊。例如 `430a6b90503eef95c89295c8999c7981`。

1. 透過將 SHA256 雜湊與垂直長條 (\$1) 和群組名稱串連來建立群組 ID。例如，如果群組名稱為 "localGroupName"，則群組 ID 將為：

   `"430a6b90503eef95c89295c8999c7981 | localGroupName"`
**注意**  
在垂直長條前後包含空格。垂直列用於`localGroupName`識別其 SHA256 雜湊。

當您呼叫[查詢 API](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) 時，請將群組 ID Amazon Kendra 做為 `_group_id` 屬性傳送至 。例如， AWS CLI 命令如下所示：

```
aws kendra  query \
                --index-id index ID  
                --query-text "query text" 
                --attribute-filter '{
                   "EqualsTo":{
                     "Key": "_group_id", 
                     "Value": {"StringValue": "430a6b90503eef95c89295c8999c7981 | localGroupName"}
                  }}'
```

**對於 AD 群組**

1. 使用 AD 群組 ID 來設定搜尋結果的篩選。

當您呼叫[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 時，請將群組 ID Amazon Kendra 做為 `_group_id` 屬性傳送至 。例如， AWS CLI 命令如下所示：

```
aws kendra  query \
                --index-id index ID  
                --query-text "query text" 
                --attribute-filter '{
                   "EqualsTo":{
                     "Key": "_group_id", 
                     "Value": {"StringValue": "AD group"}
                  }}'
```

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Microsoft SQL Server 資料來源的使用者內容篩選
<a name="context-filter-ms-sql-server"></a>

當您使用 Microsoft SQL Server 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

Microsoft SQL Server 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Microsoft Teams 資料來源的使用者內容篩選
<a name="context-filter-teams"></a>

Amazon Kendra 會在將文件編製索引時，從 Microsoft Teams 擷取使用者資訊。使用者資訊取自基礎 Microsoft Teams 執行個體。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Microsoft Yammer 資料來源的使用者內容篩選
<a name="context-filter-yammer"></a>

Amazon Kendra 會在將文件編製索引時，從 Microsoft Yammer 擷取使用者資訊。使用者和群組資訊取自基礎 Microsoft Yammer 執行個體。

Microsoft Yammer 使用者 IDs的映射方式如下：
+ `_email_id`— 映射至 `_user_id` 欄位的 Microsoft 電子郵件 ID。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。



### MySQL 資料來源的使用者內容篩選
<a name="context-filter-mysql"></a>

當您使用 MySQL 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

MySQL 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Oracle 資料庫資料來源的使用者內容篩選
<a name="context-filter-oracle-database"></a>

當您使用 Oracle 資料庫資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

Oracle 資料庫資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### PostgreSQL 資料來源的使用者內容篩選
<a name="context-filter-postgresql"></a>

當您使用 PostgreSQL 資料來源時， 會從來源資料表中的資料欄 Amazon Kendra 取得使用者和群組資訊。您可以在 主控台中或使用 [TemplateConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_TemplateConfiguration.html) 物件做為 [CreateDataSource](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CreateDataSource.html) API 的一部分來指定此欄。

PostgreSQL 資料庫資料來源有下列限制：
+ 您只能為資料庫資料來源設定允許清單。無法設定拒絕清單。
+ 僅支援設定群組。不支援為允許清單指定單一使用者。
+ 資料庫欄位必須為字串格式，內容為以分號分隔的群組清單。

### Quip 資料來源的使用者內容篩選
<a name="context-filter-quip"></a>

當您使用 Quip 資料來源時， 會從 Quip 執行個體 Amazon Kendra 取得使用者資訊。

Quip 使用者 ID 的對應方式如下：
+ `_user_id` — 使用者 ID 會出現在 Quip 中已設定存取許可的檔案上。在 Quip 中，使用者的 ID 會對應自其電子郵件位址。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Salesforce 資料來源的使用者內容篩選
<a name="context-filter-salesforce"></a>

Salesforce 資料來源會從 Salesforce 存取控制清單 (ACL) 實體傳回使用者和群組資訊。您可以將使用者內容篩選套用至 Salesforce 標準物件和 Chatter 摘要。使用者內容篩選不適用於 Salesforce 知識文章。

如果您將任何 Salesforce 欄位映射至 Amazon Kendra 文件標題和文件內文欄位，Amazon Kendra 將使用搜尋回應中文件標題和內文欄位的資料。

對於標準物件， `_user_id`和 `_group_ids` 的使用方式如下：
+ `_user_id`- Salesforce 使用者的使用者名稱。
+ `_group_ids`—
  + Salesforce 的名稱 `Profile`
  + Salesforce 的名稱 `Group`
  + Salesforce 的名稱 `UserRole`
  + Salesforce 的名稱 `PermissionSet`

對於聊天器摘要， `_user_id`和 `_group_ids` 的使用方式如下：
+ `_user_id`- Salesforce 使用者的使用者名稱。僅當項目張貼於使用者摘要時可用。
+ `_group_ids`- 群組 IDs的使用方式如下。僅當摘要項目張貼於 Chatter 或協同合作群組時可用。
  + Chatter 或協同合作群組的名稱。
  + 若群組為公開狀態，則為 `PUBLIC:ALL`。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### ServiceNow 資料來源的使用者內容篩選
<a name="context-filter-servicenow"></a>

只有 TemplateConfiguration API 和 ServiceNow Connector v2.0 才支援 ServiceNow 的使用者內容篩選。 ServiceNow ServiceNowConfiguration API 和 ServiceNow Connector v1.0。 不支援使用者內容篩選。

當您使用 ServiceNow 資料來源時， 會從 ServiceNow 執行個體 Amazon Kendra 取得使用者和群組資訊。

群組與使用者 ID 的對應方式如下：
+ `_group_ids`- 群組 IDs存在於 ServiceNow 中已設定存取許可的檔案。它們會從 ServiceNow `sys_ids`中 的角色名稱映射。
+ `_user_id`- 使用者 IDs存在於 ServiceNow 中已設定存取許可的檔案。從使用者電子郵件映射為 ServiceNow IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Slack 資料來源的使用者內容篩選
<a name="context-filter-slack"></a>

當您使用 Slack 資料來源時， 會從 Slack 執行個體 Amazon Kendra 取得使用者資訊。

Slack 使用者 IDs的映射方式如下：
+ `_user_id`- 在具有設定存取許可的訊息和頻道上，使用者 IDs 存在於 Slack 中。它們從使用者電子郵件映射為 Slack IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

### Zendesk 資料來源的使用者內容篩選
<a name="context-filter-zendesk"></a>

當您使用 Zendesk 資料來源時， 會從 Zendesk 執行個體 Amazon Kendra 取得使用者和群組資訊。

群組與使用者 ID 的對應方式如下：
+ `_group_ids`- IDs 存在於具有設定存取許可的 Zendesk 票證和文章中。它們會從 Zendesk 中的群組名稱映射。
+ `_user_id`- IDs 存在於具有設定存取許可的 Zendesk 票證和文章中。它們會從使用者電子郵件映射為 Zendesk IDs。

您可以在 `AccessControlList` 欄位中新增最多 200 個項目。

# 查詢回應和回應類型
<a name="query-responses-types"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

Amazon Kendra 支援不同的查詢回應和回應類型。

## 查詢回應
<a name="query-responses"></a>

對[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 的呼叫會傳回有關搜尋結果的資訊。結果位於 [QueryResultItem](https://docs.aws.amazon.com/kendra/latest/APIReference/API_QueryResultItem.html) 物件的陣列中 (`ResultItems`)。每個 都`QueryResultItem`包含結果的摘要。包含與查詢結果相關聯的文件屬性。

**摘要資訊**  
摘要資訊會根據結果類型而有所不同。在每個案例中，都包含符合搜尋詞彙的文件文字。它還包含反白資訊，您可以用來反白應用程式輸出中的搜尋文字。例如，如果搜尋詞*是 Space Needle 的高度？*，則摘要資訊會包含文字*高度*和*空格針*的文字位置。如需回應類型的資訊，請參閱 [查詢回應和回應類型](#query-responses-types)。

**文件屬性**  
每個結果都包含符合查詢之文件的文件屬性。某些屬性是預先定義的，例如 `DocumentId`、 `DocumentTitle`和 `DocumentUri`。其他則是您定義的自訂屬性。您可以使用文件屬性來篩選`Query`來自 API 的回應。例如，您可能只想要特定作者撰寫的文件或特定版本的文件。如需詳細資訊，請參閱[篩選和面向搜尋](filtering.md)。將文件新增至索引時，您可以指定文件屬性。如需詳細資訊，請參閱[自訂欄位或屬性](https://docs.aws.amazon.com/kendra/latest/dg/custom-attributes.html)。

以下是查詢結果的範例 JSON 程式碼。請注意 `DocumentAttributes`和 中的文件屬性`AdditionalAttributes`。

```
{
    "QueryId": "query-id",
    "ResultItems": [
        {
            "Id": "result-id",
            "Type": "ANSWER",
            "AdditionalAttributes": [
                {
                    "Key": "AnswerText",
                    "ValueType": "TEXT_WITH_HIGHLIGHTS_VALUE",
                    "Value": {
                        "TextWithHighlightsValue": {
                            "Text": "text",
                            "Highlights": [
                                {
                                    "BeginOffset": 55,
                                    "EndOffset": 90,
                                    "TopAnswer": false
                                }
                            ]
                        }
                    }
                }
            ],
            "DocumentId": "document-id",
            "DocumentTitle": {
                "Text": "title"
            },
            "DocumentExcerpt": {
                "Text": "text",
                "Highlights": [
                    {
                        "BeginOffset": 0,
                        "EndOffset": 300,
                        "TopAnswer": false
                    }
                ]
            },
            "DocumentURI": "uri",
            "DocumentAttributes": [],
            "ScoreAttributes": "score",
            "FeedbackToken": "token"
        },
        {
            "Id": "result-id",
            "Type": "ANSWER",
            "Format": "TABLE",
            "DocumentId": "document-id",
            "DocumentTitle": {
                "Text": "title"
            },
            "TableExcerpt": {
                "Rows": [{
                    "Cells": [{
                        "Header": true,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    }, {
                        "Header": true,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    }, {
                        "Header": true,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    }, {
                        "Header": true,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    }]
                }, {
                    "Cells": [{
                        "Header": false,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    }, {
                        "Header": false,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    }, {
                        "Header": false,
                        "Highlighted": true,
                        "TopAnswer": true,
                        "Value": "value"
                    }, {
                        "Header": false,
                        "Highlighted": false,
                        "TopAnswer": false,
                        "Value": "value"
                    ]}
                  }],
                    "TotalNumberofRows": number
			},
            "DocumentURI": "uri",
            "ScoreAttributes": "score",
            "FeedbackToken": "token"
        },
        {
            "Id": "result-id",
            "Type": "DOCUMENT",
            "AdditionalAttributes": [],
            "DocumentId": "document-id",
            "DocumentTitle": {
                "Text": "title",
                "Highlights": []
            },
            "DocumentExcerpt": {
                "Text": "text",
                "Highlights": [
                    {
                        "BeginOffset": 74,
                        "EndOffset": 77,
                        "TopAnswer": false
                    }
                ]
            },
            "DocumentURI": "uri",
            "DocumentAttributes": [
                {
                    "Key": "_source_uri",
                    "Value": {
                        "StringValue": "uri"
                    }
                }
            ],
            "ScoreAttributes": "score",
            "FeedbackToken": "token",
        }
    ],
    "FacetResults": [],
    "TotalNumberOfResults": number
}
```

## 回應類型
<a name="response-types"></a>

Amazon Kendra 傳回三種類型的查詢回應。
+ 答案 （包括資料表答案）
+ 文件
+ 問題和解答

回應的類型會在 [QueryResultItem](https://docs.aws.amazon.com/kendra/latest/APIReference/API_QueryResultItem.html) 物件的`Type`回應欄位中傳回。

### 答案
<a name="query-answer"></a>

Amazon Kendra 在回應中偵測到一或多個問題答案。事實是對以下人員的回應：什麼人、什麼、何時或哪裡的問題，例如距離*我最近的服務中心在哪裡？* 會 Amazon Kendra 傳回索引中最符合查詢的文字。文字在 `AnswerText` 欄位中，並包含回應文字中搜尋詞彙的反白資訊。 `AnswerText`包含具有反白文字的完整文件摘錄，同時`DocumentExcerpt`包含具有反白文字的截斷 (290 個字元） 文件摘錄。

Amazon Kendra 每個文件只會傳回一個答案，而這是可信度最高的答案。若要從文件傳回多個答案，您必須將文件分割成多個文件。

```
{
    'AnswerText': {
        'TextWithHighlights': [
            {
                'BeginOffset': 271,
                'EndOffset': 279,
                'TopAnswer': False
            },
            {
                'BeginOffset': 481,
                'EndOffset': 489,
                'TopAnswer': False
            },
            {
                'BeginOffset': 547,
                'EndOffset': 555,
                'TopAnswer': False
            },
            {
                'BeginOffset': 764,
                'EndOffset': 772,
                'TopAnswer': False
            }
        ],
        'Text': 'Asynchronousoperationscan\n''alsoprocess\n''documentsthatareinPDF''format.UsingPDFformatfilesallowsyoutoprocess''multi-page\n''documents.\n''Forinformationabouthow''AmazonTextractrepresents\n''documentsasBlockobjects,
        ''seeDocumentsandBlockObjects.\n''\n''\n''\n''Forinformationaboutdocument''limits,
        seeLimitsinAmazonTextract.\n''\n''\n''\n''TheAmazonTextractsynchronous''operationscanprocessdocumentsstoredinanAmazon\n''S3Bucketoryoucanpass''base64encodedimagebytes.\n''Formoreinformation,
        see''CallingAmazonTextractSynchronousOperations.''Asynchronousoperationsrequireinputdocuments\n''tobesuppliedinanAmazon''S3Bucket.'
    },
    'DocumentExcerpt': {
        'Highlights': [
            {
                'BeginOffset': 0,
                'EndOffset': 300,
                'TopAnswer': False
            }
        ],
        'Text': 'Asynchronousoperationscan\n''alsoprocess\n''documentsthatareinPDF''format.UsingPDFformatfilesallowsyoutoprocess''multi-page\n''documents.\n''ForinformationabouthowAmazon''Textractrepresents\n'''
    },
    'Type': 'ANSWER'
}
```

### 文件
<a name="query-document"></a>

Amazon Kendra 會傳回符合搜尋詞彙的排名文件。排名是根據對搜尋結果 Amazon Kendra 準確性的可信度。[QueryResultItem](https://docs.aws.amazon.com/kendra/latest/APIReference/API_QueryResultItem.html) 中會傳回相符文件的相關資訊。它包含文件的標題。摘錄包含搜尋文字的反白資訊，以及文件中相符文字的區段。相符文件的 URI 位於`SourceURI`文件屬性中。下列範例 JSON 顯示相符文件的文件摘要。

```
{
    'DocumentTitle': {
        'Highlights': [
            {
                'BeginOffset': 7,
                'EndOffset': 15,
                'TopAnswer': False
            },
            {
                'BeginOffset': 97,
                'EndOffset': 105,
                'TopAnswer': False
            }
        ],
        'Text': 'AmazonTextractAPIPermissions: Actions,
        \n''Permissions,
        andResourcesReference-''AmazonTextract'
    },
    'DocumentExcerpt': {
        'Highlights': [
            {
                'BeginOffset': 68,
                'EndOffset': 76,
                'TopAnswer': False
            },
            {
                'BeginOffset': 121,
                'EndOffset': 129,
                'TopAnswer': False
            }
        ],
        'Text': '...LoggingandMonitoring\tMonitoring\n''\tCloudWatchMetricsforAmazonTextract\n''\tLoggingAmazonTextractAPICallswithAWSCloudTrail\n''\tAPIReference\tActions\tAnalyzeDocument\n''\tDetectDocumentText\n''\tGetDocumentAnalysis...'
    },
    'Type': 'DOCUMENT'
}
```

### 問題和解答
<a name="query-question-answer"></a>

當 Amazon Kendra 符合您索引中其中一個常見問題的問題時，會傳回問題和答案回應。回應包含 [QueryResultItem](https://docs.aws.amazon.com/kendra/latest/APIReference/API_QueryResultItem.html) 欄位中相符的問題和答案。它還包含查詢字串中偵測到的查詢詞彙反白資訊。下列 JSON 會顯示問題和答案回應。請注意，回應包含問題文字。

```
{
    'AnswerText': {
        'TextWithHighlights': [
            
        ],
        'Text': '605feet'
    },
    'DocumentExcerpt': {
        'Highlights': [
            {
                'BeginOffset': 0,
                'EndOffset': 8,
                'TopAnswer': False
            }
        ],
        'Text': '605feet'
    },
    'Type': 'QUESTION_ANSWER',
    'QuestionText': {
        'Highlights': [
            {
                'BeginOffset': 12,
                'EndOffset': 18,
                'TopAnswer': False
            },
            {
                'BeginOffset': 26,
                'EndOffset': 31,
                'TopAnswer': False
            },
            {
                'BeginOffset': 32,
                'EndOffset': 38,
                'TopAnswer': False
            }
        ],
        'Text': 'whatistheheightoftheSpaceNeedle?'
    }
}
```

如需將問題和答案文字新增至索引的詳細資訊，請參閱[建立常見問答集](https://docs.aws.amazon.com/kendra/latest/dg/in-creating-faq.html)。

# 調校和排序回應
<a name="tuning-sorting-responses"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

您可以透過相關性調校來修改欄位或屬性對搜尋相關性的影響。您也可以依特定屬性或欄位排序搜尋結果。

**Topics**
+ [調校回應](#tuning-responses)
+ [排序回應](#sorting-responses)

## 調校回應
<a name="tuning-responses"></a>

您可以透過相關性調校來修改欄位或屬性對搜尋相關性的影響。若要快速測試相關性調校，請使用[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 在查詢中傳入調校組態。然後，您可以查看從不同組態取得的不同搜尋結果。主控台不支援查詢層級的關聯性調校。您也可以只在`StringList`索引層級調校類型 的欄位或屬性。如需詳細資訊，請參閱[調整搜尋相關性](https://docs.aws.amazon.com/kendra/latest/dg/tuning.html)。

根據預設，查詢回應會依回應中每個結果 Amazon Kendra 的相關性分數進行排序。

您可以調校下列類型之任何內建或自訂屬性/欄位的結果：
+ 日期值
+ 長值
+ 字串值

您無法排序下列類型的屬性：
+ 字串清單值

**排名和調校文件結果 (AWS SDK)**  
將 `Searchable` 參數設定為 true，以提升文件中繼資料組態。

若要調校查詢中的屬性，請設定 `Query` API 的 `DocumentRelevanceOverrideConfigurations` 參數，並指定要調校的屬性名稱。

下列 JSON 範例顯示`DocumentRelevanceOverrideConfigurations`物件，可覆寫索引中稱為 "department" 之屬性的調校。

```
"DocumentRelevanceOverrideConfigurations" : [
    "Name": "department",
    "Relevance": {
        "Importance": 1,
        "ValueImportanceMap": {
            "IT": 3,
            "HR": 7
        }
    }
]
```

## 排序回應
<a name="sorting-responses"></a>

Amazon Kendra 使用排序屬性或欄位做為查詢所傳回文件條件的一部分。例如，依 "\$1created\$1at" 排序的查詢傳回的結果，可能不會包含與依 "\$1version" 排序的查詢相同的結果。

根據預設，查詢回應會依回應中每個結果 Amazon Kendra 的相關性分數進行排序。若要變更排序順序，請將文件屬性設為可排序，然後設定 Amazon Kendra 使用該屬性來排序回應。

您可以在下列類型的任何內建或自訂屬性/欄位上排序結果：
+ 日期值
+ 長值
+ 字串值

您無法排序下列類型的屬性：
+ 字串清單值

您可以在每個查詢中排序一或多個文件屬性。查詢會傳回 100 個結果。如果排序屬性集的文件少於 100 個，則結果結尾會傳回沒有排序屬性值的文件，並依查詢的相關性進行排序。

**排序文件結果 (AWS SDK)**

1. 若要使用 [UpdateIndex](https://docs.aws.amazon.com/kendra/latest/APIReference/API_UpdateIndex.html) API 使屬性可排序，請將 `Sortable` 參數設定為 `true`。下列 JSON 範例使用 `DocumentMetadataConfigurationUpdates`將名為 "Department" 的屬性新增至索引，並使其可排序。

   ```
   "DocumentMetadataConfigurationUpdates": [
      {
          "Name": "Department",
          "Type": "STRING_VALUE",
          "Search": {
              "Sortable": "true"
          }
      }
   ]
   ```

1. 若要在查詢中使用一個可排序屬性，請設定[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 的 `SortingConfiguration` 參數。指定要排序的屬性名稱，以及是否以遞增或遞減順序排序回應。

   下列 JSON 範例顯示您用來依「部門」屬性依遞增順序排序查詢結果的`SortingConfiguration`參數。

   ```
      "SortingConfiguration": { 
         "DocumentAttributeKey": "Department",
         "SortOrder": "ASC"
      }
   ```

1. 若要在查詢中使用多個可排序屬性，請設定[查詢](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html) API 的 `SortingConfigurations` 參數。您可以設定最多 3 個欄位來 Amazon Kendra 排序結果。您也可以指定結果是否應依遞增或遞減順序排序。排序欄位配額可以增加。

   如果您不提供排序組態，結果會依 Amazon Kendra 結果決定的相關性進行排序。如果結果排序有關聯，結果會依相關性排序。

   下列 JSON 範例顯示您用來依屬性 "Name" 和 "Price" 依遞增順序排序查詢結果的`SortingConfigurations`參數。

   ```
   "CollapseConfiguration" : {
       "DocumentAttributeKey": "Name",
       "SortingConfigurations": [
           { 
               "DocumentAttributeKey": "Price",
               "SortOrder": "ASC"
           }
       ],
       "MissingAttributeKeyStrategy": "IGNORE"
   }
   ```

**排序文件結果 （主控台）**
**注意**  
目前不支援多屬性排序 AWS 管理主控台。

1. 若要在主控台中使屬性可排序，請在屬性定義中選擇**可排序**。您可以在建立屬性時讓屬性可排序，也可以稍後修改。

1. 若要在主控台中排序查詢回應，請從**排序**功能表選擇屬性來排序回應。只有資料來源組態期間標示為可排序的屬性才會出現在清單中。

# 收合/展開查詢結果
<a name="expand-collapse-query-results"></a>

**注意**  
功能支援會因索引類型和正在使用的搜尋 API 而有所不同。若要查看您正在使用的索引類型和搜尋 API 是否支援此功能，請參閱[索引類型](https://docs.aws.amazon.com/kendra/latest/dg/hiw-index-types.html)。

當您 Amazon Kendra 連線到資料時，它會編目[文件中繼資料屬性](https://docs.aws.amazon.com/kendra/latest/dg/hiw-document-attributes.html)，例如 `_document_title`、 `_created_at`和 `_document_id`，並使用這些屬性或欄位在查詢期間提供進階搜尋功能。

Amazon Kendra的收合和展開查詢結果功能可讓您使用常見文件屬性將搜尋結果分組，並在指定的主要文件下顯示折疊或部分展開。

**注意**  
摺疊和展開查詢結果功能目前只能透過 [Amazon Kendra API](https://docs.aws.amazon.com/kendra/latest/APIReference/welcome.html) 使用。

這在下列類型的搜尋情況下非常有用：
+ 索引中的文件中存在多個版本的內容。當您的最終使用者查詢索引時，您希望他們查看文件的最相關版本，其中包含隱藏/收合的重複項目。例如，如果您的索引包含名為 "NYC leave policy" 的多個文件版本，您可以選擇使用 "Type" 屬性/欄位來摺疊特定群組 "HR" 和 "Legal" 的文件。  
![\[範例 1\]](http://docs.aws.amazon.com/zh_tw/kendra/latest/dg/images/expand-collapse-1.png)
+ 您的索引包含多份文件，其中包含有關一種項目或物件的獨特資訊，例如產品庫存。若要方便地擷取和排序項目資訊，您希望最終使用者存取項目或物件連結的所有文件，做為一個搜尋結果。在下列範例中，客戶搜尋「動物印花襯衫」會傳回依名稱分組的結果，並依遞增價格順序排序。  
![\[範例 2\]](http://docs.aws.amazon.com/zh_tw/kendra/latest/dg/images/expand-collapse-2.png)

## 摺疊結果
<a name="expand-results"></a>

若要將類似或相關文件分組在一起，您必須指定要收合的屬性 （例如，您可以依 收合/分組文件`_category`)。若要這樣做，請呼叫[查詢 API](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Query.html)，並使用 [CollapseConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CollapseConfiguration.html) 物件來指定`DocumentAttributeKey`要收合的 。`DocumentAttributeKey` 控制將摺疊哪些欄位搜尋結果。支援的屬性索引鍵欄位包括 `String`和 `Number`。不支援 `String list`和 `Date`類型。

## 使用排序順序選擇主要文件
<a name="primary-document"></a>

若要將主要文件設定為顯示摺疊群組，請在 [CollapseConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CollapseConfiguration.html) 下使用 `SortingConfigurations` 參數。例如，若要取得文件的最新版本，您可以依 排序每個摺疊的群組`_version`。您可以使用 指定最多 3 個要排序的屬性/欄位，以及每個屬性/欄位的排序順序`SortingConfigurations`。您可以請求增加排序屬性數量的配額。

根據預設， 會根據其在回應中為每個結果決定的相關性分數來 Amazon Kendra 排序查詢回應。若要變更預設排序順序，請將文件屬性設為可排序，然後設定 Amazon Kendra 使用這些屬性來排序回應。如需詳細資訊，請參閱[排序回應](https://docs.aws.amazon.com/kendra/latest/dg/tuning-sorting-responses.html#sorting-responses)。

## 缺少文件金鑰策略
<a name="missing-doc-key"></a>

如果您的文件沒有摺疊屬性值， Amazon Kendra 提供三個自訂選項：
+ 在一個群組中選擇具有 null 值或遺失值`COLLAPSE`的所有文件。這是預設組態。
+ 選擇具有 null 或遺失值`IGNORE`的文件。忽略的文件不會出現在查詢結果中。
+ 將具有 null 或遺失值`EXPAND`的每個文件選擇為自己的群組。

## 展開結果
<a name="expanding-results"></a>

您可以使用 [CollapseConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_CollapseConfiguration.html) 物件中的 `Expand` 參數，選擇折疊的搜尋結果群組是否展開。展開的結果會維持用來選取群組主要文件的相同排序順序。

若要設定要展開的摺疊搜尋結果群組數量，您可以在 [ExpandConfiguration](https://docs.aws.amazon.com/kendra/latest/APIReference/API_ExpandConfiguration.html) 物件中使用 `MaxResultItemstoExpand` 參數。例如，如果您將此值設定為 10，則只有 100 個結果群組中的前 10 個將具有擴展功能。

若要設定展開的結果數量，以顯示每個摺疊的主要文件，請使用 `MaxExpandResultsPerItem` 參數。例如，如果您將此值設定為 3，則每個摺疊的群組最多會顯示 3 個結果。

## 與其他 Amazon Kendra 功能的互動
<a name="cross-feature-interactions"></a>
+ 摺疊和擴展結果不會變更構面數，也不會影響顯示的結果總數。
+ Amazon Kendra [特徵化搜尋結果](https://docs.aws.amazon.com/kendra/latest/dg/featured-results.html)即使與您設定的收合欄位具有相同的欄位值，也不會收合。
+ 摺疊和擴展結果僅適用於類型 的結果`DOCUMENT`。