

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

# Amazon Kendra 自我管理 OpenSearch 的智慧型排名
<a name="opensearch-rerank"></a>

您可以利用 Amazon Kendra的語意搜尋功能來改善 [OpenSearch](https://opensearch.org/docs/latest) 的搜尋結果，這是以 Apache 2.0 授權為基礎的自我管理開放原始碼搜尋服務。Intelligent Ranking Amazon Kendra 外掛程式使用 以語意方式重新排序 OpenSearch 的結果 Amazon Kendra。它透過從預設 OpenSearch 搜尋結果中了解使用特定欄位搜尋查詢的含義和內容，例如文件內文或標題。

例如，以此查詢為例：「主要主題演講地址」。由於「地址」有數個意義，因此 Amazon Kendra 可以推斷查詢背後的意義，以傳回與預期意義一致的相關資訊。在這種情況下，它是會議主題演講地址。例如，更簡單的搜尋服務可能不會考慮意圖，並且可能會傳回 Main Street 上街道地址的結果。

OpenSearch 的 Intelligent Ranking 外掛程式適用於 OpenSearch （自我管理） 2.4.0 版及更新版本。您可以使用快速入門 Bash 指令碼安裝外掛程式，以使用隨附的 Intelligent Ranking 外掛程式建置 OpenSearch 的新 Docker 映像。請參閱 [設定智慧型搜尋外掛程式](#setup-opensearch-rerank-plugin)— 這是可讓您快速啟動和執行的設定範例。

## 智慧型搜尋外掛程式的運作方式
<a name="how-opensearch-rerank-plugin-works"></a>

適用於 OpenSearch 的 Intelligent Ranking 外掛程式 （自我管理） 的整體程序如下：

1. OpenSearch 使用者發出查詢，而 OpenSearch 會提供查詢回應或與查詢相關的文件清單。

1. Intelligent Ranking 外掛程式會取得查詢回應，並從文件中擷取資訊。

1. Intelligent Ranking 外掛程式會呼叫 Amazon Kendra Intelligent Ranking 的 [Rescore](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Ranking_Rescore.html) API。

1. `Rescore` API 會從文件中擷取資訊，並以語意方式重新排序搜尋結果。

1. `Rescore` API 會將重新排名的搜尋結果傳回至外掛程式。外掛程式會重新排列 OpenSearch 搜尋回應中的搜尋結果，以反映新的語意排名。

Intelligent Ranking 外掛程式會使用「本文」和「標題」欄位來重新排序結果。這些外掛程式欄位可以映射到 OpenSearch 索引中最符合文件內文和標題定義的欄位。例如，如果您的索引包含具有 "chapter\$1heading" 和 "chapter\$1contents" 等欄位的書籍章節，您可以將前者映射至 "title"，後者映射至 "body"，以取得最佳結果。

## 設定智慧型搜尋外掛程式
<a name="setup-opensearch-rerank-plugin"></a>

以下概述如何使用 Intelligent Ranking 外掛程式快速設定 OpenSearch （自我管理）。

**使用 Intelligent Ranking 外掛程式設定 OpenSearch （自我管理） （快速設定）**

如果您已使用 Docker 映像 `opensearch:2.4.0`，您可以使用此 [Dockerfile](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html#dockerfile-build-opensearch-example) 搭配 Intelligent Ranking 外掛程式建置 OpenSearch 2.4.0 的新映像。您可以在 [docker-compose.yml](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html#docker-compose-opensearch-example) 檔案或 opensearch.yml 檔案中包含新映像的容器。您也會包含建立重新評分執行計畫所產生的重新評分執行計畫 ID，以及您的區域和端點資訊，請參閱建立重新評分執行計畫的步驟 2。

如果您先前已下載早於 `opensearch` 2.4.0 的 Docker 映像版本，則必須使用 Docker 映像`opensearch:2.4.0`或更新版本，並使用隨附的 Intelligent Ranking 外掛程式建置新的映像。

1. 為您的作業系統下載並安裝 [Docker Desktop](https://docs.docker.com/get-docker/)。Docker 桌面包括 Docker Compose 和 Docker 引擎。建議您檢查電腦是否符合 Docker 安裝詳細資訊中所述的系統需求。

   您也可以在 Docker 桌面的設定中增加記憶體用量需求。在 Docker 服務的免費可用用量限制之外，您必須負責 Docker 的用量需求。請參閱 [Docker 訂閱](https://docs.docker.com/subscription/)。

   檢查 Docker 桌面狀態為「執行中」。

1. 佈建 Amazon Kendra 智慧型排名和您的[容量](https://docs.aws.amazon.com/kendra/latest/dg/adjusting-capacity.html)需求。佈建 Amazon Kendra Intelligent Ranking 後，會根據您設定的容量單位，按小時向您收費。請參閱[免費方案和定價資訊](https://aws.amazon.com/kendra/intelligent-ranking-pricing/)。

   您可以使用 [CreateRescoreExecutionPlan](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Ranking_CreateRescoreExecutionPlan.html) API 來佈建 `Rescore API`。如果您不需要比單一單位預設值更多的容量單位，請勿新增更多單位，並僅提供重新評分執行計畫的名稱。您也可以使用 [UpdateRescoreExecutionPlan](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Ranking_UpdateRescoreExecutionPlan.html) API 來更新容量需求。如需詳細資訊，請參閱[對搜尋服務的結果進行語意排名](https://docs.aws.amazon.com/kendra/latest/dg/search-service-rerank.html)。

   或者，您也可以前往步驟 3，在執行快速啟動 Bash 指令碼時建立預設的重新評分執行計畫。

   對於步驟 4，請注意回應中包含的重新評分執行計畫 ID。

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

   ```
   aws kendra-ranking create-rescore-execution-plan \
     --name MyRescoreExecutionPlan \ 
     --capacity-units '{"RescoreCapacityUnits":<integer number of additional capacity units>}'
    
   Response:
    
   {
       "Id": "<rescore execution plan ID>",
       "Arn": "arn:aws:kendra-ranking:<region>:<account-id>:rescore-execution-plan/<rescore-execution-plan-id>"
   }
   ```

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

   ```
   import boto3
   from botocore.exceptions import ClientError
   import pprint
   import time
   
   kendra_ranking = boto3.client("kendra-ranking")
   
   print("Create a rescore execution plan.")
   
   # Provide a name for the rescore execution plan
   name = "MyRescoreExecutionPlan"
   # Set your required additional capacity units
   # Don't set capacity units if you don't require more than 1 unit given by default
   capacity_units = 1
   
   try:
       rescore_execution_plan_response = kendra_ranking.create_rescore_execution_plan(
           Name = name,
           CapacityUnits = {"RescoreCapacityUnits":capacity_units}
       )
   
       pprint.pprint(rescore_execution_plan_response)
   
       rescore_execution_plan_id = rescore_execution_plan_response["Id"]
   
       print("Wait for Amazon Kendra to create the rescore execution plan.")
   
       while True:
           # Get the details of the rescore execution plan, such as the status
           rescore_execution_plan_description = kendra_ranking.describe_rescore_execution_plan(
               Id = rescore_execution_plan_id
           )
           # When status is not CREATING quit.
           status = rescore_execution_plan_description["Status"]
           print(" Creating rescore execution plan. Status: "+status)
           time.sleep(60)
           if status != "CREATING":
               break
   
   except ClientError as e:
           print("%s" % e)
   
   print("Program ends.")
   ```

------

1. 從主分支下拉式清單中選取版本分支，從 GitHub 為您的 OpenSearch 版本下載[快速入門 Bash 指令碼](https://github.com/opensearch-project/search-processor/tree/main/helpers)。

   此指令碼會使用您在 GitHub 儲存庫上為指令碼選取的版本，針對 OpenSearch 和 OpenSearch Dashboards 使用 Docker 映像。它會下載 Intelligent Ranking 外掛程式的 zip 檔案，並產生 `Dockerfile`以建置包含外掛程式之 OpenSearch 的新 Docker 映像。它也會建立 [docker-compose.yml](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html#docker-compose-opensearch-example) 檔案，其中包含使用 Intelligent Ranking 外掛程式和 OpenSearch Dashboards 的 OpenSearch 容器。指令碼會將您的 rescore 執行計畫 ID、區域資訊和端點 （使用區域） 新增至 docker-compose.yml 檔案。然後，指令碼會執行 `docker-compose up`以啟動包含智慧型排名的 OpenSearch 容器和 OpenSearch Dashboards。若要停止容器而不將其移除，請執行 `docker-compose stop`。若要移除容器，請執行 `docker-compose down`。

1. 開啟終端機，並在 Bash 指令碼的 目錄中執行下列命令。

   ```
   bash search_processing_kendra_quickstart.sh -p <execution-plan-id> -r <region>
   ```

   當您執行此命令時，請提供您在佈建 Amazon Kendra Intelligent Ranking 時在步驟 2 中記下的重新評分執行計畫 ID，以及您的區域資訊。或者，您可以使用 `--create-execution-plan`選項改為佈建 Amazon Kendra Intelligent Ranking。這會建立具有預設名稱和預設容量的重新評分執行計畫。

   若要在移除預設暫時性容器時不會遺失索引，您可以使用 `--volume-name`選項提供資料磁碟區名稱，讓索引在執行期間持續存在。如果您先前已建立索引，您可以在 docker-compose.yml 或 opensearch.yml 檔案中指定磁碟區。若要保持磁碟區完整，**請勿**執行 `docker-compose down -v`。

   快速入門 Bash 指令碼會在 OpenSearch 金鑰存放區中設定您的 AWS 登入資料，以連線至 Amazon Kendra Intelligent Ranking。若要將您的 AWS 登入資料提供給指令碼，請使用 `--profile`選項來指定 AWS 設定檔。如果未指定 `--profile`選項，則快速啟動 Bash 指令碼會嘗試從環境變數讀取 AWS 登入資料 （存取/私密金鑰、選用工作階段字符），然後從預設 AWS 設定檔讀取登入資料。如果未指定 `--profile`選項，且找不到登入資料，則指令碼不會將登入資料傳遞至 OpenSearch 金鑰存放區。如果 OpenSearch 金鑰存放區中未指定登入資料，則外掛程式仍會檢查[預設登入資料提供者鏈結](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-chain.html)中的登入資料，包括容器 Amazon ECS 登入資料或透過 Amazon EC2 中繼資料服務傳遞的執行個體設定檔登入資料。

   請確定您已建立具有必要許可的 IAM 角色，以叫用 Amazon Kendra Intelligent Ranking。以下是授予許可以使用 `Rescore` API 進行特定重新評分執行計畫 IAM 的政策範例：

### docker-compose.yml 的範例
<a name="docker-compose-opensearch-example"></a>

使用 OpenSearch 2.4.0 或更新版本搭配 Intelligent Ranking 外掛程式和 OpenSearch Dashboards 2.4.0 或更新版本的 docker-compose.yml 檔案範例。

```
version: '3'
networks:
  opensearch-net:
volumes: 
  <volume-name>:
services:
  opensearch-node:
    image: <Docker image tag name of OpenSearch with Intelligent Ranking plugin>
    container_name: opensearch-node
    environment: 
      - cluster.name=opensearch-cluster
      - node.name=opensearch-node
      - discovery.type=single-node
      - kendra_intelligent_ranking.service.endpoint=https://kendra-ranking.<region>.api.aws
      - kendra_intelligent_ranking.service.region=<region>
      - kendra_intelligent_ranking.service.execution_plan_id=<rescore-execution-plan-id>
    ulimits:
      memlock:
        soft: -1
        hard: -1
      nofile:
        soft: 65536
        hard: 65536
    ports:
      - 9200:9200
      - 9600:9600
    networks:
      - opensearch-net
  volumes:
    <docker-volume-name>:/usr/share/opensearch/data 
  opensearch-dashboard:
   image: opensearchproject/opensearch-dashboards:<your-version>
   container_name: opensearch-dashboards
   ports:
     - 5601:5601
   environment:
     OPENSEARCH_HOSTS: '["https://opensearch-node:9200"]'
   networks:
     - opensearch-net
```

### Dockerfile 和建置映像的範例
<a name="dockerfile-build-opensearch-example"></a>

`Dockerfile` 使用 OpenSearch 2.4.0 或更新版本搭配 Intelligent Ranking 外掛程式的 範例。

```
FROM opensearchproject/opensearch:<your-version>
RUN /usr/share/opensearch/bin/opensearch-plugin install --batch  https://github.com/opensearch-project/search-processor/releases/download/<your-version>/search-processor.zip
```

使用 Intelligent Ranking 外掛程式為 OpenSearch 建置 Docker 映像。

```
docker build --tag=<Docker image tag name of OpenSearch with Intelligent Ranking plugin>
```

## 與智慧型搜尋外掛程式互動
<a name="interact-opensearch-rerank-plugin"></a>

使用 Intelligent Ranking 外掛程式設定 OpenSearch （自我管理） 後，您可以使用 curl 命令或 OpenSearch 用戶端程式庫與外掛程式互動。使用 Intelligent Ranking 外掛程式存取 OpenSearch 的預設登入資料是使用者名稱 'admin' 和密碼 'admin'。

若要將 Intelligent Ranking 外掛程式設定套用至 OpenSearch 索引：

------
#### [ Curl ]

```
curl -XPUT "https://localhost:9200/<your-docs-index>/_settings" -u 'admin:admin' --insecure -H 'Content-Type: application/json' -d'
{
  "index": {
    "plugin" : {
      "searchrelevance" : {
        "result_transformer" : {
          "kendra_intelligent_ranking": {
              "order": 1,
              "properties": {
                "title_field": "title_field_name_here",
                "body_field": "body_field_name_here"
              }
          }
        }
      }
    }
  }
}
'
```

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

```
pip install opensearch-py

from opensearchpy import OpenSearch
host = 'localhost'
port = 9200
auth = ('admin', 'admin')

client = OpenSearch(
    hosts = [{'host': host, 'port': port}],
    http_compress = True, # enables gzip compression for request bodies
    http_auth = auth,
    # client_cert = client_cert_path,
    # client_key = client_key_path,
    use_ssl = True,
    verify_certs = False,
    ssl_assert_hostname = False,
    ssl_show_warn = False,
    ca_certs = ca_certs_path
)

setting_body = {
    "index": {
        "plugin" : {
            "searchrelevance" : {
                "result_transformer" : {
                    "kendra_intelligent_ranking": {
                            "order": 1,
                            "properties": {
                                "title_field": "title_field_name_here",
                                "body_field": "body_field_name_here"
                            }
                    }
                }
            }
        }
    }
}

response = client.indices.put_settings(index_name, body=setting_body)
```

------

您必須包含要用來重新排名的主要文字欄位名稱，例如文件內文或文件內容欄位。您也可以包含其他文字欄位，例如文件標題或文件摘要。

現在，您可以發出任何查詢，並使用 Intelligent Ranking 外掛程式對結果進行排名。

------
#### [ Curl ]

```
curl -XGET "https://localhost:9200/<your-docs-index>/_search?pretty" -u 'admin:admin' --insecure -H 'Content-Type: application/json' -d'
{
  "query" : {
    "match" : {
      "body_field_name_here": "intelligent systems"
    }
  }
}
'
```

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

```
from opensearchpy import OpenSearch
host = 'localhost'
port = 9200
auth = ('admin', 'admin')

client = OpenSearch(
    hosts = [{'host': host, 'port': port}],
    http_compress = True, # enables gzip compression for request bodies
    http_auth = auth,
    # client_cert = client_cert_path,
    # client_key = client_key_path,
    use_ssl = True,
    verify_certs = False,
    ssl_assert_hostname = False,
    ssl_show_warn = False,
    ca_certs = ca_certs_path
)

query = {
  'size': 10,
  "query" : {
    "match" : {
      "body_field_name_here": "intelligent systems"
    }
  }
}

response = client.search(
    body = query,
    index = index_name
)

print('\nSearch results:')
print(response)
```

------

若要移除 OpenSearch 索引的 Intelligent Ranking 外掛程式設定：

------
#### [ Curl ]

```
curl -XPUT "http://localhost:9200/<your-docs-index>/_settings" -H 'Content-Type: application/json' -d'
{
  "index": {
    "plugin": {
      "searchrelevance": {
        "result_transformer": {
          "kendra_intelligent_ranking.*": null
        }
      }
    }
  }
}
'
```

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

```
from opensearchpy import OpenSearch
host = 'localhost'
port = 9200
auth = ('admin', 'admin')

client = OpenSearch(
    hosts = [{'host': host, 'port': port}],
    http_compress = True, # enables gzip compression for request bodies
    http_auth = auth,
    # client_cert = client_cert_path,
    # client_key = client_key_path,
    use_ssl = True,
    verify_certs = False,
    ssl_assert_hostname = False,
    ssl_show_warn = False,
    ca_certs = ca_certs_path
)

setting_body = {
  "index": {
    "plugin": {
      "searchrelevance": {
        "result_transformer": {
          "kendra_intelligent_ranking.*": null
        }
      }
    }
  }
}

response = client.indices.put_settings(index_name, body=setting_body)
```

------

若要在特定查詢上測試 Intelligent Ranking 外掛程式，或在特定內文和標題欄位上測試：

------
#### [ Curl ]

```
curl -XGET "https://localhost:9200/<your-docs-index>/_search?pretty" -u 'admin:admin' --insecure -H 'Content-Type: application/json' -d'
{
  "query": {
    "multi-match": {
      "query": "intelligent systems",
      "fields": ["body_field_name_here", "title_field_name_here"]
    }
  },
  "size": 25,
  "ext": {
    "search_configuration": {
      "result_transformer": {
        "kendra_intelligent_ranking": {
          "order": 1,
          "properties": {
            "title_field": "title_field_name_here",
            "body_field": "body_field_name_here"
          }
        }
      }
    }
  }
}
'
```

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

```
from opensearchpy import OpenSearch
host = 'localhost'
port = 9200
auth = ('admin', 'admin')

client = OpenSearch(
    hosts = [{'host': host, 'port': port}],
    http_compress = True, # enables gzip compression for request bodies
    http_auth = auth,
    # client_cert = client_cert_path,
    # client_key = client_key_path,
    use_ssl = True,
    verify_certs = False,
    ssl_assert_hostname = False,
    ssl_show_warn = False,
    ca_certs = ca_certs_path
)

# Index settings null for kendra_intelligent_ranking

query = {
  "query": {
    "multi_match": {
      "query": "intelligent systems",
      "fields": ["body_field_name_here", "title_field_name_here"] 
    }
  },
  "size": 25,
  "ext": {
    "search_configuration": {
      "result_transformer": {
        "kendra_intelligent_ranking": {
          "order": 1,
          "properties": {
            "title_field": "title_field_name_here",
            "body_field": "body_field_name_here"
          }
        }
      }
    }
  }
}

response = client.search(
    body = query,
    index = index_name
)

print('\nSearch results:')
print(response)
```

------

## 比較 OpenSearch 結果與 Amazon Kendra 結果
<a name="compare-opensearch-rerank-plugin"></a>

您可以side-by-side比較 OpenSearch （自我管理） 排名結果 Amazon Kendra與重新排名的結果。OpenSearch Dashboards 2.4.0 版和更新版本提供side-by-side結果，讓您可以比較 OpenSearch 如何對文件進行排名，以及 Amazon Kendra 外掛程式如何對文件進行排名以進行搜尋查詢。

在您可以將 OpenSearch 排名結果與 Amazon Kendra 重新排名的結果進行比較之前，請確定您的 OpenSearch Dashboards 由具有 Intelligent Ranking 外掛程式的 OpenSearch 伺服器提供支援。您可以使用 Docker 和快速啟動 Bash 指令碼進行設定。請參閱 [設定智慧型搜尋外掛程式](#setup-opensearch-rerank-plugin)。

以下概述如何在 OpenSearch Dashboards 中比較 OpenSearch 和 Amazon Kendra 搜尋結果。如需詳細資訊，請參閱 [OpenSearch 文件](https://opensearch.org/docs/latest/search-plugins/search-relevance)。

**在 OpenSearch Dashboards 中比較搜尋結果**

1. 開啟 http://localhost:5601 並登入 OpenSearch Dashboards。預設登入資料是使用者名稱 'admin' 和密碼 'admin'。

1. 從導覽功能表中的 OpenSearch 外掛程式中選取**搜尋關聯**。

1. 在搜尋列中輸入搜尋文字。

1. 選取**查詢 1 **的索引，然後在 OpenSearch Query DSL 中輸入查詢。您可以使用 `%SearchText%`變數來參考您在搜尋列中輸入的搜尋文字。如需此查詢的範例，請參閱 [OpenSearch 文件](https://opensearch.org/docs/latest/search-plugins/search-relevance/compare-search-results/#reranking-results-with-amazon-kendra-intelligent-ranking-for-opensearch)。此查詢傳回的結果是未使用 Intelligent Ranking 外掛程式的 OpenSearch 結果。

1. 選取**查詢 2 **的相同索引，然後在 OpenSearch Query DSL 中輸入相同的查詢。此外，使用 加入 擴充功能，`kendra_intelligent_ranking`並指定`body_field`要排名的強制性 。您也可以指定標題欄位，但內文欄位是強制性的。如需此查詢的範例，請參閱 [OpenSearch 文件](https://opensearch.org/docs/latest/search-plugins/search-relevance/compare-search-results/#reranking-results-with-amazon-kendra-intelligent-ranking-for-opensearch)。此查詢傳回的結果是使用 Intelligent Ranking 外掛程式 Amazon Kendra 重新排名的結果。外掛程式最多可排名 25 個結果。

1. 選取**搜尋**以傳回和比較結果。