Skip to content
Home » Starlark Custom Expressions in Bloomreach

Starlark Custom Expressions in Bloomreach

    Starlark Custom Expressions in Bloomreach

    Custom expressions in Bloomreach Data hub let you generate attribute values with code during schema mapping. You use them to combine fields, calculate values, transform data beyond the built-in transformations, and read nested or variant-level data.

    The language is Starlark, a Python dialect built for safe, deterministic execution. Bloomreach documentation describes it as Python-like code and refers to the Starlark specification for the full list of functions and methods.

    How mature is your CRM setup?

    Find out in minutes with a free CRM maturity check.

    Get Your Free Check

    Three rules cover most of what you need:

    1. Read data through the br object with bracket notation.
    2. Single-line expressions return their value automatically. Multi-line expressions must end with return.
    3. Python code that uses features Starlark does not have will fail.

    Where custom expressions run

    Custom expressions belong to schema mapping in a Data hub item collection. For each schema attribute, you choose where its value comes from. A custom expression is the right choice when one field is not enough and the value needs logic: a calculation, a condition, or data from several fields.

    If you only need to copy a field or pull a value out of a nested structure, use a direct field mapping or JSON Path instead. They are simpler to maintain and do not count against expression limits.

    Accessing data with the br object

    What you can read depends on the level of the attribute you are configuring.

    Fields sit under fields:

    br['product']['fields']['brand']
    br['variant']['fields']['color']

    Two details cause most access errors:

    • Dot notation does not work. br.product.fields.brand fails. Always use brackets and quoted field names.
    • Field names are case-sensitive. If your source field is Color, then br['product']['fields']['color'] will not find it.

    What Starlark does not support

    Developers who write regular Python hit the same errors repeatedly. Starlark intentionally leaves out several Python features:

    Python habitIn StarlarkUse instead
    if x is NoneNo is operatorif x == None
    round(x, 2)No round() built-inLeave rounding to display, or truncate with int(x * 100) / 100.0
    try / exceptNo exception handlingCheck values before using them
    while loopsNot availablefor loops over a list or range()
    importNo imports or external librariesBuilt-in functions and methods only

    Functions you can rely on include len(), min(), max(), sorted(), range(), any(), str(), int() and float(). Common string methods include .lower(), .upper(), .strip(), .split(), .replace(), .removeprefix() and .removesuffix(). Lists support .append(), .remove() and .index().

    Handling missing fields

    Product feeds are rarely complete. Accessing a field that does not exist stops the expression. Use .get() with a default value for any field that can be missing:

    br['product']['fields'].get('brand', '')

    Use == None when you need to branch on a missing value, and check values before converting them with float() or int(). A conversion of an empty string fails.

    Examples

    1. Normalize text

    Lowercase a category and remove stray spaces. A single-line expression needs no return.

    br['product']['fields']['category'].strip().lower()

    2. Combine product and variant fields

    A variant-level attribute that joins the parent product’s brand with the variant’s color, with safe defaults:

    brand = br['product']['fields'].get('brand', '')
    color = br['variant']['fields'].get('color', '')
    return brand + " - " + color

    3. Calculate margin percentage

    Values imported from flat files arrive as strings, so convert them before calculating. Check the inputs first, because Starlark has no try:

    sale_raw = br['product']['fields'].get('sale_price', '')
    cost_raw = br['product']['fields'].get('cost_price', '')
    
    if sale_raw == '' or cost_raw == '':
        return 0.0
    
    sale = float(sale_raw)
    cost = float(cost_raw)
    
    if sale == 0:
        return 0.0
    
    return (sale - cost) / sale * 100.0

    If the values are already numeric in your records, you can skip the conversion.

    4. Stock level from variant quantities

    A product-level attribute that sums variant stock and returns a bucket:

    total = 0
    for variant in br['product']['variants']:
        total += variant['fields'].get('quantityAvailable', 0)
    
    if total < 1:
        return "oos"
    elif total < 11:
        return "low"
    return "high"

    Change the thresholds to match your assortment, and use the same labels across all collections so segments and filters stay consistent.

    5. Flag products with any variant in stock

    A shorter alternative when you only need a true or false value:

    return any([v['fields'].get('quantityAvailable', 0) > 0 for v in br['product']['variants']])

    6. Lowest variant price

    A “from” price for product tiles and emails:

    prices = [float(v['fields']['price']) for v in br['product']['variants'] if v['fields'].get('price', '') != '']
    if len(prices) == 0:
        return 0.0
    return min(prices)

    Limits and what happens when an expression fails

    Each custom expression runs under two limits:

    • Time limit: the expression must finish within a set time.
    • Step limit: the number of internal operations is capped.

    If an expression exceeds a limit, the attribute is ignored, or Data hub follows the exceptional scenario configuration you set for that attribute. There is also a global timeout per item. If the combined processing of all custom expressions on one item takes too long, the update of that item fails. You can see these failures under Jobs.

    To stay within limits:

    • Access only the data you need. If you need one variant, read it directly instead of looping through all of them.
    • Avoid loops where a direct field access works.
    • Move heavy calculations upstream to the source system before data reaches Data hub.

    Set the exceptional scenario for each attribute deliberately. A silent fallback can hide a broken expression for weeks, while a visible failure in Jobs gets fixed. When Voxwise reviews a Data hub setup, failed jobs and attribute fallbacks are one of the first things checked, because they often explain gaps in recommendations or segments later.

    How mature is your CRM setup?

    Find out in minutes with a free CRM maturity check.

    Get Your Free Check

    Common mistakes

    • Using dot notation instead of brackets.
    • Wrong capitalization of a field name.
    • Missing return at the end of a multi-line expression.
    • Calling float() on an empty or missing value.
    • Using Python features Starlark does not have: is, round(), try, while, import.
    • Looping through all variants when one direct access would do.

    FAQ

    What language do Bloomreach Data hub custom expressions use?

    Starlark, a Python dialect. Bloomreach documentation calls it Python-like code and points to the Starlark specification for available functions and methods.

    Why does my multi-line custom expression return nothing?

    Multi-line expressions must end with a return statement. Single-line expressions return their value automatically.

    Can custom expressions call APIs or import libraries?

    No. Expressions can only use the record data in the br object and the built-in Starlark functions and methods.

    Why does my expression fail with a field that clearly exists?

    Field names are case-sensitive and must use bracket notation. Check the exact field name in your records, and use .get() for fields that are not present on every record.

    What happens if a custom expression hits the step or time limit?

    The attribute is ignored, or Data hub applies the exceptional scenario configuration for that attribute. If all expressions on one item exceed the global timeout, the item update fails and the failure appears in Jobs.

    Make your schema mapping reliable

    Custom expressions are the place where feed data turns into attributes that recommendations, search and campaigns depend on. A single unchecked expression can leave thousands of items with empty values.

    Voxwise helps retail teams review Data hub schema mappings, fix failing expressions and design attributes that work across Bloomreach Marketing and Search.

    Tags: