

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon Kendra セルフマネージド OpenSearch のインテリジェントランキング
<a name="opensearch-rerank"></a>

 Amazon Kendraのセマンティック検索機能を活用して、Apache 2.0 ライセンスに基づくセルフマネージドオープンソース検索サービスである [OpenSearch](https://opensearch.org/docs/latest) の検索結果を改善できます。 Amazon Kendra インテリジェントランキングプラグインは、 Amazon Kendraを使用して OpenSearch の結果をセマンティックに再度ランク付けします。これは、デフォルトの OpenSearch 検索結果に含まれる特定のフィールド (ドキュメント本文やタイトルなど) を使用する検索クエリの意味とコンテキストを理解することで行われます。

例えば、「メインキーノートアドレス」というクエリを考えてみましょう。「アドレス」にはいくつかの意味があるため、 はクエリの背後にある意味を推測して、意図した意味に沿った関連情報を返す Amazon Kendra ことができます。このコンテキストでは、これは会議の基調講演です。単純な検索サービスでは、その意図が考慮されず、例えばメインストリートの住所の結果が返される可能性があります。

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. 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 検索レスポンス内の検索結果を、新しいセマンティックランキングを反映するように再配置します。

インテリジェントランキングプラグインは、「本文」と「タイトル」フィールドを使用して結果を再度ランク付けします。これらのプラグインフィールドは、ドキュメントの本文とタイトルの定義に最も合う OpenSearch インデックスのフィールドにマッピングできます。例えば、索引に「chapter\$1heading」や「chapter\$1contents」のようなフィールドを含む本の章が含まれている場合、前者を「タイトル」に、後者を「本文」にマッピングすると、最良の結果が得られます。

## インテリジェント検索プラグインの設定
<a name="setup-opensearch-rerank-plugin"></a>

インテリジェントランキングプラグインを使って OpenSearch (セルフマネージド) をすばやくセットアップする方法を以下に概説します。

**インテリジェントランキングプラグイン (Quick Setup) を使って 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 を参照してください。

2.4.0 より古いバージョンの `opensearch` Docker イメージを以前にダウンロードしていた場合は、Docker `opensearch:2.4.0` イメージ以降を使用し、インテリジェントランキングプラグインが含まれた新しいイメージを構築する必要があります。

1. オペレーティングシステム用の [Docker デスクトップ](https://docs.docker.com/get-docker/) をダウンロードしてインストールします。Docker デスクトップには Docker Compose と Docker Engine が含まれています。お使いのコンピュータが Docker インストールの詳細に記載されているシステム要件を満たしているかどうかを確認することをお勧めします。

   Docker デスクトップの設定でメモリ使用量の要件を増やすこともできます。Docker サービスの無料使用制限以外の Docker の使用要件については、お客様の責任となります。「[Docker サブスクリプション](https://docs.docker.com/subscription/)」を参照してください。

   Docker デスクトップのステータスが「実行中」であることを確認します。

1. Intelligent Ranking 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 API](https://docs.aws.amazon.com/kendra/latest/APIReference/API_Ranking_UpdateRescoreExecutionPlan.html) を使用してキャパシティー要件を更新することもできます。詳細については、「[検索サービスの結果をセマンティックにランク付けする](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. メインブランチのドロップダウンからバージョンブランチを選択して、お使いの OpenSearch バージョン用の[クイックスタート Bash スクリプト](https://github.com/opensearch-project/search-processor/tree/main/helpers)を GitHub からダウンロードします。

   このスクリプトは、GitHub リポジトリでスクリプト用に選択したバージョンを使用して OpenSearch ダッシュボードと OpenSearch ダッシュボードに Docker イメージを使用します。このスクリプトは Intelligent Ranking プラグインの zip ファイルをダウンロードし、そのプラグインを含む OpenSearch の新しい Docker イメージを構築するための `Dockerfile` を生成します。また、インテリジェントランキングプラグインと OpenSearch ダッシュボードを使った OpenSearch 用のコンテナを含む [docker-compose.yml](https://docs.aws.amazon.com/kendra/latest/dg/opensearch-rerank.html#docker-compose-opensearch-example) ファイルも作成します。このスクリプトは、スコア実行プラン 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 Intelligent Ranking をプロビジョニングしたときにメモした再スコア実行プラン ID とリージョン情報を指定します。オプションで、代わりに `--create-execution-plan` オプションを使用して Amazon Kendra インテリジェントランキングをプロビジョニングすることもできます。これにより、デフォルトの名前とデフォルトのキャパシティーで再スコア実行プランが作成されます。

   デフォルトのエフェメラルコンテナが削除されてもインデックスが失われないようにするには、`--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 キーストアに認証情報が指定されていない場合でも、プラグインは Amazon EC2 、メタデータサービスを介して配信される Amazon ECS コンテナ認証情報やインスタンスプロファイル認証情報など、[デフォルトの認証情報プロバイダーチェーン](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/credentials-chain.html)内の認証情報をチェックします。

    Amazon Kendra Intelligent Ranking を呼び出すために必要なアクセス許可を持つ IAM ロールが作成されていることを確認します。以下は、特定の再スコア実行プランに `Rescore` API を使用するアクセス許可を付与する IAM ポリシーの例です。

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

OpenSearch 2.4.0 以降をインテリジェントランキングプラグインと OpenSearch ダッシュボード 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>

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>

OpenSearch (セルフマネージド) のランク付けされた結果を、 Amazon Kendra再ランク付けされた結果とside-by-side比較できます。OpenSearch Dashboards バージョン 2.4.0 以降では、結果を並べて表示できるため、OpenSearch がドキュメントをランク付けする方法と、 Amazon Kendra またはプラグインが検索クエリでドキュメントをランク付けする方法を比較できます。

OpenSearch のランク付けされた結果と Amazon Kendra 再ランク付けされた結果を比較する前に、OpenSearch Dashboards が Intelligent Ranking プラグインを備えた OpenSearch サーバーによってバックアップされていることを確認してください。これは Docker とクイックスタート Bash スクリプトを使用して設定できます。「[インテリジェント検索プラグインの設定](#setup-opensearch-rerank-plugin)」を参照してください。

以下に、OpenSearch ダッシュボードで OpenSearch と Amazon Kendra 検索結果を比較する方法の概要を示します。詳細については、[OpenSearch ドキュメント](https://opensearch.org/docs/latest/search-plugins/search-relevance) を参照してください。

**OpenSearch Dashboards での検索結果の比較**

1. http://localhost:5601 を開いて OpenSearch ダッシュボードにサインインします。デフォルトの認証情報は、ユーザー名は「admin」、パスワードは「admin」です。

1. ナビゲーションメニューの OpenSearch プラグインから **[検索関連性]** を選択します。

1. 検索バーに検索テキストを入力します。

1. **[クエリ 1]** のインデックスを選択し、OpenSearch クエリ DSL にクエリを入力します。この `%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]** のインデックスを選択し、OpenSearch クエリ 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. **[検索]** を選択すると、結果を返して比較できます。