You want to know which topics recent Hacker News discussions are about. The answer is in story titles and comment threads, but free text is hard to count: one comment says “postgres”, another says “PostgreSQL”, and a third writes a whole phrase. A tally over raw words splits one topic into many. Sending every comment to an LLM on every run also costs time and money.
The same split hurts an agent or a retrieval step that filters by topic. A topic filter finds the messages about a thing only when they store a name it matches, and “JFK” and “John Kennedy” share no substring, so a search for one misses the other. Normalized topics give an agent one name to look up for each thing, plus the other common names when a thing has several.
This tutorial builds a CocoIndex v1 pipeline for both problems. It reads the 10 latest Hacker News stories and their comments, asks an LLM to pull normalized topics out of every message, and ranks the topics with a weighted SQL score in Postgres. When you run it again, only text that CocoIndex has not seen goes to the LLM.
The source is two async functions over the Algolia HN API (the public search API for Hacker News). The sibling post, Turn a polling API into an incremental source, covers that side: setup, the fetch functions, row ownership, failed fetches and reruns. This post covers the other half: the prompt that turns free text into normalized topics, and the SQL score that turns those topics into a leaderboard.
The full example is in the CocoIndex v1 repo.
How the pipeline fits together
Each recent story becomes its own processing component: a unit of work that CocoIndex runs, tracks and cleans up on its own. The component fetches the story and its comments, extracts topics from each message with an LLM, and declares rows into 2 Postgres tables:
hn_messages: one row per message (the story and each comment), so a topic search can show the message texthn_topics: one row per topic mention, keyed on(topic, message_id)
Because the same topic mentioned in many messages becomes many hn_topics rows, ranking becomes a SQL aggregate. Re-running catches up on new stories, and because per-message extraction is memoized (its result is cached and reused while the inputs and the code stay the same), only content CocoIndex hasn’t seen hits the LLM.
Step 1: Normalize topics in the prompt
The hard part is getting topics back in a shape you can rank. Raw model output can give you “postgres” in one comment and “PostgreSQL” in another, or a whole phrase like “books for autistic kids” as one topic, and none of those add up to one score.
The normalization rules are in the prompt, written as the description of a Pydantic field. They ask the model to split combined phrases into parts, keep proper nouns canonical (such as “PostgreSQL”), use a person’s preferred name, and return each common name of one thing:
class TopicsResponse(BaseModel):
"""Response containing a list of extracted topics."""
topics: list[str] = Field(
description="""List of extracted topics.
Each topic can be a product name, technology, model, people, company name, business domain, etc.
Capitalize for proper nouns and acronyms only.
Use the form that is clear alone.
Avoid acronyms unless very popular and unambiguous for common people even without context.
Examples:
- "Anthropic" (not "ANTHR")
- "Claude" (specific product name)
- "React" (well-known library)
- "PostgreSQL" (canonical database name)
For topics that are a phrase combining multiple things, normalize into multiple topics if needed. Examples:
- "books for autistic kids" -> "book", "autistic", "autistic kids"
- "local Large Language Model" -> "local Large Language Model", "Large Language Model"
For people, use preferred name and last name. Examples:
- "Bill Clinton" instead of "William Jefferson Clinton"
When there're multiple common ways to refer to the same thing, use multiple topics. Examples:
- "John Kennedy", "JFK"
"""
)
Each topic the model returns becomes its own hn_topics row, so 2 spellings of one thing split its score: without these rules, “PostgreSQL” and “postgres” count as 2 topics. The prompt names “PostgreSQL” as the canonical form and asks for names that are clear alone, which pulls common variants toward one spelling. It does not list every variant, so how far the merge goes depends on the model.
Extraction itself is one CocoIndex function: text in, a list of topics out. It calls the model through litellm, a library with one API for many LLM providers, so any provider works. response_format=TopicsResponse asks for JSON in that schema, and model_validate_json checks it. The function reads at most the first 4,000 characters of a message.
memo=True caches the result, so an unchanged message is not sent to the model twice while the prompt, the model, and the function’s code stay the same. The prompt and LLM_MODEL live outside the function body, so deps declares them, and editing either one invalidates the cached results:
@coco.fn(
memo=True,
deps={
"model": LLM_MODEL,
"prompt": TopicsResponse.model_fields["topics"].description,
},
)
async def extract_topics(text: str | None) -> list[str]:
if not text or not text.strip():
return []
response = await acompletion(
model=LLM_MODEL,
messages=[
{"role": "user", "content": f"Extract topics from the following text:\n\n{text[:4000]}"}
],
response_format=TopicsResponse,
)
content = response.choices[0].message.content
return TopicsResponse.model_validate_json(content).topics
What you see. For a message that contains “books for autistic kids”, the prompt asks for ["book", "autistic", "autistic kids"], not one topic for the whole phrase. An empty or blank message returns [] without a model call. The default model is gemini/gemini-2.5-flash; set LLM_MODEL to use another provider.
Quick check: you add a new example line to the TopicsResponse description. Which messages go to the LLM on the next run?
Every non-empty message in the 10 listed stories (a blank or missing text returns [] without a model call). The field description is the "prompt" entry in deps, so editing it changes the logic of extract_topics, and every cached result for it misses once. After that run, unchanged messages hit the cache again. Changing LLM_MODEL has the same effect.
Step 2: Declare a row per message and per topic
The 2 target tables are plain dataclasses. A thread and each of its comments both become an HnMessage (distinguished by content_type), and every extracted topic becomes an HnTopic keyed on (topic, message_id):
@dataclass
class HnMessage:
id: str
thread_id: str
content_type: str # "thread" or "comment"
author: str | None
text: str | None
url: str | None
created_at: datetime | None
@dataclass
class HnTopic:
topic: str
message_id: str
thread_id: str
content_type: str
created_at: datetime | None
process_thread fetches one story, extracts topics for the story and every comment, and declares the rows as target states: rows that should exist in Postgres. You declare what should exist; CocoIndex works out the inserts, updates, and deletes. The story’s text is its title, plus its body when it has one; fetch_thread flattens the nested comment tree into one list:
@coco.fn
async def process_thread(thread_id: str, targets: TableTargets) -> None:
async with aiohttp.ClientSession() as session:
thread = await fetch_thread(session, thread_id)
thread_topics = await extract_topics(thread.text)
targets.messages.declare_row(row=HnMessage(
id=thread.id, thread_id=thread.id, content_type="thread",
author=thread.author, text=thread.text, url=thread.url, created_at=thread.created_at,
))
for topic in thread_topics:
targets.topics.declare_row(row=HnTopic(
topic=topic, message_id=thread.id, thread_id=thread.id,
content_type="thread", created_at=thread.created_at,
))
for comment in thread.comments:
comment_topics = await extract_topics(comment.text)
targets.messages.declare_row(row=HnMessage(..., content_type="comment", ...))
for topic in comment_topics:
targets.topics.declare_row(row=HnTopic(..., content_type="comment", ...))
What you see. A story with 2 comments gives 3 hn_messages rows that share one thread_id. Its hn_topics rows carry the same thread_id and the content_type of the message they came from. The story’s own row has message_id equal to thread_id.
app_main mounts the 2 tables and starts one process_thread per listed story with coco.mount_each, keyed by the story ID. The sibling post walks through it in Wire up the app.
Quick check: why is hn_topics keyed on (topic, message_id) and not on topic alone?
With topic alone as the key, all mentions of “Rust” would collapse into one row, and there would be nothing to count. With (topic, message_id), each message that mentions “Rust” gets its own row, so SUM ... GROUP BY topic turns mentions into a score.
Step 3: Rank topics with a weighted SQL score
Trending is a SQL query over hn_topics. Each row contributes a weight to its topic’s score: a thread-level mention counts 5 and a comment-level mention counts 1, because a topic in the story title is the subject, while a topic in a comment is supporting discussion. Group by topic, order by score:
SELECT
topic,
SUM(CASE WHEN content_type = 'thread' THEN 5 ELSE 1 END) AS score,
MAX(created_at) AS latest_mention,
COUNT(DISTINCT thread_id) AS thread_count
FROM coco_examples.hn_topics
GROUP BY topic
ORDER BY score DESC, latest_mention DESC
LIMIT 20
The weights are the constants THREAD_LEVEL_MENTION_SCORE = 5 and COMMENT_LEVEL_MENTION_SCORE = 1 in main.py. Here is the score over 8 example rows:
Weighting thread mentions 5 to 1 over comment mentions makes the ranking favor the subjects of stories over topics mentioned in passing. The playground below runs both steps over 6 messages. Switch between topics as written and topics as the prompt asks for them, then move the weight: as written, one database splits into 3 rows, and at a weight of 1, “JFK” from 2 comments outranks “autistic kids” from a story title.
Normalize the topics, then weight the score
Illustrative messages; real output depends on the modelextract_topicsShow HN: We replaced Redis with Postgres for our job queue
- Redis
- Postgres
PostgreSQL with SKIP LOCKED has handled this for us for years.
- PostgreSQL
postgres is fine until you need pub/sub at scale, then Redis again.
- postgres
- Redis
Ask HN: Good books for autistic kids?
- books for autistic kids
My daughter loved a John Kennedy biography.
- John Kennedy
Same here: JFK books were a hit with our autistic son.
- JFK
- books
- autistic
SUM(CASEWHEN content_type = 'thread'THEN 5 ELSE 1END) AS score- 1 Redis 5 + 1 = 6
- 2 books for autistic kids 5
- 3 Postgres1 of 3 spellings 5
- 4 autistic 1
- 5 books 1
- 6 JFK 1
- 7 John Kennedy 1
- 8 postgres1 of 3 spellings 1
- 9 PostgreSQL1 of 3 spellings 1
As written, one database is split across 3 rows: Postgres (5), PostgreSQL (1), postgres (1). Normalized, PostgreSQL gets all 7 points.
The same score, filtered to one topic and grouped by thread_id, ranks which threads are driving a given topic (see What to try next).
Quick check: a story’s title mentions “Rust”, and 3 of its comments mention “Rust” too. What does that story add to the score of “Rust”?
8: 5 for the thread-level mention plus 1 for each of the 3 comment-level mentions. It adds 1 to thread_count, because all 4 rows share one thread_id.
Run it
Set up Postgres, the .env file and the example as in the sibling post’s Prerequisites. Then, from examples/hn_trending_topics, build the index and query it:
cocoindex update main # fetch the 10 latest stories, extract topics, write both tables
python main.py # top 20 trending topics + interactive search
python main.py "rust" # search content for one topic
cocoindex update loads .env; python main.py reads POSTGRES_URL before it loads .env, so export the variable in your shell if you changed it from the default.
What you see. python main.py prints Top 20 Trending Topics: and a row of dashes, then one line per topic such as 1. <topic, padded to 30 characters> (score: N, threads: N), then asks Enter topic to search (or Enter to quit):. A search prints Searching for '<text>' related content: and a row of dashes. It matches topics that contain your text, ignoring case, and prints up to 5 of the newest matching topic mentions, each as [comment] by <author>: <first 100 characters>... (or [thread] for a story). A message that matches through 2 topics appears twice. The topics depend on what was posted when you ran the pipeline.
What a re-run does
Every cocoindex update main fetches the 10 latest stories again and runs process_thread for each one. The expensive step, the LLM call, runs only where the extract_topics cache misses:
The “New story” and “Story drops out” rows follow from row ownership: rows belong to the component that declared them, and a story that leaves the 10 latest has no component, so CocoIndex deletes the rows it owned. The sibling post’s second-run section has a simulator for these cases. For the ranking, it means the leaderboard describes the 10 stories listed on the last run, not every story the pipeline has seen.
What to try next
-
Change the weights. Edit
THREAD_LEVEL_MENTION_SCOREandCOMMENT_LEVEL_MENTION_SCOREinmain.py. The score is computed at query time, sopython main.pyshows the new ranking without re-running the pipeline. -
Cover more stories. Raise
MAX_THREADSand runcocoindex update main. The new stories go to the LLM; the stories already indexed hit the cache. -
Switch the model. Set
LLM_MODELto another litellm model name and add its API key to.env. Because the model is indeps, the next run re-extracts every message. -
Rank the threads behind a topic. Filter the score to one topic and group by thread:
SELECT thread_id, SUM(CASE WHEN content_type = 'thread' THEN 5 ELSE 1 END) AS score FROM coco_examples.hn_topics WHERE topic = 'Rust' GROUP BY thread_id ORDER BY score DESC
Larger extensions on the same pipeline:
- Trending dashboards. Serve the leaderboard and the threads behind each topic to a page that refreshes after each run.
- Sentiment-aware trends. Add a second extraction step for sentiment to track how people feel about a topic as well as how often it comes up.
- Contributor tracking. Every message stores its
author, so you can find who drives conversation around a given topic. - A knowledge graph. Feed the topics into a graph linking companies, products, and people mentioned across Hacker News.
Each of these is a new transform or target on the same declared source. The extraction and the ranking, the 2 pieces this post focused on, stay as they are.
Further reading:
- The example on GitHub:
main.py,models.pyand the README - Turn a polling API into an incremental source: the fetch side of this pipeline, row ownership and failed fetches
- Processing components: mounting, ownership and cleanup
- CocoIndex on GitHub: the open-source framework and its source
Frequently asked questions
How do I extract structured topics from text with an LLM in CocoIndex v1?
Write one CocoIndex function: text in, a list of topics out. It calls the model through litellm with a Pydantic response_format (here TopicsResponse), so any provider works and the response is validated. Wrap it in @coco.fn(memo=True) so an unchanged message is not sent to the model twice while the prompt, the model and the function's code stay the same.
Why normalize topics, and how does the prompt do it?
Each topic the model returns becomes its own hn_topics row, so "postgres" in one comment and "PostgreSQL" in another would split one score, and a whole phrase returned as one topic never aggregates. The normalization rules are in the Pydantic field description (the prompt): it splits combined phrases into parts ("books for autistic kids" becomes "book", "autistic", "autistic kids"), asks for canonical proper nouns such as "PostgreSQL", and emits each common name of one thing ("JFK", "John Kennedy"). Normalized topics also help an agent or a search that filters by topic, because messages about one thing share the names it looks up. The prompt does not list every variant, so how far the merge goes depends on the model.
How are trending topics scored and ranked?
Trending is a SQL query over hn_topics. Each row contributes a weight to its topic's score: a thread-level mention counts 5, a comment-level mention counts 1, because a topic in the story title is the subject while a topic in a comment is supporting discussion. Group by topic, order by score. The same score filtered to one topic and grouped by thread_id ranks which threads drive it.
Why is the hn_topics table keyed on (topic, message_id)?
Because the same topic mentioned in many messages should become many rows, one per mention. Keying on (topic, message_id) keeps each mention as its own row instead of collapsing them, which is what lets a simple SUM ... GROUP BY topic turn mentions into a trending score.
Does CocoIndex re-run the LLM on every message each run?
No. Per-message extraction is memoized (@coco.fn(memo=True)), so the LLM calls run only for content CocoIndex hasn't seen. The prompt and LLM_MODEL are declared in deps, so editing either one re-extracts every message once. The source is a one-shot catch-up per run: re-run cocoindex update main to pick up new stories, and only new or edited messages hit the model. A story that drops out of the 10 latest has its rows deleted.
See What a re-run does.
Where is the custom Hacker News source explained?
The source here is two small async functions over the Algolia HN API, handed to coco.mount_each as one processing component per story. This post covers topic normalization and the trending ranking. The source side (setup, fetching stories and flattening the comment tree, row ownership, failed fetches and reruns) is in the sibling post, Turn a polling API into an incremental source: Hacker News.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.


