MQTT/Sorting and keeping/Wildcards

Wildcards

A subscription can be a filter rather than one topic. Plus stands for exactly one level and hash for everything below, so a room or a whole house is one subscription — if the topics were named for it.

A subscription does not have to name one topic. It can be a filter, with two wildcards in it, and the broker delivers every topic the filter matches.

Plus: one level

+ stands for exactly one level, whatever its name:

FilterMatchesDoes not match
home/+/temphome/kitchen/temp, home/garage/temphome/temp, home/kitchen/oven/temp

home/temp is the one that surprises people. It has two levels and the filter has three, and + is always exactly one of them. It cannot stand for none.

Hash: everything below

# stands for any number of levels from there on, and it can only be the last thing in a filter:

FilterMatchesDoes not match
home/#home, home/temp, home/kitchen/temp, home/kitchen/humidityoffice/desk/temp

It also matches the level it hangs from: home/# includes home itself. A filter of just # matches every topic on the broker, which is useful for watching what is going on and a bad idea on a busy one.

Topics that start with $, such as the $SYS/ statistics many brokers publish, are left out of # and +. A reader who wants them subscribes to $SYS/# by name.

Wooden pigeonholes arranged as a branching tree, one group of branches lit together
A filter takes a whole branch of the tree at once.Generated illustration

Naming for the filters you will want

Filters only work on levels, so the order of the levels decides what can be asked for. Name topics from the biggest thing to the smallest: house/floor/room/device/reading. Then the kitchen is house/ground/kitchen/#, the ground floor is house/ground/#, and every temperature in the house is house/+/+/+/temp. Put the room last and none of that is possible.

Common mistakes

  • Posting to a topic with a wildcard in it. Wildcards are for subscribing. home/+/temp is not a topic anything can be posted to.
  • # in the middle, as in home/#/temp. It is refused: # has to be last.
  • Levels in an order nobody can filter. temp/kitchen/home works exactly as well as home/kitchen/temp until the day you want everything in the house.

Edit this page — content/fundamentals/mqtt/wildcards.mdx

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Fundamentals on the forum →