

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

# AWS AppSync での Amazon OpenSearch Service リゾルバーの使用
<a name="tutorial-elasticsearch-resolvers-js"></a>

AWS AppSync は、VPC 内に存在しない場合、独自の AWS アカウントでプロビジョニングしたドメインからの Amazon OpenSearch Service の使用をサポートします。ドメインをプロビジョニングした後、データソースを使用してそれに接続できます。この時点で、スキーマにリゾルバーを設定し、クエリ、ミューテーション、サブスクリプションなどの GraphQL 処理を実行することができます。このチュートリアルでは、いくつかの一般的な例を説明します。

詳細については、[「OpenSearch 用の JavaScript リゾルバー関数リファレンス」](https://docs.aws.amazon.com/appsync/latest/devguide/resolver-reference-elasticsearch-js.html)を参照してください。

## 新しい OpenSearch Service ドメインを作成する
<a name="create-a-new-es-domain-js"></a>

このチュートリアルを開始するには、既存の OpenSearch Service ドメインが必要です。ドメインがない場合は、次のサンプルが使用できます。OpenSearch Service ドメインが作成されるまで、 AWS AppSync データソースとの統合に進むまでに最大 15 分かかる場合があります。

```
aws cloudformation create-stack --stack-name AppSyncOpenSearch \
--template-url https://s3.us-west-2.amazonaws.com/awsappsync/resources/elasticsearch/ESResolverCFTemplate.yaml \
--parameters ParameterKey=OSDomainName,ParameterValue=ddtestdomain ParameterKey=Tier,ParameterValue=development \
--capabilities CAPABILITY_NAMED_IAM
```

アカウントの US-West-2 (オレゴン) リージョンで次の AWS CloudFormation スタックを起動できます AWS 。

 [https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/elasticsearch/ESResolverCFTemplate.yaml](https://console.aws.amazon.com/cloudformation/home?region=us-west-2#/stacks/new?templateURL=https://s3.us-west-2.amazonaws.com/awsappsync/resources/elasticsearch/ESResolverCFTemplate.yaml)

## OpenSearch Service 用のデータソースの設定
<a name="configure-data-source-for-es-js"></a>

OpenSearch Service ドメインを作成したら、 AWS AppSync GraphQL API に移動し、**データソース**タブを選択します。**[データソースの作成]** を選択して、データソースに「*oss*」などのわかりやすい名前を入力します。次に、[**データソースタイプ**] に [**Amazon OpenSearch ドメイン**] を選択し、適切なリージョンを選択します。OpenSearch Service ドメインがリストに表示されます。選択したら、新しいロールを作成するか、 AWS AppSync がロールに適切なアクセス許可を割り当てるか、次のインラインポリシーを持つ既存のロールを選択できます。

また、そのロールに対して AWS AppSync との信頼関係を設定する必要があります。

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "appsync.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

------

さらに、OpenSearch Service ドメインには独自の**アクセスポリシー**があり、Amazon Amazon OpenSearch Service コンソールから変更できます。OpenSearch Service ドメインの適切なアクションとリソースを用いて、以下のようなポリシーを追加する必要があります。**プリンシパル**は AWS AppSync データソースロールになることに注意してください。プリンシパルは、IAM コンソールに作成させると、IAM コンソールに表示されます。

## リゾルバーを接続する
<a name="connecting-a-resolver-js"></a>

これで、データソースが OpenSearch Service ドメインに接続されたので、リゾルバーを使用して、以下の例のようにデータソースを GraphQL スキーマに接続することができます。

```
 type Query {
   getPost(id: ID!): Post
   allPosts: [Post]
 }

 type Mutation {
   addPost(id: ID!, author: String, title: String, url: String, ups: Int, downs: Int, content: String): AWSJSON
 }

type Post {
  id: ID!
  author: String
  title: String
  url: String
  ups: Int
  downs: Int
  content: String
}
```

`Post` フィールドを含むユーザー定義の `id` 型があることに注意してください。次の例では、この型を OpenSearch Service ドメインに配置するプロセス (自動化可能) があることを前提としています。このプロセスでは、`/post/_doc` へのルートパスをマッピングします。`post` はインデックスです。このルートパスから、個々のドキュメントの検索、`/id/post*` によるワイルドカード検索、`/post/_search` の パスを使用した複数ドキュメントの検索が行うことができます。例えば、同じインデックス `user` でインデックスが付けられた `User` という別の型がある場合は、`/user/_search` の **パス**を使用して複数ドキュメントが検索できます。

 AWS AppSync コンソールの**スキーマ**エディタで、前述の`Posts`スキーマを変更して`searchPosts`クエリを含めます。

```
type Query {
  getPost(id: ID!): Post
  allPosts: [Post]
  searchPosts: [Post]
}
```

スキーマを保存します。「**リゾルバー**」ペインで `searchPosts` を見つけ、「**アタッチ**」を選択します OpenSearch Service のデータソースを選択し、リゾルバーを保存します。以下のスニペットを使用してリゾルバーのコードを更新してください。

```
import { util } from '@aws-appsync/utils'

/**
 * Searches for documents by using an input term
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the request
 */
export function request(ctx) {
	return {
		operation: 'GET',
		path: `/post/_search`,
		params: { body: { from: 0, size: 50 } },
	}
}

/**
 * Returns the fetched items
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the result
 */
export function response(ctx) {
	if (ctx.error) {
		util.error(ctx.error.message, ctx.error.type)
	}
	return ctx.result.hits.hits.map((hit) => hit._source)
}
```

これは、前述のスキーマの `post` フィールドの下に OpenSearch Service でインデックス化されたドキュメントがあることを前提としています。データ構造が異なる場合は、更新が必要です。

## 検索を変更する
<a name="modifying-your-searches-js"></a>

前述のリゾルバーリクエストハンドラーは、すべてのレコードに簡単なクエリを実行します。今、特定の筆者で検索する場合を考えます。また、その筆者を、GraphQL クエリに定義した引数にするとします。 AWS AppSync コンソールの**スキーマ**エディタで、`allPostsByAuthor`クエリを追加します。

```
type Query {
  getPost(id: ID!): Post
  allPosts: [Post]
  allPostsByAuthor(author: String!): [Post]
  searchPosts: [Post]
}
```

「**リゾルバー**」ペインで `allPostsByAuthor` を見つけて「**アタッチ**」を選択します。OpenSearch Service のデータソースを選択し、以下のコードを使用してください。

```
import { util } from '@aws-appsync/utils'

/**
 * Searches for documents by `author`
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the request
 */
export function request(ctx) {
	return {
		operation: 'GET',
		path: '/post/_search',
		params: {
			body: {
				from: 0,
				size: 50,
				query: { match: { author: ctx.args.author } },
			},
		},
	}
}

/**
 * Returns the fetched items
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the result
 */
export function response(ctx) {
	if (ctx.error) {
		util.error(ctx.error.message, ctx.error.type)
	}
	return ctx.result.hits.hits.map((hit) => hit._source)
}
```

`body` には `author` フィールドを含む term クエリが含まれていることに注意してください。これは引数としてクライアントから渡されます。任意で、標準テキストなどの事前に入力された情報を追加することもできます。

## OpenSearch Service へのデータの追加
<a name="adding-data-to-es-js"></a>

GraphQL ミューテーションの結果、OpenSearch Service ドメインにデータの追加が必要になる場合があります。これは検索やその他の目的に非常に役立ちます。GraphQL サブスクリプションを使用して[データをリアルタイムで作成](aws-appsync-real-time-data.md)できるため、これは OpenSearch Service ドメインのデータの更新をクライアントに通知するメカニズムとして動作します。

 AWS AppSync コンソールの**スキーマ**ページに戻り、`addPost()`ミューテーションに**ア**タッチを選択します。OpenSearch Service のデータソースをもう一度選択し、以下のコードを使用してください。

```
import { util } from '@aws-appsync/utils'

/**
 * Searches for documents by `author`
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the request
 */
export function request(ctx) {
	return {
		operation: 'PUT',
		path: `/post/_doc/${ctx.args.id}`,
		params: { body: ctx.args },
	}
}

/**
 * Returns the inserted post
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the result
 */
export function response(ctx) {
	if (ctx.error) {
		util.error(ctx.error.message, ctx.error.type)
	}
	return ctx.result
}
```

以前と同様、これはデータ構造の一例です。別のフィールド名またはインデックスがある場合は、必要に応じて `path` と `body` を更新します。この例では `context.arguments` の使用方法も示しています。リクエストハンドラーは`ctx.args`と記述することもできます。

## 単一のドキュメントの取得
<a name="retrieving-a-single-document-js"></a>

最後に、スキーマで`getPost(id:ID)`クエリを使用して個々のドキュメントを返す場合は、 AWS AppSync コンソールの**スキーマ**エディタでこのクエリを検索し、**Attach** を選択します。OpenSearch Service のデータソースをもう一度選択し、以下のコードを使用してください。

```
import { util } from '@aws-appsync/utils'

/**
 * Searches for documents by `author`
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the request
 */
export function request(ctx) {
	return {
		operation: 'GET',
		path: `/post/_doc/${ctx.args.id}`,
	}
}

/**
 * Returns the post
 * @param {import('@aws-appsync/utils').Context} ctx the context
 * @returns {*} the result
 */
export function response(ctx) {
	if (ctx.error) {
		util.error(ctx.error.message, ctx.error.type)
	}
	return ctx.result._source
}
```

## クエリとミューテーションを実行する
<a name="tutorial-elasticsearch-resolvers-perform-queries-mutations-js"></a>

これで、OpenSearch Service ドメインに対して GraphQL 処理が実行できます。 AWS AppSync コンソールの**クエリ**タブに移動し、新しいレコードを追加します。

```
mutation AddPost {
    addPost (
        id:"12345"
        author: "Fred"
        title: "My first book"
        content: "This will be fun to write!"
        url: "publisher website",
        ups: 100,
        downs:20 
       )
}
```

ミューテーションの結果が右側に表示されます。同様に、OpenSearch Service ドメインに対して `searchPosts` クエリが実行できます。

```
query search {
    searchPosts {
        id
        title
        author
        content
    }
}
```

## ベストプラクティス
<a name="best-practices-js"></a>
+ OpenSearch Service はプライマリデータベースとしてではなく、データのクエリ発行のために使用します。「[GraphQL リゾルバーを組み合わせる](https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-combining-graphql-resolvers-js.html)」で説明したように、Amazon DynamoDB と組み合わせて OpenSearch Service を使用する場合があります。
+ ドメインへのアクセスを許可するには、 AWS AppSync サービスロールにクラスターへのアクセスを許可します。
+ 開発中は、最小限のコストのクラスターを使用して小規模で開始し、その後、本稼働への移行時に高可用性 (HA) を備えた大規模なクラスターへと移行することができます。