Filter messages in Pub/Sub subscriptions
Filtering messages in Google Cloud Pub/Sub subscriptions allows users to selectively receive only the messages that match specific criteria, based on message attributes or content. This feature helps streamline message processing and reduce unnecessary overhead by ensuring that subscribers only receive messages relevant to their needs.
Pub/Sub supports message filtering through subscription filtering, which allows users to define subscription filters using subscription policies. These filters can be configured to match messages based on attributes such as message attributes, message data, or message metadata.
Users can specify filtering conditions using Pub/Sub’s filtering language, which supports logical operators, comparison operators, and regular expressions. For example, users can define filters to only receive messages with specific attributes or values, messages containing certain keywords or patterns in their content, or messages with timestamps within a certain range.
Prerequisites
GCP account
Open Console.
Open Menu > Pubsub > Subscriptions
Click on create Subscription
Give the subscription ID.
Choose the pubsub topic.
the delivery type.
Choose the retention period for message. Choose the expiration period.
Give the Acknowledgement time
In subscription filter give the filter syntax.
These filter types you can use to filter the messages.
Filter | Description |
attributes:domain | Messages with the domain attribute |
NOT attributes:domain | Messages without the domain attribute |
attributes.domain = “com” | Messages with the domain attribute and the value of com |
attributes.domain != “com” | Messages without the domain attribute and the value of com |
hasPrefix(attributes.domain, “co”) | Messages with the domain attribute and a value that starts with co |
NOT hasPrefix(attributes.domain, “co”) | Messages without the domain attribute and a value that starts with co |
Click create. The subscription with message filtering will be created