How do I target an entity based on a uri and distance to town?

How do I target an entity based on a uri and distance to town?
Basically I need to select an entity that is not inside the town territory, and it can be any entity with that specific uri. For example, any oak tree near the town but not inside it.

I could check all the child from the root entity (the terrain itself) for those conditions, but it would be super expensive.