

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 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 도메인을 생성하는 데 최대 15분이 걸릴 수 있으며, 그 후 AWS AppSync 데이터 소스와 통합할 수 있습니다.

```
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 OpenSearch Service 콘솔을 통해 수정할 수 있는 자체 **액세스 정책**이 있습니다. 사용자는 OpenSearch Service 도메인에 대한 적정 작업 및 리소스를 사용하여 아래와 비슷한 정책을 추가해야 합니다. 보안 **주체**는 AWS AppSync 데이터 소스 역할이며, 이는 해당 콘솔에서 생성하도록 허용한 경우 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 콘솔의 **스키마** 편집기에서 `searchPosts` 쿼리를 포함하도록 이전 `Posts` 스키마를 수정합니다.

```
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` 필드에 대한 쿼리 용어로 채워져서 클라이언트에서 인수로 전달됩니다. 선택 사항으로 표준 텍스트와 같이 미리 채워진 정보를 사용할 수도 있습니다.

## 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`를 업데이트해야 합니다. 이 예는 요청 핸들러에서 `ctx.args`로 작성할 수도 있는 `context.arguments`를 사용하는 방법도 보여줍니다.

## 단일 문서 가져오기
<a name="retrieving-a-single-document-js"></a>

마지막으로 스키마의 `getPost(id:ID)` 쿼리를 사용하여 개별 문서를 반환하려면 AWS AppSync 콘솔의 **스키마** 편집기에서이 쿼리를 찾아 **연결을** 선택합니다. 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)에서 설명했듯이 OpenSearch Service를 Amazon DynamoDB와 함께 사용할 수도 있습니다.
+  AWS AppSync 서비스 역할이 클러스터에 액세스할 수 있도록 허용해야만 도메인에 대한 액세스 권한을 부여합니다.
+ 최저 비용 클러스터를 제공하는 간단한 개발부터 시작하여, 프로덕션으로 들어가면서 고가용성(HA)을 제공하는 대규모 클러스터로 이동할 수 있습니다.