

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon SNS 訊息篩選
<a name="sns-message-filtering"></a>

根據預設，Amazon SNS 主題訂閱者會接收發佈到主題的每個訊息。若要僅接收一部分的訊息，訂閱者必須將*篩選政策*指派給主題訂閱。

篩選政策是包含屬性的 JSON 物件，這些屬性會定義訂閱者接收的訊息。Amazon SNS 支援對訊息屬性或內文採取行動的政策，該政策係根據您為訂閱設定的篩選政策範圍。訊息內文的篩選政策假定訊息承載是格式正確的 JSON 物件。

如果訂閱沒有篩選政策，訂閱者會收到發佈到主題的每個訊息。當您發佈訊息至具有篩選政策的主題時，Amazon SNS 會針對每一個主題訂閱，比較訊息屬性或內文與篩選政策中的屬性。如果所有訊息屬性或訊息內文屬性都符合篩選條件政策中指定的條件，Amazon SNS 會將訊息傳送給訂閱者。否則，Amazon SNS 不會傳送訊息給訂閱者。

如需詳細資訊，請參閱 [Filter Messages Published to Topics](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)
+ [支援任何數值，但不會比對](numeric-value-matching.md#numeric-anything-but-matching)
+ [數值範圍比對](numeric-value-matching.md#numeric-value-range-matching)
+ [字串值完全相符](string-value-matching.md#string-exact-matching)
+ [支援任何字串值，但不會比對](string-value-matching.md#string-anything-but-matching)
+ [支援任何使用前綴的字串值，但不會比對](string-value-matching.md#string-anything-but-matching)
+ [字串值相同，但忽略大小寫](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` 欄位，其中包含描述交易的屬性：
+ 客戶的利益
+ 商店名稱
+ 事件狀態
+ 購買價格 (以美元為單位)

由於此訊息包含 `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` 欄位中的相同屬性，也稱為*訊息承載*或*訊息內文*。只要訂閱中的 `FilterPolicyScope` 皆設為 `MessageBody`，任何包含 `FilterPolicy` 的主題訂閱皆可選擇性地接受或拒絕訊息。

```
{
"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 到 109 (-10 億到 10 億），在小數點後有五位數的準確性。
+ **篩選政策複雜性** – 篩選政策中值的總組合不得超過 **150**。若要計算總組合，請乘以篩選政策中每個陣列的值數目。
+ **金鑰數量限制** – 篩選政策最多可有**五個**金鑰。

****其他考量事項****
+ 篩選政策的 JSON 可以包含下列項目：
  + 用引號括住的字串
  + 數字
  + 關鍵字 `true`、`false` 和 `null` (不含引號)
+ 使用 Amazon SNS API 時，您必須傳遞篩選條件政策的 JSON，做為有效的 **UTF-8 **字串。
+ 篩選條件政策的大小上限為 **256 KB**。
+ 根據預設，每個主題最多可有 **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 會使用二進位資料類型忽略訊息屬性。

**複雜性政策範例：**

在下列政策範例中，第一個索引鍵有**三個**相符運算子，第二個則**有一個**相符運算子，第三個則有兩個****相符運算子。

```
{
   "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 接受以承載為基礎的巢狀篩選政策。
+ 對於巢狀政策，只有**分葉索引鍵**會計入**五個**索引鍵限制。

**金鑰限制的政策範例：**

在下列政策範例中：
+ 有兩種分葉索引鍵： `key_c`和 `key_e`。
+ `key_c` 有**四個**巢狀層級為 **3** 的相符運算子，`key_e`以及**三個**巢狀層級為 **2** 的相符運算子。

```
{
"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 點 

   任何項目：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]}]
}
```

它符合 `customer_interests` 的值設為 `rugby` *且* `price_usd` 的值設為大於 100 數字的任何訊息屬性或訊息內文屬性。

**注意**  
您無法將 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` 具有兩個巢狀索引鍵與一個值，`source` 具有兩個巢狀索引鍵與一個值，並且 `type` 具有兩個巢狀索引鍵與一個值。

# 索引鍵比對
<a name="attribute-key-matching"></a>

在篩選條件政策中使用 `exists` 運算子，根據特定屬性是否存在，來比對傳入的訊息。
+ `exists` 僅適用於分葉節點 （結構中的最終屬性）。
+ 它不適用於巢狀 JSON 結構中的中繼節點。
+ 使用 `"exists": true` 配對包含指定屬性的傳入訊息。該鍵必須具有非空值和非空值。

  例如，下列政策屬性會使用 `exists` 運算子及為 `true` 的值：

  ```
  "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` 只有在至少有一個屬性存在時才相符。一組空白的屬性會導致篩選條件不相符。

  例如，下列政策屬性會使用 `exists` 運算子及為 `false` 的值：

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

## 除外相符
<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 (含 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"
}
```

## 除外相符
<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"
}
```

**任何項目，但萬用字元**

下列政策屬性拒絕`*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"] }
```

## 等於忽略大小寫相符
<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 管理主控台
<a name="message-filtering-apply-console"></a>

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在導覽面板上，選擇 **Subscriptions (訂閱)**。

1. 選取訂閱，然後選擇 **Edit** (編輯)。

1. 在 **Edit** (編輯) 頁面上，展開 **Subscription filter policy** (訂閱篩選政策) 區段。

1. 選擇**以屬性為基礎的篩選**或**以承載為基礎的篩選**。

1. 在 **JSON editor** (JSON 編輯器) 欄位中，提供您篩選政策的 **JSON 內文**。

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` 範例會將 `RawMessageDelivery` 屬性設定為 SQS 訂閱。  

```
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` 範例會將 `FilterPolicy` 屬性設定為 SQS 訂閱。  

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

**適用於 Python 的 SDK (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 ]

**適用於 SAP ABAP 的開發套件**  
 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 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [SetSubscriptionAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

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

若要使用 套用篩選政策 CloudFormation，請使用 JSON 或 YAML 範本來建立 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. 選擇 **Create Stack** (建立堆疊)。

1. 在 **Select Template** (選擇範本) 頁面中，選擇 **Upload a template to Amazon S3** (上傳範本到 Amazon S3)、選擇檔案，並選擇 **Next** (下一步)。

1. 在 **Specify Details** (指定詳細資訊) 頁面上，執行下列作業：

   1. 在 **Stack Name** (堆疊名稱) 中輸入 `MyFilterPolicyStack`。

   1. 對於 **myHttpEndpoint**，輸入要訂閱到主題的 HTTP 端點。
**提示**  
若您沒有 HTTP 端點，請建立一個。

1. 在 **Options** (選項) 頁面上，選擇 **Next** (下一步)。

1. 在 **Review** (檢閱) 頁面上，選擇 **Create** (建立)。

# 在 Amazon SNS 中移除訂閱篩選條件政策
<a name="message-filtering-policy-remove"></a>

若要停止篩選傳送到訂閱的訊息，請以空的 JSON 內文覆寫訂閱的篩選政策來移除政策。移除政策後，訂閱會接受發佈給它的每個訊息。

## 使用 AWS 管理主控台
<a name="message-filtering-policy-remove-console"></a>

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在導覽面板上，選擇 **Subscriptions (訂閱)**。

1. 選取訂閱，然後選擇 **Edit** (編輯)。

1. 在 **Edit *EXAMPLE1-23bc-4567-d890-ef12g3hij456*** (EXAMPLE1-23bc-4567-d890-ef12g3hij456) 頁面上，展開 **Subscription filter policy** (訂閱篩選政策) 區段。

1. 在 **JSON editor** (JSON 編輯器) 欄位中，提供您篩選政策的空白 JSON 內文：`{}`。

1. 選擇**儲存變更**。

   Amazon SNS 套用您的篩選政策到訂閱。

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

若要使用 移除篩選條件政策 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-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 內文。