

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

# Amazon SNS 메시지 필터링
<a name="sns-message-filtering"></a>

기본적으로 Amazon SNS 주제 구독자는 주제에 게시된 모든 메시지를 수신합니다. 메시지의 하위 세트만 수신하려면 구독자는 주제 구독에 *필터 정책*을 할당해야 합니다.

필터링 정책은 구독자가 어떤 메시지를 수신할지 정의하는 속성을 포함하는 JSON 객체입니다. Amazon SNS는 구독에 설정한 필터 정책 범위에 따라 메시지 속성 또는 메시지 본문에 적용되는 정책을 지원합니다. 메시지 본문의 필터 정책에서는 메시지 페이로드가 올바른 형식의 JSON 객체라고 가정합니다.

구독에 필터 정책이 없는 경우 구독자는 해당 주제에 게시된 모든 메시지를 받습니다. 메시지를 주제에 게시하면 Amazon SNS는 메시지 속성 또는 본문을 각 주제의 구독에 대한 필터 정책에 있는 속성과 비교합니다. 모든 메시지 속성 또는 메시지 본문 속성이 필터 정책에 지정된 조건을 충족하는 경우 Amazon SNS는 구독자에게 메시지를 전송합니다. 그렇지 않으면 Amazon SNS는 해당 구독자에게 메시지를 보내지 않습니다.

