GrepBoard/Manuals
605 manuals ·

Cluster search queries by intent with none added or lost

·Tested on Claude Sonnet 5.5 · 2026-10·Test scope ↓·8 steps

Ask Claude to group 300 Search Console queries by intent, then check by script that none were added or lost and impressions still add up. Six runs shown.

You ask for 300 queries grouped by intent and get back 297 lines. Which three are gone is hard to see by eye. Below: a prompt that clusters a made-up home coffee machine shop's queries and impressions (query,impressions, 300 rows), and a script that checks the output against the input.

[1] The input is one CSV. Impressions add up to 106,716. It includes pairs that differ only in word order, such as coffee machine best and best coffee machine, on purpose.

queries.en.csv
query,impressionscheapest bean to cup machine,76home coffee machine reviews,227mocha house coupon,219milk frother noise,100cold brew maker how to use,387…

[2] Put the data at the top and the instructions below it, as Claude's docs advise for long documents. The first rule restricts the model to the list you gave it, from the reduce hallucinations guide, and says why.

text
<queries>{full queries.en.csv}</queries> The <queries> above are the Search Console queries and impressions of a home coffee machine shop (300 rows). Cluster them by search intent. An SEO specialist plans to write one article per cluster, so every query in a cluster must be answerable by a single article. Rules:- Use only the queries in <queries>. The specialist maps pages query by query, so a query that is invented, merged or dropped leads to a page for a query that does not exist. Queries that differ only in word order or spacing are separate rows.- Every query appears in exactly one row and one cluster.- Copy impressions exactly as given. Do not estimate search volume or compute totals.- intent is one of: informational, comparison, transactional, navigational (navigational means looking for a specific site or brand).- Use 8 to 12 clusters, each named with a short noun phrase.- Output only the CSV with the header query,impressions,intent,cluster. No explanations.

[3] The start of one result (the third run). All 300 rows look like this.

output
query,impressions,intent,clustercheapest bean to cup machine,76,transactional,Prices and Buyingbest bean to cup machine,584,comparison,Best Picks and Reviewsbean to cup machine ranking,190,comparison,Best Picks and Reviews…

[4] Do not compare 300 rows by eye. The script compares the set of queries in the output with the input to find additions, omissions and repeats; checks that each row's impressions equals the input, that intent is one of the four allowed values, that there are 8 to 12 clusters, and that the cluster totals add up to the input total. Any mismatch exits with code 1.

check_clusters.py
import sys, csv, iofrom collections import Counter, defaultdictINTENTS = {"ko": {"정보형", "비교형", "거래형", "탐색형"},           "en": {"informational", "comparison", "transactional", "navigational"}}[sys.argv[3]]src = {r["query"]: int(r["impressions"]) for r in csv.DictReader(open(sys.argv[1], encoding="utf-8", newline=""))}text = open(sys.argv[2], encoding="utf-8").read()rows = [r for r in csv.reader(io.StringIO(text.strip())) if r]H = ["query", "impressions", "intent", "cluster"]start = next((i for i, r in enumerate(rows) if [c.strip().lower() for c in r] == H), None)bad = []if start is None: bad.append("no header line query,impressions,intent,cluster"); start = -1def num(s):    try: return int(s.replace(",", "").strip())    except ValueError: return Nonebefore, rows = rows[:start], rows[start + 1:]ok = [r for r in rows if len(r) == 4 and num(r[1]) is not None and not r[0].startswith("```")]stray = len(before) + len(rows) - len(ok)if stray: bad.append(f"stray lines (before the header, code fences, text, not 4 columns): {stray}")q = Counter(r[0] for r in ok)added = sorted(set(q) - set(src)); missing = sorted(set(src) - set(q)); dup = sorted(k for k, v in q.items() if v > 1)if not ok: bad.append("no rows")if added: bad.append(f"added {len(added)}: {added[:4]}")if missing: bad.append(f"missing {len(missing)}: {missing[:4]}")if dup: bad.append(f"repeated {len(dup)}: {dup[:4]}")wrong = [(r[0], r[1], src[r[0]]) for r in ok if r[0] in src and num(r[1]) != src[r[0]]]if wrong: bad.append(f"impressions differ {len(wrong)}: {wrong[:3]}")badint = sorted({r[2] for r in ok} - INTENTS)if badint: bad.append(f"intent outside the list: {badint}")by = defaultdict(list)for r in ok: by[r[3]].append(num(r[1]) or 0)if not 8 <= len(by) <= 12: bad.append(f"clusters: {len(by)}")if sum(map(sum, by.values())) != sum(src.values()): bad.append(f"cluster sums add up to {sum(map(sum, by.values()))}, input {sum(src.values())}")print(f"{sys.argv[2]}: {len(ok)} rows, {len(by)} clusters, input {len(src)} queries / {sum(src.values())} impressions")for c, v in sorted(by.items(), key=lambda kv: -sum(kv[1])): print(f"  {c}: {len(v)} queries, {sum(v)}")print(("FAIL " if bad else "PASS ") + "; ".join(bad))sys.exit(1 if bad else 0)

