redis/redis-py · error · ValueError
collect sort_by must contain at least one field
Error message
collect sort_by must contain at least one field
What it means
Raised by the collect reducer constructor when sort_by is provided but resolves to zero sort fields (e.g. an empty list). COLLECT's SORTBY clause needs at least one Asc/Desc field; an empty sort list is a caller bug.
Solutions
- Omit sort_by entirely if no ordering is needed.
- Pass at least one Asc or Desc instance: collect(sort_by=Desc('price')).
- Guard dynamic lists: only set sort_by when it is non-empty.
Example fix
// before
r = collect(fields='*', sort_by=sort_list) # sort_list == []
// after
from redis.commands.search.aggregation import Desc
r = collect(fields='*', sort_by=sort_list or Desc('price'))
# or omit it
r = collect(fields='*') Defensive patterns
Strategy: validation
Validate before calling
sort_by = sort_by if (isinstance(sort_by, (Asc, Desc)) or (sort_by and len(list(sort_by)) > 0)) else None collect(fields=fields, sort_by=sort_by)
Try / catch
try:
r = collect(fields=fields, sort_by=sort_by)
except ValueError:
r = collect(fields=fields) Prevention
- Omit sort_by entirely when no ordering is needed.
- Build sort lists from concrete Asc/Desc instances.
When it happens
Trigger: Calling collect(sort_by=[]) or collect(sort_by=iter([])). Passing a filtered list that became empty.
Common situations: Building sort_by dynamically from user input that produced no fields. Mixing up Asc/Desc instances with raw strings so the list is structurally empty after processing.
Related errors
- collect fields must be '*' or a non-empty list of names
- Cannot use FIELDNAME alias with no field
- Did not receive a SortByField.
- AGGREGATION requires exactly one aggregation spec per key
- At least one tag must be specified
AI-assisted analysis of redis/redis-py@6a6b581b48 (2026-08-10).
Data as JSON: /api/errors/e177c6e184b3d5ca.
Report an issue: GitHub.
Appendix: source
Thrown at redis/commands/search/reducers.py:253
if not names or any(not n.strip() for n in names):
raise ValueError(
"collect fields must be '*' or a non-empty list of names"
)
names = [_ensure_at_prefix(n) for n in names]
args += ["FIELDS", str(len(names))] + names
# DISTINCT (optional)
if distinct:
args += ["DISTINCT"]
# SORTBY (optional)
if sort_by is not None:
sort_fields = [sort_by] if isinstance(sort_by, (Asc, Desc)) else sort_by
sort_args: list[str] = []
for f in sort_fields:
sort_args += [_ensure_at_prefix(f.field), f.DIRSTRING]
if not sort_args:
raise ValueError("collect sort_by must contain at least one field")
args += ["SORTBY", str(len(sort_args))] + sort_args
# LIMIT (optional)
if limit is not None:
offset, count = limit
args += ["LIMIT", str(offset), str(count)]
super().__init__(*args)
View on GitHub (pinned to 6a6b581b48)