Suppose your dedup job groups business rows by website. A branch disappears, another branch inherits its phone number, and retrieval now offers a remarkably convenient address that belongs nowhere.
Lab note 165: which fields should identify a directory profile when several locations can share a website?
Our bet is companyId, with canonical profileUrl as a fallback. The catch: their presence doesn't establish permanent identity across refreshes. That stability still needs checking.
What should a business document represent?
For this corpus, the retrievable unit is a directory profile. Your task is to answer which listed business matches a location and how to contact it.
A shared website is insufficient evidence for merging directory profiles into the same retrieval document.
Organization, branch, legal entity, and directory profile are different matching targets. Choosing the wrong target can corrupt the corpus before an embedding model sees it.
This sketch shows the boundary we want:
directory profile --> profile key --> retrieval document
published website --> hostname --> relationship between profiles
A shared domain can help connect documents later. It shouldn't decide which document survives ingestion.
Dedup belongs before chunking. If you split a wrongly merged profile into chunks, each chunk merely inherits a more portable version of the mistake.
Separate identity from contact evidence
The Actor supplies canonical profile URLs, directory slugs, and internal company IDs separately from postal addresses and contact details. That separation gives us a useful starting point.
Here's the field map for this task:
| Fields | Role | Treatment |
|---|---|---|
companyId |
Directory identity candidate | Preferred key, namespaced by source; preserve as a string |
profileUrl |
Canonical profile identity and provenance | Fallback key; connect to an ID when both occur together |
slug |
Additional directory reference | Retain in staging; don't construct a key from assumed slug rules |
name |
Retrieval context | Keep; don't use name equality to merge profiles |
address, street, postalCode, county, voivodeship, country
|
Branch context | Check conflicts; serialize the published address or available fragments |
phone, email
|
Published contact details | Keep for contact answers; conflicting values require review |
website |
Contact detail and relationship evidence | Keep when published; exclude from the dedup key |
nip |
Optional tax identity evidence | Retain for separate legal-entity matching; exclude from this prompt |
The address fields are especially useful as a brake on merging. An identifier match accompanied by different contact or postal values deserves inspection.
That disagreement might be a changed listing, inconsistent extraction, or an identity problem. Automatically picking the latest row would settle the argument without hearing it.
Keep branch context; cut prompt ballast
The Actor leaves unpublished values out of a record. A missing contact field therefore doesn't authorize borrowing a value from another profile with a matching domain.
For this task, we'd keep identity, provenance, name, address, and published contacts. We'd leave reviews, ratings, media links, opening hours, and long descriptions outside the prompt.
Those fields can matter for other questions. They don't help decide which profile owns a postal address or phone number.
Search provenance and scrape timestamps belong in ingestion storage. Repeating them in every retrieval passage adds text without helping this particular answer.
The same distinction applies to nip: retain it for relationship analysis, but don't silently turn a tax identifier into a branch identifier.
Collect without requiring a website
Requiring a website would remove businesses that don't publish one. That would make website availability part of corpus membership before identity handling even begins.
Example collection setup: this input searches the same trade across the selected locations and keeps profile enrichment enabled.
import json
import os
from collections import defaultdict
from urllib.parse import urlsplit
from apify_client import ApifyClient
run_input = {
"mode": "search",
"searchTerms": ["hydraulik"],
"locations": ["Warszawa", "Kraków"],
"fetchDetails": True,
"requireWebsite": False,
"maxItems": 50,
}
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
"vexaloom-labs/panoramafirm-pl-polish-business-directory-finder"
).call(run_input=run_input)
if run["status"] != "SUCCEEDED":
raise RuntimeError(f"Collection ended with status {run['status']}")
items = client.dataset(run["defaultDatasetId"]).list_items().items
Profile enrichment adds fields such as NIP and fuller descriptions. It doesn't change our identity policy.
The item cap also makes this a bounded collection. It can't establish that you've collected every relevant business.
Quarantine before choosing a survivor
A plain ID-first fallback has a small trap: a row carrying an ID and URL gets a different key from a repeat carrying only that URL.
We can connect those identifiers when they appear together. Matching hostnames never enter that decision.
This cell projects the fields we need, preserves identifier strings, and sends unusable identities to a review queue.
staging_fields = (
"companyId", "profileUrl", "slug", "name",
"address", "street", "postalCode", "county",
"voivodeship", "country", "phone", "email", "website", "nip",
)
review_queue = []
candidates = []
parents = {}
def find(node):
parents.setdefault(node, node)
while parents[node] != node:
parents[node] = parents[parents[node]]
node = parents[node]
return node
for row in items:
try:
record = {}
for field in staging_fields:
value = row.get(field)
if value is None:
continue
if not isinstance(value, str):
raise ValueError(f"{field} must be a string")
if value.strip():
record[field] = value
if "profileUrl" in record:
parsed_url = urlsplit(record["profileUrl"])
if parsed_url.scheme not in {"http", "https"} or not parsed_url.hostname:
raise ValueError("profileUrl must be an absolute web URL")
identities = [
(field, record[field])
for field in ("companyId", "profileUrl")
if field in record
]
if not identities:
raise ValueError("No usable companyId or profileUrl")
except ValueError as error:
review_queue.append({"reason": str(error), "rows": [row]})
continue
anchor = identities[0]
for identity in identities:
parents[find(identity)] = find(anchor)
candidates.append((record, anchor))
We use the supplied canonical URL without inventing path normalization rules. Removing a meaningful URL component would recreate the original bug with better punctuation.
The next cell groups connected identities and checks every retained field for disagreement. Compatible partial records can contribute missing values; conflicting records produce no accepted document.
groups = defaultdict(list)
for record, anchor in candidates:
groups[find(anchor)].append(record)
accepted = {}
for records in groups.values():
merged = {}
conflicts = {}
for field in staging_fields:
values = {record[field] for record in records if field in record}
if len(values) > 1:
conflicts[field] = sorted(values)
elif values:
merged[field] = next(iter(values))
if conflicts:
review_queue.append({
"reason": "Conflicting values within linked profile records",
"conflicts": conflicts,
"rows": records,
})
continue
key_field = "companyId" if "companyId" in merged else "profileUrl"
profile_key = f"panoramafirm.pl:{key_field}:{merged[key_field]}"
accepted[profile_key] = merged
This deliberately favors review over aggressive normalization. Phone formatting differences can trigger it. So can a renamed business.
That costs review work, but it keeps the serializer from quietly manufacturing a combined contact record. A later reconciliation process can distinguish formatting changes from substantive changes.
Serialize a bounded piece of evidence
A prompt-ready document needs enough context to answer the task and enough provenance to inspect the answer.
This serializer uses the full published address when available, otherwise retaining available address fragments. It also builds a separate hostname relationship map.
prompt_documents = {}
website_relationships = defaultdict(set)
for profile_key, record in accepted.items():
document = {"profile_key": profile_key}
for field in ("profileUrl", "name", "phone", "email", "website"):
if field in record:
document[field] = record[field]
address_fields = (
("address",)
if "address" in record
else ("street", "postalCode", "county", "voivodeship", "country")
)
for field in address_fields:
if field in record:
document[field] = record[field]
prompt_documents[profile_key] = json.dumps(
document, ensure_ascii=False, sort_keys=True
)
if "website" in record:
website_value = record["website"]
try:
hostname = urlsplit(
website_value
if "://" in website_value
else f"//{website_value}"
).hostname
except ValueError:
hostname = None
if hostname:
website_relationships[hostname.lower()].add(profile_key)
The address fallback doesn't reconstruct a complete postal address. It preserves fragments without guessing the missing locality.
The hostname map also makes no claim about corporate ownership. It records shared published hostnames, which you can inspect separately.
Keep profile_key as metadata on every downstream chunk. If a later retrieval task needs service descriptions, those chunks should still belong to the same profile boundary.
What this key still can't settle
The worked example uses PanoramaFirm.pl Polish Business Directory Finder.
Our schema verdict: its directory identity fields are better candidates for profile dedup than website domains. That's an identity-policy judgment; retrieval improvement would need its own evaluation.
The schema doesn't promise that an internal ID lasts forever, that a canonical URL never changes, or that separate profiles always represent separate branches.
The identifier connections above exist only within the current batch. Across refreshes, persist accepted ID-to-URL aliases and check changes before updating the index. An ID-keyed row and an older URL-keyed row need that history to converge.
If neither an ID nor a URL connects duplicate profiles, this code leaves them separate. Fuzzy name-and-address matching belongs in a review process with its own evidence.
Website-only dedup can't resolve that uncertainty. It can merely hide it.
Reproduce the corpus boundary
- Set
APIFY_TOKEN, installapify-client, and execute the Python cells in order. - Inspect
review_queuebefore indexingprompt_documents. - For profiles sharing a hostname, check their keys and postal context before proposing any merge.
- On a later refresh, inspect identifier changes before replacing stored documents.
Example input for the collection cell, with website publication excluded from the admission criteria:
{
"mode": "search",
"searchTerms": ["hydraulik"],
"locations": ["Warszawa", "Kraków"],
"fetchDetails": true,
"requireWebsite": false,
"maxItems": 50
}
A shared hostname can introduce profiles. It doesn't get a delete vote.
Drafted with AI assistance and reviewed for accuracy.
Top comments (0)