Premier League Predictor: FastAPI & Redis — Chapter 5, Exercise 3 ================================================================= TASK Fetch the expert's prediction across five fixtures using a pipelined HGET, then list the same fixtures' prediction keys using SCAN. Explain why SCAN returns more keys than the five you asked about, and when each approach is the right one. SOLUTION async with r.pipeline(transaction=False) as p: for f in [11, 12, 13, 14, 15]: p.hget(f"fixture:{f}:predictions", "expert") print(await p.execute()) keys = sorted([k async for k in r.scan_iter(match="fixture:*:predictions")]) Real results: pipelined HGET -> ['0-1', '0-2', '0-3', '0-4', '0-5'] SCAN -> ['fixture:11:predictions', 'fixture:12:predictions', 'fixture:13:predictions', 'fixture:14:predictions', 'fixture:15:predictions', 'fixture:1:predictions'] SCAN returned six keys, not five, because its pattern matches every key in the whole keyspace that looks like fixture:*:predictions, including fixture:1:predictions from an earlier test. SCAN has no notion of "the fixtures I care about" — it walks everything and filters by name. When to use which: - Pipelined HGET: the fixture IDs are already known (for example from the gameweek's fixtures Set). One round trip, touches only those keys. - SCAN: the IDs are not known and a full sweep is genuinely needed, such as a one-off maintenance job. It touches the entire keyspace and its cost grows with the total number of keys, not the number you want. If "all of one source's predictions" becomes a frequent query, the Redis-style answer is to maintain a second key for it — for example a Set per source listing the fixture IDs it has predicted — written alongside every HSET. That is extra bookkeeping the code owns; a relational index would maintain it automatically. WHY THIS WORKS AS AN ANSWER ---------------------------- It runs both approaches, explains the extra SCAN result from what SCAN actually matches on, and ties the choice to whether the keys are already known — which is the real deciding factor when there is no index.