자세한 정보는 [주제에 게시된 메시지 필터링](https://aws.amazon.com/getting-started/tutorials/filter-messages-published-to-topics/)을 참조하세요.

# Amazon SNS 구독 필터 정책 범위
<a name="sns-message-filtering-scope"></a>

`FilterPolicyScope` 구독 속성을 사용하면 다음 값 중 하나를 설정하여 필터링 범위를 정의할 수 있습니다.
+ `MessageAttributes` - 메시지 속성(기본 설정)에 필터 정책을 적용합니다.
+ `MessageBody` - 필터 정책이 메시지 본문에 적용됩니다.

**참고**  
기존 필터 정책에 대해 정의된 필터 정책 범위가 없는 경우 범위는 `MessageAttributes`로 기본 설정됩니다.

# Amazon SNS 구독 필터 정책
<a name="sns-subscription-filter-policies"></a>

구독 필터 정책을 사용하면 속성 이름을 지정하고 각 속성 이름에 값 목록을 지정할 수 있습니다. 자세한 내용은 [Amazon SNS 메시지 필터링](sns-message-filtering.md) 단원을 참조하십시오.

Amazon SNS는 구독 필터 정책을 기준으로 메시지 속성 또는 메시지 본문 속성을 평가할 때 정책에 지정되지 않은 메시지 속성이나 메시지 본문 속성을 무시합니다.

**중요**  
AWS IAM 및 Amazon SNS와 같은 서비스는 최종 일관성이라는 분산 컴퓨팅 모델을 사용합니다. 구독 필터 정책의 추가 또는 변경 사항이 완전히 적용되려면 최대 15분이 소요됩니다.

구독은 다음 조건에서 메시지를 수락합니다.
+ 필터 정책 범위를 `MessageAttributes`로 설정하면 필터 정책의 각 속성 이름을 메시지 속성 이름과 일치시킵니다. 필터 정책에서 일치하는 각 속성 이름에 대해 하나 이상의 속성 값을 메시지 속성 값과 일치시킵니다.
+ 필터 정책 범위를 `MessageBody`로 설정하면 필터 정책의 각 속성 이름을 메시지 본문 속성 이름과 일치시킵니다. 필터 정책에서 일치하는 각 속성 이름에 대해 하나 이상의 속성 값을 메시지 본문 속성 값과 일치시킵니다.

Amazon SNS에서는 현재 다음과 같은 필터 연산자를 지원합니다.
+ [AND 로직](and-or-logic.md#and-logic)
+ [OR 로직](and-or-logic.md#or-logic)
+ [OR 연산자](and-or-logic.md#or-operator)
+ [키 일치](attribute-key-matching.md)
+ [숫자 값 정확한 일치](numeric-value-matching.md#numeric-exact-matching)
+ [숫자 값 anything-but 일치](numeric-value-matching.md#numeric-anything-but-matching)
+ [숫자 값 범위 일치](numeric-value-matching.md#numeric-value-range-matching)
+ [문자열 값 정확한 일치](string-value-matching.md#string-exact-matching)
+ [문자열 값 anything-but 일치](string-value-matching.md#string-anything-but-matching)
+ [접두사와 anything-but 연산자를 사용한 문자열 일치](string-value-matching.md#string-anything-but-matching)
+ [문자열 값 equals-ignore case](string-value-matching.md#string-equals-ignore)
+ [문자열 값 IP 주소 일치](string-value-matching.md#string-address-matching)
+ [문자열 값 접두사 일치](string-value-matching.md#string-prefix-matching)
+ [문자열 값 접미사 일치](string-value-matching.md#string-suffix-matching)

# Amazon SNS 예제 필터 정책
<a name="example-filter-policies"></a>

다음 예제에서는 고객 트랜잭션을 처리하는 Amazon SNS 주제에서 전송된 메시지 페이로드를 보여 줍니다.

첫 번째 예에서 `MessageAttributes` 필드에는 트랜잭션을 설명하는 속성이 포함됩니다.
+ 고객의 관심사
+ 스토어 이름
+ 이벤트 상태
+ 구매 가격(USD)

이 메시지에는 `MessageAttributes` 필드가 포함되어 있으므로, 구독의 `FilterPolicyScope`가 `MessageAttributes`로 설정되어 있는 한 `FilterPolicy`가 설정된 주제 구독은 메시지를 선택적으로 수락 또는 거부할 수 있습니다. 메시지에 속성을 적용하는 방법에 대한 자세한 내용은 [Amazon SNS 메시지 속성](sns-message-attributes.md)에서 확인하세요.

```
{
   "Type": "Notification",
   "MessageId": "a1b2c34d-567e-8f90-g1h2-i345j67klmn8",
   "TopicArn": "arn:aws:sns:us-east-2:123456789012:MyTopic",
   "Message": "message-body-with-transaction-details",
   "Timestamp": "2019-11-03T23:28:01.631Z",
   "SignatureVersion": "4",
   "Signature": "signature",
   "UnsubscribeURL": "unsubscribe-url",
   "MessageAttributes": {
      "customer_interests": {
         "Type": "String.Array",
         "Value": "[\"soccer\", \"rugby\", \"hockey\"]"
      },
      "store": {
         "Type": "String",
         "Value":"example_corp"
      },
      "event": {
         "Type": "String",
         "Value": "order_placed"
      },
      "price_usd": {
         "Type": "Number", 
         "Value": "210.75"
      }
   }
}
```

다음 예에서는 `Message` 필드(메시지 페이로드** 또는 메시지 본문**이라고도 함)에 포함된 동일한 속성을 보여줍니다. `FilterPolicy`를 포함하는 모든 주제 구독은 구독의 `FilterPolicyScope`가 `MessageBody`로 설정되어 있는 한 메시지를 선택적으로 수락하거나 거부할 수 있습니다.

```
{
"Type": "Notification",
   "MessageId": "a1b2c34d-567e-8f90-g1h2-i345j67klmn8",
   "TopicArn": "arn:aws:sns:us-east-2:123456789012:MyTopic",
   "Message": "{
      \"customer_interests\": [\"soccer\", \"rugby\", \"hockey\"],
      \"store\": \"example_corp\",
      \"event\":\"order_placed\",
      \"price_usd\":210.75
   }",
   "Timestamp": "2019-11-03T23:28:01.631Z",
   "SignatureVersion": "4",
   "Signature": "signature",
   "UnsubscribeURL": "unsubscribe-url"
}
```

다음 필터 정책은 속성 이름과 값을 기준으로 메시지를 수락하거나 거부합니다.

## 예제 메시지를 수락하는 정책
<a name="policy-accepts-messages"></a>

다음 구독 필터 정책의 속성이 예제 메시지에 지정된 속성과 일치합니다. 참고로 `MessageAttributes` 또는 `MessageBody`로 설정되었는지와 관계없이 `FilterPolicyScope`에 대해 동일한 필터 정책이 적용됩니다. 각 구독자는 주제에서 받는 메시지의 구성에 따라 필터링 범위를 선택합니다.

이 정책의 속성 중 하나가 메시지에 지정된 속성과 일치하지 않으면 정책은 해당 메시지를 거부합니다.

```
{
   "store": ["example_corp"],
   "event": [{"anything-but": "order_cancelled"}],
   "customer_interests": [
      "rugby",
      "football",
      "baseball"
   ],
   "price_usd": [{"numeric": [">=", 100]}]
}
```

## 예제 메시지를 거부하는 정책
<a name="policy-rejects-messages"></a>

다음 구독 필터 정책의 속성과 예제 메시지에 지정된 속성이 서로 여러 가지가 불일치합니다. 예를 들어 `encrypted` 속성 이름이 메시지 속성에 없으므로 이 정책 속성은 할당된 값과 관계없이 메시지를 거부합니다.

불일치가 하나라도 있을 경우 정책은 해당 메시지를 거부합니다.

```
{
   "store": ["example_corp"],
   "event": ["order_cancelled"],
   "encrypted": [false],
   "customer_interests": [
      "basketball",
      "baseball"
   ]
}
```

# Amazon SNS에서 필터 정책 제약 조건
<a name="subscription-filter-policy-constraints"></a>

Amazon SNS에서 필터 정책을 설정할 때 유의해야 할 몇 가지 중요한 규칙이 있습니다. 이러한 규칙은 시스템 성능과 호환성을 유지하면서 필터 정책을 효과적으로 적용하는 데 도움이 됩니다.

## 필터 정책 제약 조건
<a name="subscription-filter-policy-common-constraints"></a>

Amazon SNS에서 필터 정책을 구성할 때 다음과 같은 중요한 규칙을 따라 시스템 성능과 호환성을 유지하면서 효과적으로 작동하는지 확인합니다.
+ **문자열 일치** - 필터 정책의 문자열 일치에서 비교는 대/소문자를 구분합니다.
+ **숫자 일치** - 숫자 일치에서 값의 범위는 -109\$1109(-10억\$110억)이며 소수점 이하 정확도는 5자리입니다.
+ **필터 정책 복잡도** - 필터 정책 복잡도에서 전체 값 조합이 **150**을 초과해서는 안 됩니다. 전체 조합을 계산하려면 필터 정책에 있는 각 어레이의 값의 개수를 곱합니다.
+ **키 수 제한** - 필터 정책에는 최대 **5**개의 키가 있을 수 있습니다.

****추가 고려 사항****
+ 필터 정책의 JSON에는 다음이 포함될 수 있습니다.
  + 인용 부호로 묶인 문자열
  + 숫자
  + 인용 부호 없는 키워드 `true`, `false` 및 `null`
+ Amazon SNS API를 사용하는 경우 필터 정책의 JSON을 유효한 **UTF-8** 문자열로 전달해야 합니다.
+ 필터 정책의 최대 크기는 **256KB**입니다.
+ 기본적으로 주제당 최대 **200**개의 필터 정책과 AWS 계정당 **10,000**개의 필터 정책을 가질 수 있습니다.

  이 정책 제한으로 인해 [https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html](https://docs.aws.amazon.com/sns/latest/api/API_Subscribe.html) API를 사용한 Amazon SQS 대기열 구독 생성이 중단되지는 않습니다. 하지만 `Subscribe` API 직접 호출(또는 [https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html) API 직접 호출)에 필터 정책을 연결하면 실패합니다.

  할당량 증가를 요청하려면 [AWS Service Quotas](https://docs.aws.amazon.com/servicequotas/latest/userguide/intro.html)를 사용합니다.

## 속성 기반 필터링에 대한 정책 제약 조건
<a name="subscription-filter-policy-attribute-constraints"></a>

속성 기반 필터링은 기본 옵션으로, 구독에서 [https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html#API_SetSubscriptionAttributes_RequestParameters](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html#API_SetSubscriptionAttributes_RequestParameters)는 `MessageAttributes`로 설정되어 있습니다.
+ Amazon SNS는 속성 기반 필터링을 위한 중첩된 필터 정책을 허용하지 않습니다.
+ Amazon SNS는 다음 데이터 형식을 갖는 메시지 속성만 정책 속성과 비교합니다.
  + `String`
  + `String.Array`
**중요**  
Amazon SNS에서 속성 기반 필터링을 사용하는 경우 특정 특수 문자, 특히 다음을 이중 이스케이프해야 합니다.  
큰따옴표(")
백슬래시()
이러한 문자를 두 번 이스케이프하지 않으면 필터 정책이 게시된 메시지의 속성과 일치하지 않고 알림이 전달되지 않습니다.

**추가 고려 사항**
+ 배열의 객체를 전달하면 속성 기반 필터링에서 지원되지 않는 중첩으로 인해 예상치 못한 결과가 발생할 수 있으므로 배열의 객체를 전달하는 것은 권장되지 않습니다. 중첩된 정책에 페이로드 기반 필터링을 사용합니다.
+ `Number`는 숫자 속성 값에 대해 지원됩니다.
+ Amazon SNS는 데이터 유형이 Binary인 메시지 속성을 무시합니다.

**복잡성에 대한 정책 예제:**

다음 정책 예제에서 첫 번째 키에는 **3개의** 일치 연산자가 있고, 두 번째 키에는 **1개의** 일치 연산자가 있으며, 세 번째 키에는 **2개의** 일치 연산자가 있습니다.

```
{
   "key_a": ["value_one", "value_two", "value_three"],
   "key_b": ["value_one"],
   "key_c": ["value_one", "value_two"]
}
```

총 조합은 필터 정책의 각 키에 대한 일치 연산자 수의 곱으로 계산됩니다.

```
3(match operators of key_a) 
x 1(match operators of key_b) 
x 2(match operators of key_c) 
= 6
```

## 페이로드 기반 필터링에 대한 정책 제약 조건
<a name="subscription-filter-policy-payload-constraints"></a>

속성 기반(기본값)에서 페이로드 기반 필터링으로 전환하려면 구독에서 [https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeprovisionIpamPoolCidr.html](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeprovisionIpamPoolCidr.html)를 `MessageBody`로 설정해야 합니다.
+ Amazon SNS는 페이로드 기반 필터링을 위한 중첩된 필터 정책을 허용합니다.
+ 중첩된 정책의 경우 **리프 키**만 **5개의** 키 제한에 포함됩니다.

**키 제한에 대한 정책 예제:**

다음은 정책의 예제입니다.
+ 리프 키에는 `key_c` 및 `key_e` 등 두 가지가 있습니다.
+ `key_c`에는 중첩 수준이 **3**인 **4**개의 일치 연산자가 있고, `key_e`에는 중첩 수준이 **2**인 **3**개의 일치 연산자가 있습니다.

```
{
"key_a": {
    "key_b": {
        "key_c": ["value_one", "value_two", "value_three", "value_four"]
        }
    },
"key_d": {
    "key_e": ["value_one", "value_two", "value_three"]
    }
}
```

총 조합은 필터 정책의 각 키에 대한 중첩 수준과 일치 연산자 수의 곱으로 계산됩니다.

```
4(match operators of key_c) 
x 3(nested level of key_c) 
x 3(match operators of key_e) 
x 2(nested level of key_e) 
= 72
```

## 와일드카드 패턴 사용 지침
<a name="filter-policy-constraints-wildcard"></a>

 Amazon SQS는 와일드카드가 포함된 필터 정책을 등록할 때에 대한 보호를 구현하여 필터 정책이 너무 복잡하게 생성되지 않도록 합니다. 애플리케이션 성능에 영향을 미칠 수 있기 때문입니다.

**패턴 구조**

필드에는 하나 이상의 패턴이 포함됩니다. 다음 예제에서는 두 가지 패턴을 사용하는 필드를 보여줍니다.

```
{
    "greeting": [
      {"anything-but": {"prefix": "Hello"}},
      {"wildcard": "H*"}
    ] // 2 patterns
  }
```

**복잡성 규칙**
+  모든 필드의 총 와일드카드 복잡성은 100점을 초과해서는 안 됩니다.
+  패턴당 최대 3개의 와일드카드 

**복잡성 계산**
+  필드 복잡성 = `(Sum of pattern points)`× `(Number of patterns)` 
+ 패턴 포인트:

   단일 와일드카드: 1점 

   다중 와일드카드: 각각 3점 

   Anything-but: 1점 

  다음은 복잡성 계산의 예제입니다.

  ```
  {
    "filename": [
      {"wildcard": "*.txt"},     // 1 point
      {"wildcard": "log*"}      // 1 point
    ]                           // Total: (1 + 1) × 2 = 4 points
  }
  ```

# AND/OR 로직
<a name="and-or-logic"></a>

필터 정책에서 AND/OR 로직을 사용하여 Amazon SNS의 메시지 속성 또는 본문 속성을 일치시킵니다. 이를 통해 보다 정확하고 유연한 메시지 필터링이 가능합니다.

## AND 로직
<a name="and-logic"></a>

여러 속성 이름을 사용하여 AND 로직을 적용할 수 있습니다.

다음 정책을 살펴보겠습니다.

```
{
  "customer_interests": ["rugby"],
  "price_usd": [{"numeric": [">", 100]}]
}
```

이 속성은 `rugby`로 설정된 `customer_interests` 값 *그리고* 100을 초과하는 값으로 설정된 `price_usd` 값을 갖는 모든 메시지 속성 또는 메시지 본문 속성과 일치합니다.

**참고**  
동일한 속성의 값에는 AND 로직을 적용할 수 없습니다.

## OR 로직
<a name="or-logic"></a>

속성 이름에 여러 값을 할당하여 OR 로직을 적용할 수 있습니다.

다음 정책을 살펴보겠습니다.

```
{
   "customer_interests": ["rugby", "football", "baseball"]
}
```

이 속성은 `customer_interests` 값이 `rugby`, `football` *또는* `baseball`로 설정된 모든 메시지 속성 또는 메시지 본문 속성과 일치합니다.

## OR 연산자
<a name="or-operator"></a>

`"$or"` 연산자를 사용해 필터 정책을 명시적으로 정의하여 정책에 있는 여러 속성 간의 OR 관계를 표현할 수 있습니다.

Amazon SNS는 정책이 다음 조건을 모두 충족하는 경우에만 `"$or"` 관계를 인식합니다. 이러한 조건이 모두 충족되지 않으면 `"$or"`은 정책의 다른 문자열과 마찬가지로 일반 속성 이름으로 처리됩니다.
+ 규칙에 `"$or"` 필드 속성이 있고 그 뒤에 배열이 있습니다(예: `“$or” : []`).
+ `"$or"` 배열에 최소 두 개의 객체가 있습니다. `"$or": [{}, {}]` 
+ `"$or"` 배열의 모든 객체에 예약된 키워드인 필드 이름이 없습니다.

그렇지 않으면 `"$or"`는 정책의 다른 문자열과 마찬가지로 일반 속성 이름으로 처리됩니다.

숫자와 접두사는 예약된 키워드이므로 다음 정책은 OR 관계로 구문 분석되지 않습니다.

```
{ 
   "$or": [ {"numeric" : 123}, {"prefix": "abc"} ] 
}
```

**`OR` 연산자 예제**

표준 `OR`:

```
{
  "source": [ "aws.cloudwatch" ], 
  "$or": [
    { "metricName": [ "CPUUtilization" ] },
    { "namespace": [ "AWS/EC2" ] }
  ] 
}
```

이 정책의 필터 로직은 다음과 같습니다.

```
"source" && ("metricName" || "namespace")
```

이는 다음 메시지 속성 중 하나와 일치합니다.

```
"source": {"Type": "String", "Value": "aws.cloudwatch"},
"metricName": {"Type": "String", "Value": "CPUUtilization"}
```

또는

```
"source": {"Type": "String", "Value": "aws.cloudwatch"},
"namespace": {"Type": "String", "Value": "AWS/EC2"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
    "source": "aws.cloudwatch",
    "metricName": "CPUUtilization"
}
```

또는

```
{
    "source": "aws.cloudwatch",
    "namespace": "AWS/EC2"
}
```

### `OR` 관계를 포함하는 정책 제약 조건
<a name="or-operator-constraints"></a>

다음 정책을 살펴보겠습니다.

```
{
    "source": [ "aws.cloudwatch" ],
    "$or": [
      { "metricName": [ "CPUUtilization", "ReadLatency" ] },
      {
        "metricType": [ "MetricType" ] ,
        "$or" : [
          { "metricId": [ 1234, 4321 ] },
          { "spaceId": [ 1000, 2000, 3000 ] }
        ]
      }
    ]
  }
```

이 정책의 로직을 다음과 같이 단순화할 수도 있습니다.

```
("source" AND "metricName") 
OR 
("source" AND "metricType" AND "metricId") 
OR 
("source" AND "metricType" AND "spaceId")
```

OR 관계가 있는 정책의 복잡성 계산은 각 OR 문에 대한 조합 복잡성의 합으로 단순화할 수 있습니다.

따라서 전체 조합은 다음과 같습니다.

```
(source * metricName) + (source * metricType * metricId) + (source * metricType * spaceId)
= (1 * 2) + (1 * 1 * 2) + (1 * 1 * 3) 
= 7
```

`source`에는 값이 하나, `metricName`에는 값이 두 개, `metricType`에는 값이 하나, `metricId`에는 값이 두 개, `spaceId`에는 값이 세 개 있습니다.

다음과 같은 중첩 필터 정책을 고려해 봅니다.

```
{
    "$or": [
      { "metricName": [ "CPUUtilization", "ReadLatency" ] },
      { "namespace": [ "AWS/EC2", "AWS/ES" ] }
    ],
    "detail" : {
      "scope" : [ "Service" ],
      "$or": [
        { "source": [ "aws.cloudwatch" ] },
        { "type": [ "CloudWatch Alarm State Change"] }
      ]
    }
  }
```

이 정책의 로직을 다음과 같이 단순화할 수 있습니다.

```
("metricName" AND ("detail"."scope" AND "detail"."source")
OR
("metricName" AND ("detail"."scope" AND "detail"."type")
OR
("namespace" AND ("detail"."scope" AND "detail"."source")
OR
("namespace" AND ("detail"."scope" AND "detail"."type")
```

총 조합 계산은 키의 중첩 수준을 고려해야 한다는 점을 제외하고 중첩되지 않은 정책과 동일합니다.

따라서 전체 조합은 다음과 같습니다.

```
(2 * 2 * 2) + (2 * 2 * 2) + (2 * 2 * 2) + (2 * 2 * 2) = 32
```

`metricName`에는 두 개의 값이 있고, `namespace`에는 두 개의 값이 있고, `scope`는 하나의 값이 있는 2수준 중첩 키이고, `source`는 하나의 값이 있는 2수준 중첩 키이며, `type`은 하나의 값이 있는 2수준 중첩 키입니다.

# 키 일치
<a name="attribute-key-matching"></a>

필터 정책의 `exists` 연산자를 사용하여 특정 속성이 있는지 여부에 따라 수신 메시지를 일치시킵니다.
+ `exists`는 리프 노드(구조의 최종 속성)에서만 작동합니다.
+ 중첩된 JSON 구조 내의 중간 노드에는 적용되지 않습니다.
+ `"exists": true`를 사용하여 지정된 속성을 포함하는 수신 메시지를 일치시킬 수 있습니다. 키는 null이 아니고 비어 있지 않은 값을 가져야 합니다.

  예를 들어, 다음 정책 속성은 `true` 값을 지닌 `exists` 연산자를 사용합니다.

  ```
  "store": [{"exists": true}]
  ```

  이 속성은 다음과 같이 `store` 속성 키가 있는 모든 메시지 속성 목록과 일치합니다.

  ```
  "store": {"Type": "String", "Value": "fans"}
  "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball\"]"}
  ```

  이 속성은 다음 메시지 본문 중 하나와 일치합니다.

  ```
  {
      "store": "fans"
      "customer_interests": ["baseball", "basketball"]
  }
  ```

  그러나 다음과 같이 `store` 속성 키가 *없는* 메시지 속성 목록과는 일치하지 않습니다.

  ```
  "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball\"]"}
  ```

  다음 메시지 본문과도 일치하지 않습니다.

  ```
  {
      "customer_interests": ["baseball", "basketball"]
  }
  ```
+ `"exists": false`를 사용하여 지정된 속성을 포함하지 *않는* 수신 메시지를 일치시킬 수 있습니다.
**참고**  
`"exists": false`는 하나 이상의 속성이 있는 경우에만 일치합니다. 속성 세트가 비어 있으면 필터가 일치하지 않습니다.

  예를 들어, 다음 정책 속성은 `false` 값을 지닌 `exists` 연산자를 사용합니다.

  ```
  "store": [{"exists": false}]
  ```

  이 속성은 다음과 같이 `store` 속성 키가 있는 모든 메시지 속성 목록과 일치하지 *않습니다*.

  ```
  "store": {"Type": "String", "Value": "fans"}
  "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball\"]"}
  ```

  또한 다음 메시지 본문과도 일치하지 않습니다.

  ```
  {
      "store": "fans"
      "customer_interests": ["baseball", "basketball"]
  }
  ```

  그러나 다음과 같이 `store` 속성 키가 *없는* 모든 메시지 속성 목록과 일치합니다.

  ```
  "customer_interests": {"Type": "String.Array", "Value": "[\"baseball\", \"basketball\"]"}
  ```

  이 속성은 다음 메시지 본문과도 일치합니다.

  ```
  {
      "customer_interests": ["baseball", "basketball"]
  }
  ```

# 숫자 값 일치
<a name="numeric-value-matching"></a>

숫자 값을 메시지 속성 값이나 메시지 본문 속성 값과 일치시켜 메시지를 필터링합니다. 숫자 값은 JSON 정책에서 큰따옴표로 묶지 않습니다. 필터링에 다음과 같은 숫자 작업을 사용할 수 있습니다.

**참고**  
접두사는 *문자열* 일치에 대해서만 지원됩니다.

## 정확한 일치
<a name="numeric-exact-matching"></a>

정책 속성 값이 키워드 `numeric`과 연산자 `=`를 포함하는 경우, 동일한 이름과 동일한 숫자 값을 가지고 있는 모든 메시지 속성 또는 메시지 본문 속성값과 일치합니다.

다음 정책 속성을 살펴보겠습니다.

```
"price_usd": [{"numeric": ["=",301.5]}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"price_usd": {"Type": "Number", "Value": 301.5}
```

```
"price_usd": {"Type": "Number", "Value": 3.015e2}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
   "price_usd": 301.5
}
```

```
{
   "price_usd": 3.015e2
}
```

## Anything-but 일치
<a name="numeric-anything-but-matching"></a>

정책 속성 값에 키워드 `anything-but`가 포함되어 있으면 정책 속성 값을 포함하지 *않는* 모든 메시지 속성 또는 메시지 본문 속성값과 일치합니다.

다음 정책 속성을 살펴보겠습니다.

```
"price": [{"anything-but": [100, 500]}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"price": {"Type": "Number", "Value": 101}
```

```
"price": {"Type": "Number", "Value": 100.1}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
   "price": 101
}
```

```
{
   "price": 100.1
}
```

또한 다음 메시지 속성과 일치합니다(`100` 또는 `500`이 *아닌* 값이 포함되어 있기 때문).

```
"price": {"Type": "Number.Array", "Value": "[100, 50]"}
```

또한 다음 메시지 본문과도 일치합니다(`100` 또는 `500`이 *아닌* 값이 포함되어 있기 때문).

```
{
   "price": [100, 50]
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"price": {"Type": "Number", "Value": 100}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
   "price": 100
}
```

## 값 범위 일치
<a name="numeric-value-range-matching"></a>

연산자 `=` 외에도, 숫자 정책 속성은 다음 연산자를 포함할 수 있습니다. `<`, `<=`, `>` 및 `>=`.

다음 정책 속성을 살펴보겠습니다.

```
"price_usd": [{"numeric": ["<", 0]}]
```

이 속성은 음수 값을 갖는 모든 메시지 속성 또는 메시지 본문 속성과 일치합니다.

다른 메시지 속성을 살펴보겠습니다.

```
"price_usd": [{"numeric": [">", 0, "<=", 150]}]
```

이 속성은 최대 150까지의 양수를 갖는 모든 메시지 속성 또는 메시지 본문 속성과 일치합니다.

# 문자열 값 일치
<a name="string-value-matching"></a>

문자열 값을 메시지 속성 값이나 메시지 본문 속성 값과 일치시켜 메시지를 필터링합니다. 문자열 값은 JSON 정책에서 큰따옴표로 묶습니다. 다음 문자열 작업을 사용하여 메시지 속성 또는 메시지 본문 속성을 일치시킬 수 있습니다.

## 정확한 일치
<a name="string-exact-matching"></a>

정책 속성 값이 하나 이상의 메시지 속성 값과 일치하는 경우 정확한 일치가 발생합니다. `String.Array` 유형 속성의 경우 배열의 각 요소는 일치를 위해 별도의 문자열로 처리됩니다.

다음 정책 속성을 살펴보겠습니다.

```
"customer_interests": ["rugby", "tennis"]
```

이 속성은 다음 메시지 속성과 일치합니다.

```
"customer_interests": {"Type": "String", "Value": "rugby"}
```

```
"customer_interests": {"Type": "String", "Value": "tennis"}
```

```
"customer_interests": {"Type": "String.Array", "Value": "[\"rugby\", \"tennis\"]"}
```

또한 다음 메시지 본문과도 일치합니다.

```
{
   "customer_interests": "rugby"
}
```

```
{
   "customer_interests": "tennis"
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"customer_interests": {"Type": "String", "Value": "baseball"}
```

```
"customer_interests": {"Type": "String.Array", "Value": "[\"baseball\"]"}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
   "customer_interests": "baseball"
}
```

## Anything-but 일치
<a name="string-anything-but-matching"></a>

정책 속성 값에 키워드 `anything-but`가 포함되어 있으면 정책 속성 값을 포함하지 *않는* 모든 메시지 속성 또는 메시지 본문 값과 일치합니다. `anything-but`는 `"exists": false`와 함께 사용할 수 있습니다. `String.Array` 유형 속성의 경우 정책 속성에 나열된 배열 요소가 없는 경우 일치합니다.

다음 정책 속성을 살펴보겠습니다.

```
"customer_interests": [{"anything-but": ["rugby", "tennis"]}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"customer_interests": {"Type": "String", "Value": "baseball"}
```

```
"customer_interests": {"Type": "String", "Value": "football"}
```

```
"customer_interests": {"Type": "String.Array", "Value": "[\"rugby\", \"baseball\"]"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
   "customer_interests": "baseball"
}
```

```
{
   "customer_interests": "football"
}
```

또한 다음 메시지 속성과 일치합니다(`rugby` 또는 `tennis`이 *아닌* 값이 포함되어 있기 때문).

```
"customer_interests": {"Type": "String.Array", "Value": "[\"rugby\", \"baseball\"]"}
```

또한 다음 메시지 본문과도 일치합니다(`rugby` 또는 `tennis`가 아닌 값이 포함되어 있기 때문).

```
{
   "customer_interests": ["rugby", "baseball"]
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"customer_interests": {"Type": "String", "Value": "rugby"}
```

```
"customer_interests": {"Type": "String.Array", "Value": "[\"rugby\"]"}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
   "customer_interests": ["rugby"]
}
```

**접두사 `anything-but` 사용**

문자열 일치의 경우 `anything-but` 연산자와 함께 접두사를 사용할 수도 있습니다. 예를 들어 다음 정책 속성은 `order-` 접두사를 거부합니다.

```
"event":[{"anything-but": {"prefix": "order-"}}]
```

이 속성은 다음 속성 중 하나와 일치합니다.

```
"event": {"Type": "String", "Value": "data-entry"}
```

```
"event": {"Type": "String", "Value": "order_number"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
   "event": "data-entry"
}
```

```
{
   "event": "order_number"
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"event": {"Type": "String", "Value": "order-cancelled"}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
   "event": "order-cancelled"
}
```

**anything-but 와일드카드**

다음 정책 속성은 `*ball` 와일드카드를 거부합니다.

```
"customer_interests" : [{ "anything-but": { "wildcard": "*ball" }}]
```

이 속성은 다음 속성과 일치합니다.

```
{"customer_interests": ["hockey", "rugby", "soccer] }
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
{"customer_interests": ["baseball", "basketball"] }
```

**anything-but 접미사** 

다음 정책 속성은 `-ball`

 접미사를 거부합니다.

```
"customer_interests": [ { "anything-but": { "suffix": "ball" } } ]
```

이 속성은 다음 속성과 일치합니다.

```
{"customer_interests": ["hockey", "rugby", "soccer] }
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
 {"customer_interests": ["baseball", "basketball"] }
```

## Equals-ignore-case 일치
<a name="string-equals-ignore"></a>

정책 속성이 키워드 `equals-ignore-case`를 포함하고 있는 경우, 모든 메시지 속성 또는 본문 속성 값에 대해 대소문자를 구분하지 않는 일치 연산을 수행합니다.

다음 정책 속성을 살펴보겠습니다.

```
"customer_interests": [{"equals-ignore-case": "tennis"}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"customer_interests": {"Type": "String", "Value": "TENNIS"}
```

```
"customer_interests": {"Type": "String", "Value": "Tennis"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
    "customer_interests": "TENNIS"
}
```

```
{
    "customer_interests": "teNnis"
{
```

## IP 주소 일치
<a name="string-address-matching"></a>

`cidr` 연산자를 사용하여 수신 메시지가 특정 IP 주소 또는 서브넷에서 발생하는지 확인할 수 있습니다.

다음 정책 속성을 살펴보겠습니다.

```
"source_ip":[{"cidr": "10.0.0.0/24"}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"source_ip": {"Type": "String", "Value": "10.0.0.0"}
```

```
"source_ip": {"Type": "String", "Value": "10.0.0.255"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
   "source_ip": "10.0.0.0"
}
```

```
{
   "source_ip": "10.0.0.255"
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"source_ip": {"Type": "String", "Value": "10.1.1.0"}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
   "source_ip": "10.1.1.0"
}
```

## 접두사 일치
<a name="string-prefix-matching"></a>

정책 속성이 키워드 `prefix`를 포함하고 있는 경우, 이 값은 메시지 속성 또는 지정된 문자로 시작하는 모든 메시지 속성 값과 일치합니다.

다음 정책 속성을 살펴보겠습니다.

```
"customer_interests": [{"prefix": "bas"}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"customer_interests": {"Type": "String", "Value": "baseball"}
```

```
"customer_interests": {"Type": "String", "Value": "basketball"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
   "customer_interests": "baseball"
}
```

```
{
   "customer_interests": "basketball"
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"customer_interests": {"Type": "String", "Value": "rugby"}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
   "customer_interests": "rugby"
}
```

## 접미사 일치
<a name="string-suffix-matching"></a>

정책 속성이 키워드 `suffix`를 포함하고 있는 경우, 이 값은 메시지 속성 또는 지정된 문자로 끝나는 모든 메시지 속성 값과 일치합니다.

다음 정책 속성을 살펴보겠습니다.

```
"customer_interests": [{"suffix": "ball"}]
```

이 속성은 다음 메시지 속성 중 하나와 일치합니다.

```
"customer_interests": {"Type": "String", "Value": "baseball"}
```

```
"customer_interests": {"Type": "String", "Value": "basketball"}
```

이 속성은 다음 메시지 본문 중 하나와도 일치합니다.

```
{
    "customer_interests": "baseball"
}
```

```
{
    "customer_interests": "basketball"
}
```

그러나 다음 메시지 속성과는 일치하지 않습니다.

```
"customer_interests": {"Type": "String", "Value": "rugby"}
```

다음 메시지 본문과도 일치하지 않습니다.

```
{
    "customer_interests": "rugby"
}
```

## 와일드카드
<a name="string-value-wildcard"></a>

 와일드카드 문자(\$1)를 사용하여 이벤트 패턴의 문자열 값을 매칭할 수 있습니다.

다음 정책은 와일드카드(\$1) 문자를 사용합니다.

```
"customer_interests": [ { "wildcard": "*ball" } ]
```

이 속성은 다음 속성과 일치합니다.

```
{"customer_interests": ["baseball", "basketball"] }
```

# Amazon SNS에서 구독 필터 정책 적용
<a name="message-filtering-apply"></a>

Amazon SNS에서 메시지 필터링을 사용하면 필터 정책에 따라 구독자에게 선택적으로 메시지를 전달할 수 있습니다. 이러한 정책에서는 메시지가 구독에 전달되려면 충족되어야 하는 조건을 정의합니다. 원시 메시지 전송은 메시지 처리에 영향을 미칠 수 있는 옵션이지만 구독 필터가 작동하는 데 필수는 아닙니다.

Amazon SNS 콘솔을 사용하여 필터 정책을 Amazon SNS 구독에 적용할 수 있습니다. 또는 프로그래밍 방식으로 정책을 적용하려면 Amazon SNS API, AWS Command Line Interface (AWS CLI) 또는 Amazon SNS를 지원하는 AWS SDK를 사용할 수 있습니다. 를 사용할 수도 있습니다 AWS CloudFormation.

**원시 메시지 전송 사용**

원시 메시지 전송을 사용하면 추가 인코딩 또는 변환 없이 메시지 페이로드를 구독자에게 있는 그대로 전달할 수 있습니다. 이는 구독자가 처리하는 데 원본 메시지 형식을 필요로 하는 경우에 유용할 수 있습니다. 하지만 원시 메시지 전송은 구독 필터의 기능과는 직접적인 관련이 없습니다.

**구독 필터 적용**

메시지 필터를 구독에 적용하려면 JSON 구문을 사용하여 필터 정책을 정의합니다. 이 정책에서는 메시지가 구독에 전달되려면 충족되어야 하는 조건을 지정합니다. 필터는 메시지 속성, 메시지 구조, 메시지 콘텐츠와 같은 메시지 속성을 기반으로 작동할 수 있습니다.

**원시 메시지 전송과 구독 필터 간의 관계**

원시 메시지 전송을 사용하면 구독자가 메시지를 전송하고 처리하는 방식에 영향을 미칠 수 있지만 구독 필터를 사용하기 위한 사전 조건은 아닙니다. 하지만 구독자가 수정 없이 원본 메시지 형식을 요구하는 시나리오에서는 구독 필터와 함께 원시 메시지 전송을 사용하는 것이 도움이 될 수 있습니다.

**효과적인 필터링을 위한 고려 사항**

메시지 필터링을 구현할 경우 애플리케이션 및 구독자의 특정 요구 사항을 고려하세요. 메시지 전송 기준과 정확하게 일치하는 필터 정책을 정의하여 효율적이고 대상에 맞게 메시지를 배포합니다.

**중요**  
AWS IAM 및 Amazon SNS와 같은 서비스는 최종 일관성이라는 분산 컴퓨팅 모델을 사용합니다. 구독 필터 정책의 추가 또는 변경 사항이 완전히 적용되려면 최대 15분이 소요됩니다.

## AWS Management Console
<a name="message-filtering-apply-console"></a>

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 탐색 창에서 **구독**을 선택합니다.

1. 구독을 선택한 후 **편집**을 선택합니다.

1. **편집(Edit)** 페이지에서 **구독 필터 정책(Subscription filter policy)** 섹션을 확장합니다.

1. **속성 기반 필터링** 또는 **페이로드 기반 필터링** 중에서 선택합니다.

1. **JSON 편집기(JSON editor)** 필드에서 필터 정책의 **JSON 본문(JSON body)**을 제공합니다.

1. **변경 사항 저장**을 선택합니다.

   Amazon SNS에서 구독에 필터 정책을 적용합니다.

## AWS CLI
<a name="message-filtering-apply-cli"></a>

 AWS Command Line Interface (AWS CLI)를 사용하여 필터 정책을 적용하려면 다음 예제와 같이 [https://docs.aws.amazon.com/cli/latest/reference/sns/set-subscription-attributes.html](https://docs.aws.amazon.com/cli/latest/reference/sns/set-subscription-attributes.html) 명령을 사용합니다. `--attribute-name` 옵션의 경우 `FilterPolicy`를 지정합니다. `--attribute-value`의 경우 **JSON 정책**을 지정합니다.

```
$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicy --attribute-value '{"store":["example_corp"],"event":["order_placed"]}'
```

정책에 유효한 JSON을 제공하려면 속성 이름과 값을 큰 따옴표로 묶습니다. 또한 전체 정책 인수를 따옴표로 묶어야 합니다. 따옴표 이스케이프를 방지하려면, 위의 예제와 같이 작은따옴표를 사용하여 정책을 묶고 큰따옴표를 사용하여 JSON 이름과 값을 묶을 수 있습니다.

속성 기반(기본값)에서 페이로드 기반 메시지 필터링으로 전환하려면 [set-subscription-attributes](https://docs.aws.amazon.com/cli/latest/reference/sns/set-subscription-attributes.html) 명령도 사용할 수 있습니다. `--attribute-name` 옵션의 경우 `FilterPolicyScope`를 지정합니다. `--attribute-value`에서 `MessageBody`를 지정합니다.

```
$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicyScope --attribute-value MessageBody
```

필터 정책이 적용되었는지 확인하려면 `get-subscription-attributes` 명령을 사용합니다. 터미널 출력의 속성에는 다음 예제와 같이 `FilterPolicy` 키에 대한 필터 정책이 표시되어야 합니다:

```
$ aws sns get-subscription-attributes --subscription-arn arn:aws:sns: ...
{
    "Attributes": {
        "Endpoint": "endpoint . . .", 
        "Protocol": "https",
        "RawMessageDelivery": "false", 
        "EffectiveDeliveryPolicy": "delivery policy . . .",
        "ConfirmationWasAuthenticated": "true", 
        "FilterPolicy": "{\"store\": [\"example_corp\"], \"event\": [\"order_placed\"]}", 
        "FilterPolicyScope": "MessageAttributes",
        "Owner": "111122223333", 
        "SubscriptionArn": "arn:aws:sns: . . .", 
        "TopicArn": "arn:aws:sns: . . ."
    }
}
```

## AWS SDKs
<a name="message-filtering-apply-sdks"></a>

다음 코드 예시는 `SetSubscriptionAttributes`의 사용 방법을 보여 줍니다.

**중요**  
Java 2.x 예제용 SDK를 사용하는 경우 클래스 `SNSMessageFilterPolicy`는 즉시 사용할 수 없습니다. 이 클래스를 설치하는 방법에 대한 지침은 GitHub 웹 사이트의 [예제](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/sns/src/main/java/com/example/sns/SNSMessageFilterPolicy.java)를 참조하세요.

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

**AWS CLI**  
**구독 속성을 설정하려면**  
다음 `set-subscription-attributes`예제에서는 SQS 구독에 `RawMessageDelivery`속성을 설정합니다.  

```
aws sns set-subscription-attributes \
    --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \
    --attribute-name RawMessageDelivery \
    --attribute-value true
```
이 명령은 출력을 생성하지 않습니다.  
다음 `set-subscription-attributes`예제에서는 SQS 구독에 `FilterPolicy`속성을 설정합니다.  

```
aws sns set-subscription-attributes \
    --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \
    --attribute-name FilterPolicy \
    --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }"
```
이 명령은 출력을 생성하지 않습니다.  
다음 `set-subscription-attributes`예제에서는 SQS 구독에서 `FilterPolicy`속성을 제거합니다.  

```
aws sns set-subscription-attributes \
    --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \
    --attribute-name FilterPolicy \
    --attribute-value "{}"
```
이 명령은 출력을 생성하지 않습니다.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [SetSubscriptionAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-subscription-attributes.html)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.ArrayList;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class UseMessageFilterPolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <subscriptionArn>

                Where:
                   subscriptionArn - The ARN of a subscription.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String subscriptionArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        usePolicy(snsClient, subscriptionArn);
        snsClient.close();
    }

    public static void usePolicy(SnsClient snsClient, String subscriptionArn) {
        try {
            SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy();
            // Add a filter policy attribute with a single value
            fp.addAttribute("store", "example_corp");
            fp.addAttribute("event", "order_placed");

            // Add a prefix attribute
            fp.addAttributePrefix("customer_interests", "bas");

            // Add an anything-but attribute
            fp.addAttributeAnythingBut("customer_interests", "baseball");

            // Add a filter policy attribute with a list of values
            ArrayList<String> attributeValues = new ArrayList<>();
            attributeValues.add("rugby");
            attributeValues.add("soccer");
            attributeValues.add("hockey");
            fp.addAttribute("customer_interests", attributeValues);

            // Add a numeric attribute
            fp.addAttribute("price_usd", "=", 0);

            // Add a numeric attribute with a range
            fp.addAttributeRange("price_usd", ">", 0, "<=", 100);

            // Apply the filter policy attributes to an Amazon SNS subscription
            fp.apply(snsClient, subscriptionArn);

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [SetSubscriptionAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/SetSubscriptionAttributes)를 참조하세요.

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

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    @staticmethod
    def add_subscription_filter(subscription, attributes):
        """
        Adds a filter policy to a subscription. A filter policy is a key and a
        list of values that are allowed. When a message is published, it must have an
        attribute that passes the filter or it will not be sent to the subscription.

        :param subscription: The subscription the filter policy is attached to.
        :param attributes: A dictionary of key-value pairs that define the filter.
        """
        try:
            att_policy = {key: [value] for key, value in attributes.items()}
            subscription.set_attributes(
                AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy)
            )
            logger.info("Added filter to subscription %s.", subscription.arn)
        except ClientError:
            logger.exception(
                "Couldn't add filter to subscription %s.", subscription.arn
            )
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [SetSubscriptionAttributes](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/SetSubscriptionAttributes)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_sns->setsubscriptionattributes(
            iv_subscriptionarn = iv_subscription_arn
            iv_attributename  = 'FilterPolicy'
            iv_attributevalue = iv_filter_policy ).
        MESSAGE 'Added filter policy to subscription.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Subscription does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API 세부 정보는 SDK for SAP ABAP API 참조의 [SetSubscriptionAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요. *AWS * 

------

## Amazon SNS API
<a name="message-filtering-apply-api"></a>

Amazon SNS API를 사용하여 필터 정책을 적용하려면 [https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html) 작업에 대한 요청을 수행합니다. `AttributeName` 파라미터를 `FilterPolicy`로 설정하고 `AttributeValue` 파라미터를 필터 정책 JSON으로 설정합니다.

속성 기반(기본값)에서 페이로드 기반 메시지 필터링으로 전환하려는 경우에도 [https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html) 작업을 사용할 수 있습니다. `AttributeName` 매개 변수를 `FilterPolicyScope`로 설정하고 `AttributeValue` 매개 변수를 `MessageBody`로 설정합니다.

## AWS CloudFormation
<a name="message-filtering-apply-cloudformation"></a>

를 사용하여 필터 정책을 적용하려면 JSON 또는 YAML 템플릿을 CloudFormation사용하여 스택을 CloudFormation 생성합니다. 자세한 내용은 *AWS CloudFormation 사용 설명서*의 `AWS::SNS::Subscription` 리소스 [`FilterPolicy` 속성](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-subscription.html#cfn-sns-subscription-filterpolicy)과 [예제 CloudFormation 템플릿을](https://github.com/aws-samples/aws-sns-samples/blob/master/templates/SNS-Subscription-Attributes-Tutorial-CloudFormation.template) 참조하세요.

1. [CloudFormation 콘솔](https://console.aws.amazon.com/cloudformation)에 로그인합니다.

1. **스택 생성**을 선택합니다.

1. **템플릿 선택** 페이지에서 **Amazon S3에 템플릿 업로드**를 선택하고 파일을 선택한 후 **다음**을 선택합니다.

1. **세부 정보 지정** 페이지에서 다음 작업을 수행합니다.

   1. **스택 이름**에 `MyFilterPolicyStack`을 입력합니다.

   1. **myHttpEndpoint**에 주제를 구독할 HTTP 엔드포인트를 입력합니다.
**작은 정보**  
HTTP 엔드포인트가 없는 경우 하나를 생성합니다.

1. **옵션** 페이지에서 **다음**을 선택합니다.

1. **검토** 페이지에서 **생성**을 선택합니다.

# Amazon SNS에서 구독 필터 정책 제거
<a name="message-filtering-policy-remove"></a>

구독자에게 보내는 메시지의 필터링을 중지하려면 해당 구독의 필터 정책을 빈 JSON 본문으로 덮어써서 제거합니다. 정책을 제거한 뒤에도 해당 구독은 자신을 상대로 게시되는 모든 메시지를 받게 됩니다.

## 사용 AWS Management Console
<a name="message-filtering-policy-remove-console"></a>

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 탐색 창에서 **구독**을 선택합니다.

1. 구독을 선택한 후 **편집**을 선택합니다.

1. **Edit *EXAMPLE1-23bc-4567-d890-ef12g3hij456*(예제 1-23bc-4567-d890-ef12g3hij456 편집)** 페이지에서 **Subscription filter policy(구독 필터 정책)** 섹션을 확장합니다.

1. **JSON 편집기** 필드에서 필터 정책의 빈 JSON 본문(`{}`)을 제공합니다.

1. **변경 사항 저장**을 선택합니다.

   Amazon SNS에서 구독에 필터 정책을 적용합니다.

## 사용 AWS CLI
<a name="message-filtering-policy-remove-cli"></a>

에서 필터 정책을 제거하려면 [https://docs.aws.amazon.com/cli/latest/reference/sns/set-subscription-attributes.html](https://docs.aws.amazon.com/cli/latest/reference/sns/set-subscription-attributes.html) 명령을 AWS CLI사용하고 `--attribute-value` 인수에 빈 JSON 본문을 제공합니다.

```
$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicy --attribute-value "{}"
```

## Amazon SNS API 사용
<a name="message-filtering-policy-remove-api"></a>

Amazon SNS API를 사용하여 필터 정책을 제거하려면 [https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html](https://docs.aws.amazon.com/sns/latest/api/API_SetSubscriptionAttributes.html) 작업을 요청합니다. `AttributeName` 파라미터를 `FilterPolicy`로 설정하고 `AttributeValue` 파라미터에 빈 JSON 문자열을 입력합니다.