Keyword clustering groups search queries that one page can satisfy. The workflow below takes a raw query export, turns it into clusters with embeddings and SERP data, labels them with an LLM, and maps each cluster to one URL. The same clusters then become the prompt set you use to track visibility in AI answers.
We rewrote this post in November 2026. The original from January 2024 predated AI Overviews in the US, AI Mode and most of the AI search products people use today, so the last part of the workflow is new.
Why cluster at all?
A site with a few hundred target queries can be planned by hand. Past a few thousand, manual grouping falls apart. People sort by shared words, and shared words are a poor proxy for shared intent. “Next.js sitemap” and “sitemap.xml app router” belong on the same page. “Next.js SEO” and “Next.js SEO audit” probably do not.
Clustering gives you three things:
- A page plan where each URL owns a distinct intent, so your pages stop competing with each other.
- A way to find gaps: clusters with demand and no page.
- A list of sub-questions for each page, which matters more now that AI search splits one question into many searches (see query fan-out).
Step 1: pull the queries
Use two sources and merge them.
Google Search Console. The UI export stops at 1,000 rows. Use the Search Analytics API or the BigQuery bulk export to get the full query list with clicks, impressions and position, ideally for 12 to 16 months. These are queries you already show up for, so they tell you how Google currently understands your site.
A keyword tool. Ahrefs, Semrush or similar, filtered to your topic, gives you demand you do not rank for yet. Pull search volume and, if the tool supports it, the top-ranking URLs per keyword. You will need those for SERP-overlap clustering.
Then clean the list:
- Lowercase and trim whitespace, remove exact duplicates.
- Remove branded queries for competitors unless you plan comparison pages.
- Drop queries with zero impressions and no volume.
- Keep a
sourcecolumn so you know where each row came from.
A mid-size technical site usually ends up with 3,000 to 20,000 queries after cleaning.
Step 2: choose a clustering method
There are two main approaches. They answer slightly different questions.
| SERP-overlap clustering | Embedding clustering | |
|---|---|---|
| Signal | Do the same URLs rank for both queries? | Do the queries mean similar things? |
| Data needed | Top 10 results per query | Only the query text |
| Cost | SERP API calls per query | Cheap, runs locally |
| Strength | Reflects how Google groups intent today | Works for new topics and low-volume queries |
| Weakness | Expensive at scale, noisy for long-tail queries | Can merge queries Google treats as different intents |
SERP overlap compares the top 10 URLs for each pair of queries. If two queries share, say, 3 or more URLs, Google seems to think one page can serve both. This is the closest thing to ground truth for “can these share a page”, because it is how the engine already behaves.
Embedding clustering converts each query into a vector with a sentence embedding model, then groups vectors that sit close together. It needs no SERP data, so you can cluster 20,000 queries in a couple of minutes on a laptop.
In practice we do both. Embeddings give a first pass over everything. SERP overlap then checks the clusters that carry real volume, and splits them where Google separates intents.
Step 3: embed and cluster in Python
This example uses sentence-transformers for embeddings and scikit-learn for clustering. HDBSCAN finds clusters of varying density and marks outliers as noise. Agglomerative clustering with a distance threshold is a simpler alternative when you want every query assigned.
# pip install sentence-transformers scikit-learn pandas
import pandas as pd
from sentence_transformers import SentenceTransformer
from sklearn.cluster import HDBSCAN, AgglomerativeClustering
df = pd.read_csv("queries.csv") # columns: query, impressions, volume, source
queries = df["query"].tolist()
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
emb = model.encode(queries, normalize_embeddings=True, batch_size=256)
# Option A: HDBSCAN, leaves outliers as -1
hdb = HDBSCAN(min_cluster_size=4, min_samples=2, metric="euclidean")
df["cluster_hdb"] = hdb.fit_predict(emb)
# Option B: agglomerative, every query gets a cluster
agg = AgglomerativeClustering(
n_clusters=None,
distance_threshold=0.35, # cosine distance, tune on a sample
metric="cosine",
linkage="average",
)
df["cluster_agg"] = agg.fit_predict(emb)
summary = (
df[df["cluster_hdb"] != -1]
.groupby("cluster_hdb")
.agg(size=("query", "count"),
impressions=("impressions", "sum"),
sample=("query", lambda s: list(s.head(8))))
.sort_values("impressions", ascending=False)
)
print(summary.head(20))
A few notes from running this on real query sets:
- With normalized embeddings, Euclidean distance ranks pairs the same way cosine distance does, so HDBSCAN works fine with
metric="euclidean". - Agglomerative clustering builds a full distance matrix. Above roughly 20,000 queries it gets slow and memory hungry. HDBSCAN scales better.
- Tune
distance_thresholdandmin_cluster_sizeon a sample of 300 queries you have grouped by hand. Read the clusters themselves, because the count alone tells you little. - HDBSCAN will often label 20 to 40% of long-tail queries as noise. That is fine. Re-run the noise points with looser settings, or attach each one to its nearest cluster centroid if the similarity is high enough.
- Any good embedding model works. Small open models are enough for short queries. If your queries are not in English, pick a multilingual model.
Checking clusters with SERP overlap
For clusters above your volume threshold, fetch the top 10 URLs for each query (from your keyword tool or a SERP API), then check pairwise overlap:
def overlap(a: set, b: set) -> int:
return len(a & b)
# serps: dict of query -> set of top-10 URLs
def split_by_serp(cluster_queries, serps, min_shared=3):
groups = []
for q in cluster_queries:
for g in groups:
if overlap(serps[q], serps[g[0]]) >= min_shared:
g.append(q)
break
else:
groups.append([q])
return groups
If an embedding cluster splits into two SERP groups, you probably need two pages. A common case: “headless CMS SEO” (informational guides rank) and “headless CMS SEO agency” (service pages rank) sit close in embedding space and share almost no results.
Step 4: label clusters with an LLM
Cluster IDs are useless to a content team. Send each cluster’s queries to an LLM and ask for structured output:
You label keyword clusters for a technical SEO site.
Queries (with monthly impressions):
{queries}
Return JSON with:
- label: a 3 to 6 word topic name
- intent: one of informational, commercial, transactional, navigational
- primary_query: the query a page title should target
- questions: up to 6 questions a user in this cluster wants answered
- merge_hint: true if this cluster looks like a duplicate of another topic
Run it with a fixed model version and low temperature, and save the raw output with the cluster ID. Then review. LLMs label well but will sometimes invent a theme that the queries do not support, especially for small clusters. A person should read every label for the top clusters by impressions.
The questions field matters later. It is the start of your sub-question list for each page and of your AI tracking prompts.
Step 5: map clusters to URLs
Now join the clusters to your site. For each cluster:
- Find the URL that already gets most of the cluster’s clicks and impressions in Search Console (the
pagedimension in the API). - If one URL clearly owns it, that is the target page.
- If two or more URLs split the impressions, you have cannibalization. Pick one, merge content, redirect or re-target the other.
- If no URL gets impressions, you have a gap. Decide whether it deserves a new page or a section on an existing one.
Write the result to a simple mapping table and keep it in version control:
| cluster_id | label | intent | primary_query | target_url | status |
|---|---|---|---|---|---|
| 14 | Next.js sitemap setup | informational | next.js sitemap | /guides/technical-seo-for-javascript-and-headless-sites/ | existing |
| 22 | llms.txt file format | informational | what is llms.txt | /guides/llms-txt/ | existing |
| 31 | headless CMS SEO risks | informational | headless cms seo | none | gap |
This table drives everything else: briefs, internal links (pages in neighboring clusters should link to each other), and the URL structure when you plan new sections.
Where technical SEO comes in
Clustering is usually treated as content work. On JavaScript and headless sites it also exposes technical problems:
- A cluster mapped to a page that gets no impressions at all often points to an indexing issue, not a content issue. Check indexability before rewriting.
- Clusters split across parameter URLs (
?sort=,?ref=) mean canonicals are not doing their job. See canonical URL. - If the target page renders its main content client-side, AI crawlers will never see the answers you write. See technical SEO for JavaScript and headless sites.
Step 6: reuse clusters as your AEO and GEO prompt set
This is the part that did not exist in 2024.
AI answer engines (Google AI Overviews and AI Mode, ChatGPT search, Perplexity, Gemini, Copilot) do not have rankings you can track. To measure AI visibility, you run a fixed set of prompts and record whether your pages are cited and your brand is mentioned. The hard part is choosing prompts that represent real demand. Your clusters already solve that.
Turn each important cluster into two to four prompts:
- The
primary_queryrewritten as a natural question. - One or two items from the LLM’s
questionslist. - One comparison or recommendation prompt where it fits (“best way to add hreflang in a headless CMS”).
Store the prompts next to the cluster mapping, with the target URL. Then:
- Run each prompt in each engine on a schedule, several times per run, because answers vary.
- Record cited URLs, brand mentions and which competitors appear.
- Report citation rate by cluster, not by single prompt.
When a cluster has a strong page in classic search but no citations in AI answers, look at retrieval before content. Is the relevant AI crawler allowed? Is the content in the raw HTML? Does the page answer the sub-questions in passages that stand alone? Our guide on how LLMs choose sources walks through that retrieval chain.
Because the prompts come from clusters, the results map straight back to URLs and to the content plan. “Cluster 31 has zero citations and no page” is a decision you can act on.
Checklist
- Full query export from the Search Console API or BigQuery, 12 to 16 months
- Keyword tool export with volume and top-ranking URLs
- Cleaned, deduplicated list with a
sourcecolumn - Embedding clusters, parameters tuned on a hand-labeled sample
- SERP-overlap check on high-volume clusters
- LLM labels with intent, primary query and questions, reviewed by a person
- Cluster to URL mapping with cannibalization and gaps marked
- Technical checks on target pages: indexed, canonical, content in HTML
- Prompt set built from clusters and tracked across AI engines
How often should you re-run it?
Re-cluster every quarter, or after a launch or migration. Query language shifts, new AI features change which queries send clicks, and your own new pages change which URL owns which cluster. Keep the cluster IDs stable between runs where you can (match new clusters to old ones by overlap of queries) so your AI visibility trend lines stay comparable.
If you want this done on your site, including the technical fixes the mapping surfaces, see our technical SEO and generative engine optimization services.