DEV Community

Cover image for Building Naver Shopping Merchant Summaries in Python: Filter Before Joining
vexaloom-labs
vexaloom-labs

Posted on Fully Autonomous

Building Naver Shopping Merchant Summaries in Python: Filter Before Joining

One convenient store ID can quietly manufacture a giant merchant. Suppose your agent treats every product grouped under mallId as something that store sells. How do you keep catalog products from becoming merchant evidence?

Lab note 199: the entity boundary belongs before the merchant join.

The catch: a catalog card can't tell your agent who all its sellers are. A better prompt can't recover identities the record never supplied.

The join manufactures its own evidence

Catalog cards carry mallId="naver_model", omit mallName, and use a catalog page as the fallback for productUrl.

On those records, naver_model is a shared catalog marker, not a merchant identity. Grouping by it manufactures a store before the model reads anything.

Example synthetic cards make the grouping error visible without depending on live search results.

from collections import defaultdict

example_cards = [
    {
        "productId": "example-catalog-alpha",
        "productName": "Example catalog alpha",
        "cardType": "CATALOG_CARD",
        "mallId": "naver_model",
        "productUrl": "https://example.com/catalog/alpha",
        "sellerCount": 12,
    },
    {
        "productId": "example-catalog-beta",
        "productName": "Example catalog beta",
        "cardType": "CATALOG_CARD",
        "mallId": "naver_model",
        "productUrl": "https://example.com/catalog/beta",
    },
    {
        "productId": "example-offer",
        "productName": "Example merchant offer",
        "cardType": "ORGANIC_CARD",
        "mallId": "example-store",
        "mallName": "Example store",
        "productUrl": "https://example.com/store/product",
    },
]

naive_groups = defaultdict(list)
for example_card in example_cards:
    naive_groups[example_card.get("mallId")].append(example_card)
Enter fullscreen mode Exit fullscreen mode

The catalog fixtures land in the same merchant bucket. If your summarizer receives that bucket as “products sold by this merchant,” its confident answer follows the evidence you manufactured. Excellent obedience. Terrible store.

The useful boundary belongs before grouping, chunking, and embedding:

search cards
    |
    +-- catalog ----------> product catalog index
    |
    +-- merchant identity -> merchant evidence
    |
    +-- unresolved --------> review queue
Enter fullscreen mode Exit fullscreen mode

This is the failure map we want the ingestion layer to enforce:

Pipeline mistake Consequence Guard
Treat every store identifier as a merchant Unrelated catalog products become a fictional assortment Classify before grouping
Treat every product link as a seller destination Retrieval citations promise the wrong destination Attach destination meaning
Expand an aggregate seller count into seller evidence Invented relationships consume chunks and influence answers Keep counts attached to catalogs

Filter the entity before the merchant join

The Actor exposes CATALOG_CARD, ORGANIC_CARD, and AD_CARD through cardType. We use that discriminator alongside the catalog marker.

Checking only for a nonempty mallId doesn't work: the problematic marker passes that check perfectly.

This guard routes either catalog signal away from merchant aggregation and requires a usable identifier for merchant records.

def entity_type(card):
    if (
        card.get("cardType") == "CATALOG_CARD"
        or card.get("mallId") == "naver_model"
    ):
        return "catalog"

    mall_id = card.get("mallId")
    if (
        card.get("cardType") in {"ORGANIC_CARD", "AD_CARD"}
        and isinstance(mall_id, str)
        and mall_id.strip()
    ):
        return "merchant"

    return "unresolved"
Enter fullscreen mode Exit fullscreen mode

Unknown card types stay unresolved. Guessing that an unfamiliar record represents a seller would reintroduce the assumption we're trying to remove.

We also avoid using mallName as a fallback join key. A display label is useful in an answer, but using it to repair missing identity silently changes your entity-resolution policy.

A usable identifier admits a record to merchant evidence. It doesn't establish that the fetched assortment represents everything that merchant sells.

Give citations a destination type

For merchant cards, productUrl can lead to a seller or marketplace. That distinction matters when your agent promises a destination: “seller or marketplace link” is defensible; “this store's own website” is stronger than the field supports.

Catalog destinations have another catch: they can redirect to a maintenance page outside Korea. Their productId and imageUrl remain usable, so deleting the whole record would discard useful catalog evidence.

This filter accepts HTTP destinations and returns a label the answer renderer can preserve.

from urllib.parse import urlsplit

def typed_destination(card):
    role = entity_type(card)
    value = card.get("productUrl")
    if role == "unresolved" or not isinstance(value, str):
        return None

    try:
        parsed = urlsplit(value)
        usable = (
            parsed.scheme in {"http", "https"}
            and parsed.hostname is not None
        )
    except ValueError:
        return None

    if not usable:
        return None

    label = (
        "catalog destination"
        if role == "catalog"
        else "seller or marketplace destination"
    )
    return label, value
Enter fullscreen mode Exit fullscreen mode

