def split_by(tags: List[Tag], query: QueryObject, exclusive: bool = True) -> QueryObject
Transform a query by decorating result items with specified groups, such as tags or enum values which they are tagged with.
Effectively, it categorizes query results. For each item returned by the input query that is associated with a group, it additionally yields a tag in a (item, decorator) tuple. The transformed query object can be passed to other dbzero functions for further composition.
Parameters
-
tagsList[Tag]
A list of tags to split results by. -
queryQuery
The input query whose result set will be categorized. -
exclusivebool, default True
Controls handling of items belonging to multiple groups:True(default): Item appears only once, paired with one matching groupFalse: Item appears for every matching group
Returns
A new query yielding (item, decorator) tuples where item is from the original query and decorator is the matched group.
Examples
Split by string tags
Let's say you have objects tagged with "tag1", "tag2", etc. You can split a query to see which objects belong to each tag.
# Find all MemoTestClass objects and group them by a list of tags
query = db0.split_by(["tag1", "tag2", "tag3"], db0.find(MemoTestClass))
# The query returns (item, decorator) tuples
for item, tag_decorator in query:
print(f"Item with value {item.value} has '{tag_decorator}'")
# Example Output:
# Item with value 0 has 'tag1'
# Item with value 1 has 'tag2'
# Item with value 2 has 'tag3'
# Item with value 3 has 'tag1'Non-exclusive split
If an object has multiple tags, you can get a result for each tag by setting exclusive=False.
# An object tagged with both "tag1" and "tag2"
obj = SomeClass(100)
db0.tags(obj).add(["tag1", "tag2"])
# Exclusive (default) split will return the object only once
exclusive_query = db0.split_by(["tag1", "tag2"], db0.find(obj))
print(f"Exclusive results: {len(list(exclusive_query))}") # -> Exclusive results: 1
# Non-exclusive split will return the object for each matching tag
non_exclusive_query = db0.split_by(["tag1", "tag2"], db0.find(obj), exclusive=False)
print(f"Non-exclusive results: {len(list(non_exclusive_query))}") # -> Non-exclusive results: 2Compose with other queries
The result of split_by is a query itself and can be used in other operations.
# First, split items tagged "tag3" or "tag4" from items also tagged "tag1"
split_query = db0.split_by(["tag3", "tag4"], db0.find("tag1"))
# Then, from that result, find only the items that ALSO have "tag2"
# The decorators from split_by are retained
final_query = db0.find(split_query, "tag2")
for item, decorator in final_query:
print(f"Item {item.value} matched 'tag1', 'tag2', and was decorated with '{decorator}'")
# Example Output:
# Item 0 matched 'tag1', 'tag2', and was tagged also with 'tag3'
# Item 4 matched 'tag1', 'tag2', and was tagged also with 'tag4'
# ...