如何在 SQL 中追蹤 RemoteOK 職位,避免把時間戳記算作薪酬修改
Track RemoteOK jobs in SQL without counting timestamps as salary edits
以 SQL 對照 RemoteOK Actor 收集的職位快照,按 jobId 配對 listings,將薪酬範圍變動與職位新增或消失分開,避免把 scrapedAt 等收集時間戳記誤算為薪酬修改。流程保留每次快照、設定及原始觀測;只有具備明確 USD 貨幣、兩個端點且範圍非負有序的薪酬資料,才納入中點計算。
Your weekly salary chart has moved upwards. Before you publish “employers raised pay”, you need to establish whether any repeatedly observed listing changed its advertised range.
The Remote OK Actor merges feeds and deduplicates listings by jobId. It also adds scrapedAt, while salary fields can be absent. Comparing entire records would therefore count collection timestamps as edits; comparing aggregate salaries would mix edits with changing membership.
Matching snapshots on jobId separates salary-band revisions on repeatedly observed listings from changes in the observed listing mix.
What actually moved in your salary chart?
The awkward moment comes when your manager asks which employers changed their bands, and your aggregate query can't name a listing.
An average can rise because lower-paid listings disappeared from your sample. It can also rise because higher-paid listings became observable, including listings whose salary was previously missing.
Neither mechanism requires an existing advertised range to change.
Example collection settings keep listings without salaries and hold enrichment constant, so missing pay remains visible to the analysis:
import os
import json
import re
import math
from decimal import Decimal
from datetime import datetime, timezone
from uuid import uuid4
import pandas as pd
import duckdb
from apify_client import ApifyClient
client = ApifyClient(os.environ["APIFY_TOKEN"])
run_input = {
"mode": "byTags",
"tags": ["python", "data-science"],
"region": "any",
"salaryOnly": False,
"enrichDetails": True,
"maxItems": 1000,
}
Many listings publish salary only on their job page, which enrichment fetches. Switching that setting between captures can make salary appear without an employer editing anything.
We also leave salary thresholds out of this comparison. Otherwise, a revised band could push a listing across your filter boundary and turn a content change into an apparent arrival or disappearance.
The useful split looks like this:
Earlier snapshot ── jobId match ── Later snapshot
│
┌───────────┼────────────┐
matched newly observed absent later
│
comparable salary evidence
│
changed or unchanged band
Those branches answer different questions. Your chart shouldn't quietly fold them into the same explanation.
Use the listing ID, not the job title
Use jobId for membership and (snapshot_id, job_id) for stored-row uniqueness.
A company can advertise several similarly named roles. A title can change while the listing remains identifiable. Joining on company and title can manufacture both departures and arrivals.
Normalise the ID before storage. An integer representation and its equivalent string shouldn't become separate listings.
The salary parser below accepts numeric values and conventional currency-prefixed, comma-grouped strings. It rejects unfamiliar formats rather than guessing what they mean:
def normalise_id(value):
if value is None or isinstance(value, bool):
raise ValueError("Missing or invalid jobId")
number = Decimal(str(value).strip())
if not number.is_finite() or number != number.to_integral_value():
raise ValueError("jobId must be an integer identifier")
return str(int(number))
def parse_salary(value):
if value is None:
return None
text = str(value).strip()
if not text:
return None
text = re.sub(r"^(?:USD\s*|\$\s*)", "", text, flags=re.I)
if not re.fullmatch(r"(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?", text):
raise ValueError(f"Unrecognised salary format: {value!r}")
amount = float(text.replace(",", ""))
if not math.isfinite(amount):
raise ValueError("Salary must be finite")
return amount
Empty fields are omitted from records, so extraction uses .get() explicitly.
A missing endpoint stays missing. It doesn't become zero, an open-ended range, or a value borrowed from the previous capture. Each substitution would create a different salary measure.
Keep each capture and its settings
Store a snapshot manifest separately from its listings. Otherwise, an empty capture has no rows and quietly loses its existence.
Keep the raw observations alongside the normalised endpoints. That gives you somewhere to investigate an apparent revision without making every optional field part of the comparison.
These tables enforce unique snapshot membership and define which rows qualify for the salary calculation:
con = duckdb.connect()
con.execute("""
CREATE TABLE snapshots (
snapshot_id VARCHAR PRIMARY KEY,
captured_at TIMESTAMPTZ NOT NULL,
settings_json VARCHAR NOT NULL
);
CREATE TABLE listings (
snapshot_id VARCHAR NOT NULL,
job_id VARCHAR NOT NULL,
salary_min DOUBLE,
salary_max DOUBLE,
currency VARCHAR,
raw_json VARCHAR NOT NULL,
PRIMARY KEY (snapshot_id, job_id)
);
CREATE VIEW salary_rows AS
SELECT *,
COALESCE(
currency = 'USD'
AND salary_min >= 0
AND salary_min <= salary_max,
FALSE
) AS salary_ok
FROM listings;
""").fetchall()
Here, a comparable salary requires both endpoints, an explicit USD currency and an ordered, non-negative range. A partial band may still contain useful information, but it doesn't enter this particular midpoint measure.
The notebook uses memory for storage. A weekly tracker needs these same tables retained in persistent storage between scheduled captures.
At ingestion, repeated observations of an ID become a single membership row. If their normalised salary tuples disagree within that capture, we retain every raw observation and leave the analytical tuple empty: choosing whichever arrived last would manufacture certainty.
This function reconciles those observations, validates membership in SQL, then writes the manifest and its batch atomically:
def capture(settings):
settings_json = json.dumps(settings, sort_keys=True)
run = client.actor(
"dataspryva/remoteok-job-board-tag-and-region-filter-tool"
).call(run_input=settings)
if run["status"] != "SUCCEEDED":
raise RuntimeError(f"Capture failed: {run['status']}")
grouped = {}
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
job_id = normalise_id(item.get("jobId"))
currency = item.get("salaryCurrency")
band = (
parse_salary(item.get("salaryMin")),
parse_salary(item.get("salaryMax")),
str(currency).strip().upper() if currency else None,
)
observations = grouped.setdefault(
job_id, {"bands": set(), "records": []}
)
observations["bands"].add(band)
observations["records"].append(item)
rows = []
for job_id, observations in grouped.items():
band = (
next(iter(observations["bands"]))
if len(observations["bands"]) == 1
else (None, None, None)
)
rows.append({
"job_id": job_id,
"salary_min": band[0],
"salary_max": band[1],
"currency": band[2],
"raw_json": json.dumps(
observations["records"], sort_keys=True
),
})
batch = pd.DataFrame(rows, columns=[
"job_id", "salary_min", "salary_max", "currency", "raw_json"
])
con.register("incoming", batch)
try:
duplicates = con.execute("""
SELECT job_id FROM incoming
GROUP BY job_id HAVING count(*) > 1
""").fetchall()
if duplicates:
raise ValueError("Duplicate jobId after reconciliation")
snapshot_id = str(uuid4())
con.execute("BEGIN").fetchall()
try:
con.execute(
"INSERT INTO snapshots VALUES (?, ?, ?)",
[snapshot_id, datetime.now(timezone.utc), settings_json],
).fetchall()
con.execute("""
INSERT INTO listings
SELECT ?, job_id, salary_min, salary_max, currency, raw_json
FROM incoming
""", [snapshot_id]).fetchall()
con.execute("COMMIT").fetchall()
except Exception:
con.execute("ROLLBACK").fetchall()
raise
finally:
con.unregister("incoming")
return snapshot_id
before_id = capture(run_input)
after_id = capture(run_input)
The adjacent calls collect successive observations; they don't represent a weekly interval. For weekly reporting, use the retained snapshot IDs from that interval.
There's deliberately no update path here. Overwriting an earlier salary would remove the evidence needed to explain its revision.
Join snapshots before comparing salaries
A full outer join preserves arrivals and disappearances. An inner join would remove precisely the membership changes you're trying to distinguish.
First reject differing collection settings. Then classify matched listings only when both observations have comparable salary evidence:
settings_count = con.execute("""
SELECT count(DISTINCT settings_json)
FROM snapshots
WHERE snapshot_id IN (?, ?)
""", [before_id, after_id]).fetchall()[0][0]
if settings_count != 1:
raise ValueError("Collection settings differ between snapshots")
con.execute("""
CREATE TABLE comparison AS
WITH earlier AS (
SELECT * FROM salary_rows WHERE snapshot_id = ?
), later AS (
SELECT * FROM salary_rows WHERE snapshot_id = ?
), paired AS (
SELECT
job_id,
earlier.snapshot_id IS NOT NULL AS seen_before,
later.snapshot_id IS NOT NULL AS seen_after,
earlier.salary_ok AS old_ok,
later.salary_ok AS new_ok,
earlier.salary_min AS old_min,
earlier.salary_max AS old_max,
earlier.currency AS old_currency,
later.salary_min AS new_min,
later.salary_max AS new_max,
later.currency AS new_currency
FROM earlier FULL OUTER JOIN later USING (job_id)
)
SELECT *,
CASE
WHEN NOT seen_before THEN 'newly_observed'
WHEN NOT seen_after THEN 'not_observed_again'
WHEN NOT (old_ok AND new_ok) THEN 'salary_not_comparable'
WHEN (old_min, old_max, old_currency)
IS DISTINCT FROM (new_min, new_max, new_currency)
THEN 'band_changed'
ELSE 'band_unchanged'
END AS status
FROM paired
""", [before_id, after_id]).fetchall()
The tuple comparison is null-safe, but null safety alone doesn't establish comparability. That's why the salary-evidence check comes first.
A listing gaining a complete salary range belongs in an observability investigation. Treating its previous missing range as zero would give your chart a very enthusiastic fictional pay rise.
Count arrivals separately from salary edits
Keep the full snapshot summary, the membership ledger and the matched salary calculation separate.
These queries produce pandas tables without combining those measures:
snapshot_summary = con.execute("""
SELECT
s.snapshot_id,
count(l.job_id) AS observed_listings,
count(l.job_id) FILTER (WHERE l.salary_ok) AS comparable_salary_rows,
avg((l.salary_min + l.salary_max) / 2)
FILTER (WHERE l.salary_ok) AS mean_band_midpoint
FROM snapshots s
LEFT JOIN salary_rows l USING (snapshot_id)
WHERE s.snapshot_id IN (?, ?)
GROUP BY s.snapshot_id
""", [before_id, after_id]).df()
membership_summary = con.execute("""
SELECT status, count(*) AS listings
FROM comparison
GROUP BY status
""").df()
matched_summary = con.execute("""
SELECT
count(*) AS comparable_matches,
count(*) FILTER (WHERE status = 'band_changed') AS changed_bands,
avg(
((new_min + new_max) - (old_min + old_max)) / 2
) AS mean_midpoint_change
FROM comparison
WHERE status IN ('band_changed', 'band_unchanged')
""").df()
The matched mean includes unchanged bands. Restricting it to edited listings would answer how large revisions were among revision candidates, rather than how the repeatedly observed comparable listings moved overall.
The midpoint is a deliberately named summary of advertised endpoints. It isn't an expected offer.
Nor is this an additive decomposition of the aggregate movement. Changing membership and changing salary observability can alter the denominator, so subtracting the matched mean change from the full-chart change doesn't produce a clean “composition effect”.
Separate extraction noise from revision candidates
The useful comparison boundary is narrower than “anything in the JSON changed”.
| Field or setting | Treatment | Analytical consequence |
|---|---|---|
salaryMin, salaryMax, salaryCurrency
|
Compare the normalised tuple after eligibility checks | Flags observed band revisions |
scrapedAt |
Retain as collection metadata | A fresh capture is not a content edit |
postedAt |
Retain separately from collection time | Posting time does not date a salary revision |
mode, input tags, region, maxItems
|
Hold constant and save in the manifest | Selection changes can alter membership |
enrichDetails |
Hold constant | Different extraction depth can alter salary visibility |
Identical settings are necessary for this comparison, but they aren't proof that extraction conditions were identical. A missing endpoint remains ambiguous until you inspect the underlying evidence.
Even a complete-to-complete change is initially a revision candidate. Before attributing it to an employer, inspect the raw records and the listing page. The stored capture times bound when you observed the difference; they don't establish when the underlying edit happened.
Keep the full chart beside the matched panel
The worked source is our RemoteOK Job Board Tag & Region Filter Tool.
Its feed slices contain about 100 latest jobs per tag and offer no pagination. Combining tags broadens the observed set, but doesn't create a census.
That matters for disappearances: a listing can leave your observed feed without leaving the board. Reaching maxItems adds another selection boundary. Raising that cap can't recover records the source feed never exposed.
Label the comparison accordingly: newly observed, rather than newly created; not observed again, rather than filled.
The matched panel has its own selection effect. It retains listings visible at both capture points, with usable salary evidence at both. Listings that persist may differ from those that turn over quickly.
Your full snapshot chart describes the observed inventory. Your matched calculation describes changes within its repeatedly observed, salary-comparable subset. Keeping both visible makes the limitation inspectable.
A listing isn't a payslip
A jobId identifies an advertised listing. It doesn't establish a unique hiring position, headcount, an accepted offer or anyone's realised earnings.
Even if both endpoints rise for a matched listing, you've evidence of an observed advertised-band revision, subject to checking extraction. You haven't measured wage growth.
The defensible sentence names the evidence: the observed inventory changed, particular matched bands changed, or both.
A rising line can't choose that sentence for you.
Drafted with AI assistance and reviewed for accuracy.
來源:DEV Community · dev.to