

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

您可以利用 Amazon Kendra基于 Apache 2.0 许可证的自我管理开源搜索服务的语义搜索功能来改善搜索结果。[OpenSearch](https://opensearch.org/docs/latest) Amazon Kendra 智能排名插件在语义上使用对结果进行重新排名 OpenSearch。 Amazon Kendra它通过使用默认搜索结果中的特定字段（例如文档正文或标题）来理解 OpenSearch 搜索查询的含义和上下文。

以此查询为例：“main keynote address”。由于 “地址” 有多种含义，因此 Amazon Kendra 可以推断出查询背后的含义以返回与预期含义一致的相关信息。在这里的上下文中，它是指会议主题演讲。例如，更简单的搜索服务可能不会考虑实际意图，而是返回 Main Street 的街道地址作为结果。

的智能排名插件可用 OpenSearch 于 OpenSearch （自我管理）版本 2.4.0 及更高版本。您可以使用快速入门 Bash 脚本安装插件，以构建包含智能排名插件 OpenSearch 的新 Docker 镜像。请参阅 [设置智能搜索插件](#setup-opensearch-rerank-plugin) - 这是一个帮助您快速启动和运行的设置示例。

## 智能搜索插件的工作原理
<a name="how-opensearch-rerank-plugin-works"></a>

 OpenSearch （自我管理）智能排名插件的整体流程如下：

1.  OpenSearch 用户发出查询，并 OpenSearch 提供查询响应或与查询相关的文档列表。

1. 智能排名插件获取查询响应并从文档中提取信息。

1. 智能排名插件调用 Amazon Kendra 智能排名的 [Rescore](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Ranking_Rescore.html) API。

1. `Rescore` API 使用从文档中提取的信息并从语义上对搜索结果进行重新排名。

1. `Rescore` API 将重新排名的搜索结果发送回插件。该插件会重新排列搜索响应中的 OpenSearch 搜索结果，以反映新的语义排名。

智能排名插件使用“body”和“title”字段对结果进行重新排名。这些插件字段可以映射到 OpenSearch 索引中最符合文档正文和标题定义的字段。例如，如果您的索引包含一本书的章节，其中包含“chapter\$1heading”和“chapter\$1contents”之类的字段，则可以将前者映射到“title”，将后者映射到“body”以获得最佳结果。

## 设置智能搜索插件
<a name="setup-opensearch-rerank-plugin"></a>

以下内容概述了如何使用智能排名插件快速设置 OpenSearch （自我管理）。

**使用智能排名插件进行设置 OpenSearch （自我管理）（快速设置）**

如果你已经在使用 Docker 镜像`opensearch:2.4.0`，你可以使用这个 [Dockerfile](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html#dockerfile-build-opensearch-example) 通过智能排名插件构建 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` Docker 映像版本低于 2.4.0，则必须使用 Docker 映像 `opensearch:2.4.0` 或更高版本，并使用随附的智能排名插件构建新映像。

1. 下载并安装适用于您的操作系统的 [Docker 桌面](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 智能排名后，将根据您设定的容量单位按小时收费。查看[免费套餐和价格信息](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)。

   或者，在运行快速入门 Bash 脚本时，您可以转到步骤 3 来创建默认的重新评分执行计划。

   请注意步骤 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)。

   此脚本使用 Docker 映像 OpenSearch 和 OpenSearch 仪表板，使用您在 GitHub 存储库中为脚本选择的版本。它会下载智能排名插件的 zip 文件，并生成一个`Dockerfile`用于构建包含 OpenSearch 该插件的新 Docker 镜像。它还会创建一个 [docker-compose.yml](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html#docker-compose-opensearch-example) 文件，其中包含 OpenSearch 带有智能排名插件和仪表板的容器。 OpenSearch 此脚本会将您的重新评分执行计划 ID、区域信息和端点（使用该区域）添加到 docker-compose.yml 文件中。然后，脚本运行`docker-compose up`以启动包含智能排名和 OpenSearch 仪表板的容器。 OpenSearch 要停止容器而不将其移除，请运行 `docker-compose stop`。要移除容器，请运行 `docker-compose down`。

1. 打开终端，在 Bash 脚本的目录中运行以下命令。

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

   运行此命令时，您需要提供您在步骤 2 中预置 Amazon Kendra 智能排名时记下的重新评分执行计划 ID 以及您的区域信息。或者，您也可以改为使用 `--create-execution-plan` 选项预配置 Amazon Kendra 智能排名。这会创建一个具有默认名称和默认容量的重新评分执行计划。

   为了在移除默认的临时容器时不丢失索引，您可以使用 `--volume-name` 选项提供数据卷名称，从而使索引在执行期间保持不变。如果您之前创建了索引，则可以在 docker-compose.yml 或 opensearch.yml 文件中指定卷。要保持卷完整，请**不要**运行 `docker-compose down -v`。

   快速入门 Bash 脚本在 OpenSearch 密钥库中配置您的 AWS 凭据以连接到智能排名。 Amazon Kendra 要向脚本提供 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 元数据服务提供的实例配置文件凭证。

   请确保您已创建具有调用 Amazon Kendra 智能排名的必要权限的 IAM 角色。以下是授予将 `Rescore` API 用于特定重新分数执行计划的权限的 IAM 策略示例：

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

使用 OpenSearch 2.4.0 或更高版本以及智能排名插件和仪表板 2.4.0 或更高版本的 docker-compose.yml 文件示例。 OpenSearch 

```
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>

在智能排名插件中使用 OpenSearch 2.4.0 或更高版本的示例。`Dockerfile`

```
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
```

 OpenSearch 使用智能排名插件构建 Docker 镜像。

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

## 与智能搜索插件交互
<a name="interact-opensearch-rerank-plugin"></a>

使用智能排名插件进行设置 OpenSearch （自我管理）后，即可使用 curl 命令或 OpenSearch 客户端库与该插件进行交互。使用智能排名插件进行访问 OpenSearch 的默认凭据是用户名 “admin” 和密码 “admin”。

要将智能排名插件设置应用于 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)
```

------

必须包括要用于重新排名的主文本字段的名称，例如，文档正文或文档内容字段。您还可以包括其他文本字段，例如，文档标题或文档摘要。

现在，您可以发出任何查询，并使用智能排名插件对结果进行排名。

------
#### [ 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 索引的智能排名插件设置，请执行以下操作：

------
#### [ 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)
```

------

要对特定查询测试智能排名插件或对某些正文和标题字段进行测试，请执行以下操作：

------
#### [ 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 仪表板版本 2.4.0 及更高版本提供了 side-by-side结果，因此您可以将文档的 OpenSearch 排名方式 Amazon Kendra 与插件对搜索查询中的文档排名方式进行比较。

在将 OpenSearch 排名结果与 Amazon Kendra 重新排名的结果进行比较之前，请确保您的 OpenSearch 仪表板由带有智能排名插件的 OpenSearch 服务器提供支持。您可以使用 Docker 和快速入门 Bash 脚本进行设置。请参阅[设置智能搜索插件](#setup-opensearch-rerank-plugin)。

以下内容概述了如何在 OpenSearch 仪表板中比较 OpenSearch 和 Amazon Kendra 搜索结果。有关更多信息，请参阅 [OpenSearch 文档](https://opensearch.org/docs/latest/search-plugins/search-relevance)。

**比较 OpenSearch 仪表板中的搜索结果**

1. 打开 http://localhost:5601 并登录 OpenSearch 控制面板。默认凭证是用户名“admin”和密码“admin”。

1. 从导航菜单的 OpenSearch 插件中选择 “**搜索相关性**”。

1. 在搜索栏中输入搜索文本。

1. 为**查询 1** 选择您的索引，然后在查询 DSL 中输入 OpenSearch 查询。您可以使用 `%SearchText%` 变量来引用在搜索栏中输入的搜索文本。有关此查询的示例，请参阅[OpenSearch 文档](https://opensearch.org/docs/latest/search-plugins/search-relevance/compare-search-results/#reranking-results-with-amazon-kendra-intelligent-ranking-for-opensearch)。此查询返回的结果是未使用智能排名插件的 OpenSearch 结果。

1. 为**查询 2** 选择相同的索引，然后在查询 DSL 中输入相同的 OpenSearch 查询。此外，在扩展中包含 `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)。此查询返回的结果是使用智能 Amazon Kendra 排名插件重新排名的结果。该插件最多可对 25 个结果进行排名。

1. 选择**搜索**以返回和比较结果。