Skip to content

Commit 1cda6f0

Browse files
committed
Make hierarchy search more efficient
1 parent 83c58af commit 1cda6f0

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

pystac/stac_object.py

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -138,26 +138,41 @@ def remove_hierarchical_links(self, add_canonical: bool = False) -> List[Link]:
138138
return remove
139139

140140
def target_in_hierarchy(self, target: Union[str, STACObject]) -> bool:
141-
"""Recursively collects all the targets referred to by the hierarchical
142-
links of the current STACObject.
141+
"""Determine if target lin is somewhere in the hierarchical link tree of
142+
a STACObject.
143+
144+
Args:
145+
target: A string or STACObject describing the target to search for
143146
144147
Returns:
145-
Set[Union[str, STACObject]]: All encountered targets
148+
bool: Returns True if the target was found in the hierarchical link tree
149+
for the current STACObject
146150
"""
147151

148152
def traverse(
149153
obj: Union[str, STACObject], visited: Set[Union[str, STACObject]]
150-
) -> Set[Union[str, STACObject]]:
154+
) -> bool:
155+
if obj == target:
156+
return True
151157
if isinstance(obj, str):
152-
return visited
158+
return False
159+
160+
new_targets = [
161+
link.target
162+
for link in obj.links
163+
if link.is_hierarchical() and link.target not in visited
164+
]
165+
if target in new_targets:
166+
return True
167+
168+
for subtree in new_targets:
169+
visited.add(subtree)
170+
if traverse(subtree, visited):
171+
return True
153172

154-
hierarchical_links = [link for link in obj.links if link.is_hierarchical()]
155-
new_targets = set([link.target for link in hierarchical_links]) - visited
156-
for target in new_targets:
157-
visited = traverse(target, visited.union(set([target])))
158-
return visited
173+
return False
159174

160-
return target in traverse(self, set([self]))
175+
return traverse(self, set([self]))
161176

162177
def get_single_link(
163178
self,

0 commit comments

Comments
 (0)