A Segment is a subset of a Collection: it's a saved filter of your Collection.
Segments are designed for those who want to systematically visualize data according to specific sets of filters. It allows you to save filter configurations so user don’t have to do repetitive actions every day.
Segments can be configured from the interface, without the need to write any code.
Sometimes, Segment filters are complicated and closely tied to your business. Forest Admin allows you to code how the Segment is computed.
The only requirement when implementing a Segment from your agent is to return a valid
from forestadmin.datasource_toolkit.context.collection_context import CollectionCustomizationContext
from forestadmin.datasource_toolkit.interfaces.query.aggregation import Aggregation, PlainAggregation, PlainAggregationGroup
from forestadmin.datasource_toolkit.interfaces.query.condition_tree.nodes.leaf import ConditionTreeLeaf
async def most_purchased_segment(context: CollectionCustomizationContext):
# Query the ids of the 10 most populate products by looking at the `orders` collection.
rows = await context.datasource.get_collection("order").aggregate(
# Return a condition tree which matches those records
field="id", operator=Operator.IN, value=[row["group"]["product_id"] for row in rows]