[5] Run it on that result. The total, 106,716, matches.

console
$ python3 -I check_clusters.py queries.en.csv better.en.3.out.txt en | sed -n '1p;$p'better.en.3.out.txt: 300 rows, 11 clusters, input 300 queries / 106716 impressionsPASS

Then on all six runs of the same prompt:

console
$ for k in 1 2 3 4 5 6; do echo -n "better.en.$k.out.txt: "; python3 -I check_clusters.py queries.en.csv better.en.$k.out.txt en | tail -1; donebetter.en.1.out.txt: FAIL missing 6: ['aeropress no steam', 'bean to cup machine no steam', 'capsule coffee maker not working', 'capsule coffee maker warranty']; cluster sums add up to 102882, input 106716better.en.2.out.txt: FAIL missing 3: ['bean to cup machine no steam', 'coffee scale discount', 'cold brew maker beginner guide']; cluster sums add up to 104506, input 106716better.en.3.out.txt: PASSbetter.en.4.out.txt: FAIL missing 2: ['coffee scale repair', 'cold brew maker beginner guide']; repeated 1: ['coffee scale how to clean']; cluster sums add up to 104558, input 106716better.en.5.out.txt: FAIL missing 3: ['bean to cup machine no steam', 'cold brew maker beginner guide', 'drip coffee maker how to use']; cluster sums add up to 104319, input 106716better.en.6.out.txt: FAIL missing 1: ['cold brew maker beginner guide']; cluster sums add up to 105210, input 106716

Only 1 of 6 passed. The other five lost between 1 and 6 queries; cold brew maker beginner guide was among the missing in 4 of the 6 runs and bean to cup machine no steam in 3. One run also repeated a query. The cluster names and labels looked fine in every run. Why these queries were skipped was not checked.

[6] Request only the missing rows. Send the queries the script reported, plus the list of cluster names from that run, and forbid new clusters.

text
<queries>query,impressionscold brew maker beginner guide,1506</queries> <clusters>{the cluster names from that run, one per line}</clusters> Put each query in <queries> into exactly one of the clusters in <clusters>. Do not create new clusters. Copy the query and impressions exactly. intent is one of: informational, comparison, transactional, navigational. Output only the CSV with the header query,impressions,intent,cluster, no explanations.

Append the returned rows to the original CSV (keeping the first copy of any repeated query) and run the script again. All five runs that had lost queries passed with 300 rows and a total of 106,716.

[7] Compare with a short instruction: "Group them by search intent and give me a CSV with the columns query,impressions,intent,cluster", followed by the data (naive.en.txt), run 6 times. The first version of this prompt was that line alone. In the Korean-language test, all 3 runs of it tried to write scripts or call file tools even though no tools were available, so one sentence was added to both tests: "Do not use tools or files; write the CSV directly in your answer."

Out of 6 runsOne-line instructionWith rules
All 300 queries, none added or repeated, impressions equal21
intent in the four allowed values0 (not requested)6
8 to 12 clusters16
Stray lines around the CSV (text, code fences)60
Script passes01

With this data both prompts lost queries: the rule prompt in 5 of 6 runs, the one-line prompt in 4 of 6. The two prompts differ in data position, output format and rules, so no single cause was isolated. The one-line prompt's labels changed between runs (commercial, support, Informational and so on), which makes them hard to join to a page list.

[8] To check that the script catches errors, better.en.3.out.txt was edited by hand in 12 ways (deleted row, invented query, changed impressions, repeated query, intent outside the list, spacing change, merged queries, header only, 14 clusters, a sentence before the CSV, a code-fence wrapper, and others) plus one harmless edit that writes 1,135 with a comma. Only the harmless one passed; all 12 were caught. Results for both languages are in run/mutation-results.txt. One example, with impressions swapped between two rows, which leaves the total unchanged (not model output):

console
$ python3 -I check_clusters.py queries.en.csv mut_en/m4_impr_swapped_between_rows.csv en | tail -1FAIL impressions differ 2: [('bean to cup machine not working', '372', 264), ('bean to cup machine no steam', '264', 372)]

#keyword-clustering#search-intent#seo#claude