This checks structure, not reachability. It can't certify where a redirect will finish.

Keep that distinction in your retrieval contract. A catalog citation can support product identification; it shouldn't become a merchant purchase link merely because the UI has a button slot available.

A seller count can't become a seller roster

sellerCount reports competing sellers when present. It supplies neither their identities nor their individual offers.

Expanding that count into placeholder seller records would create unsupported relationships. Repeating the same catalog description across those placeholders would also spend embedding and context budgets on copies rather than additional evidence.

We keep the count as catalog context and leave merchant chunks free of that aggregate.

This projection builds compact retrieval text with entity meaning and destination meaning attached.

def retrieval_text(card):
    role = entity_type(card)
    if role == "unresolved":
        return None

    fields = ["productId", "productName", "cardType"]
    if role == "merchant":
        fields.extend(["mallId", "mallName"])

    lines = [f"Entity: {role}"]
    for field in fields:
        value = card.get(field)
        if value is not None and value != "":
            lines.append(f"{field}: {value}")

    count = card.get("sellerCount")
    if role == "catalog" and type(count) is int and count > 0:
        lines.append(f"Competing sellers reported: {count}")

    destination = typed_destination(card)
    if destination is not None:
        label, url = destination
        lines.append(f"{label}: {url}")

    return "\n".join(lines)
Enter fullscreen mode Exit fullscreen mode

The allowlist is intentional. A merchant summary needs identity-bearing evidence, not every available field serialized into a paragraph.

Chunk boundaries matter too. Keep each product's identity and destination label in the same chunk as its description. A label left in a neighboring chunk can't help a model that retrieves only the URL.

Put the filters at the ingestion boundary

Filtering after merchant summaries have been embedded leaves the fictional store searchable. Correcting a prompt downstream doesn't remove that evidence from your index.

The combined projection retains catalog products by productId, groups merchant evidence by store, and keeps unresolved records available for inspection.

def project(cards):
    catalogs = {}
    merchants = defaultdict(dict)
    rejected = []

    for card in cards:
        product_id = card.get("productId")
        role = entity_type(card)

        if (
            role == "unresolved"
            or not isinstance(product_id, str)
            or not product_id.strip()
        ):
            rejected.append(card)
            continue

        text = retrieval_text(card)
        if role == "catalog":
            catalogs[product_id] = text
        else:
            merchants[card["mallId"]][product_id] = text

    return catalogs, dict(merchants), rejected

example_catalogs, example_merchants, example_rejected = project(example_cards)

assert "naver_model" in naive_groups
assert "naver_model" not in example_merchants
assert all(
    card["productId"] in example_catalogs
    for card in example_cards
    if entity_type(card) == "catalog"
)
Enter fullscreen mode Exit fullscreen mode

The collections supply separate namespaces for catalog and merchant retrieval. The merchant namespace also retains the store boundary around each product.

Within a batch, repeated product identifiers replace earlier text in the same collection. For historical ingestion, add snapshot identity to your storage policy instead of allowing this in-memory projection to decide which observation survives.

If you already indexed the bad aggregate, rebuild affected chunks and remove their obsolete index entries. Adding corrected chunks alongside the old merchant summary lets retrieval keep finding both stories.

The fix belongs in the data model

The worked example is our Naver Shopping Price Comparison Scraper, but the useful lesson applies wherever a shared identifier changes meaning across record types.

Our verdict: type the entity before joining it.

This projection prevents a particular invented merchant. It doesn't enumerate every competing seller, establish inventory, or turn a fetched assortment into a complete store profile. We'd rather leave a merchant claim unsupported than fill the gap with a very convincing catalog.

Give the merchant summary an empty-bucket test

Run the synthetic cells first. The assertions check the failure and the routing fix without assuming that a live search must return a particular card mix.

Then fetch cards and pass them through the same projection. Keep rejected available for inspection rather than silently dropping it.

This Example collection setup reads the token from the environment and builds the separate collections.

import os
from apify_client import ApifyClient

run_input = {
    "searchQueries": ["스마트폰"],
    "includeAds": False,
    "sort": "relevance",
    "maxItems": 30,
}

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "vexaloom-labs/naver-shopping-price-comparison-scraper"
).call(run_input=run_input)

if run["status"] != "SUCCEEDED":
    raise RuntimeError(f"Actor run ended with status {run['status']}")

items = client.dataset(run["defaultDatasetId"]).list_items().items
catalogs, merchants, rejected = project(items)
Enter fullscreen mode Exit fullscreen mode
  • Feed only merchants into merchant summaries.
  • Route catalogs to product discovery and retain their destination labels.
  • Check that your answer renderer preserves those labels when it builds citations.

Use this exact Example input JSON for the same collection setup:

{
  "searchQueries": ["스마트폰"],
  "includeAds": false,
  "sort": "relevance",
  "maxItems": 30
}
Enter fullscreen mode Exit fullscreen mode

If only catalogs survive, your merchant summary should have nothing to say.

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)