Files
arzani 577b9f4557
LocationBasedServices/smartguide/pipeline/head This commit looks good
initial version of multipliers in three levels: bridgers, mentors & amplifiers
2026-07-16 01:52:54 +02:00

273 lines
11 KiB
Python

#!/usr/bin/env python3
"""
index.py — idempotent indexing of scored multiplicator rows into Elasticsearch.
Target: the `multiplicators_v1` index on the INSE cluster. The index was created by
the cluster admin — the standard API key can read/write/update-mapping but NOT
create or delete indices, so this module must never attempt index creation.
Idempotency: doc _id = "<institution_short>_<author_short>", and every run first
deletes the institution's existing docs via a search + bulk-delete-by-id loop.
That loop (not _delete_by_query) is deliberate: the same cluster rejects
_delete_by_query with 403 for the org_patents key — see
inse/patents/org/elastic_search_client.py for the precedent.
"""
from __future__ import annotations
import json
import time
from datetime import datetime, timezone
from typing import Any
import httpx
from extract import INSE_KEY, INSE_URL, _headers
MULTIPLICATORS_INDEX = "multiplicators_v1"
NETWORKS_INDEX = "multiplicator_networks_v1"
REQUEST_TIMEOUT = 120.0
BULK_CHUNK = 500
MAPPING = {
"properties": {
"institution_id": {"type": "keyword"},
"cohort_institution_ids": {"type": "keyword"},
"author_id": {"type": "keyword"},
"display_name": {
"type": "text",
"fields": {"keyword": {"type": "keyword", "ignore_above": 256}},
},
"career_bucket": {"type": "keyword"},
"active_years": {"type": "integer"},
"n_works": {"type": "integer"},
"suspicious_profile": {"type": "boolean"},
"tags": {"type": "keyword"},
"max_sub_score": {"type": "float"},
"sub_scores": {
"properties": {
"bridger": {"type": "float"},
"mentor": {"type": "float"},
"amplifier": {"type": "float"},
}
},
# M3 signal counts
"patent_count": {"type": "integer"},
"patent_count_name_only": {"type": "integer"}, # evidence only, never scored
"news_mentions": {"type": "integer"},
"cordis_eu_projects": {"type": "integer"},
"industry_coauthor_share_shrunk": {"type": "float"},
# raw metrics + percentiles kept as dynamic float objects (calibration needs them)
"percentiles": {"type": "object", "dynamic": True},
"evidence": {
"properties": {"junior_ids": {"type": "keyword"}},
},
"config_hash": {"type": "keyword"},
"computed_at": {"type": "date"},
}
}
# Visualization docs: nodes/edges live in _source only ("enabled": false — never
# indexed/queried per-field, the frontend GETs whole docs by _id or author filter),
# which keeps the index small despite ~900 edge objects per doc.
NETWORK_MAPPING = {
"properties": {
"institution_id": {"type": "keyword"},
"cohort_institution_ids": {"type": "keyword"},
"author_id": {"type": "keyword"},
"display_name": {
"type": "text",
"fields": {"keyword": {"type": "keyword", "ignore_above": 256}},
},
"ego": {
"properties": {
"career_bucket": {"type": "keyword"},
"active_years": {"type": "integer"},
"n_works": {"type": "integer"},
"suspicious_profile": {"type": "boolean"},
"tags": {"type": "keyword"},
"max_sub_score": {"type": "float"},
"sub_scores": {
"properties": {
"bridger": {"type": "float"},
"mentor": {"type": "float"},
"amplifier": {"type": "float"},
}
},
}
},
"total_coauthors": {"type": "integer"},
"cohort_coauthors": {"type": "integer"},
"mentee_count": {"type": "integer"},
"shown": {"type": "integer"},
"shown_mentees": {"type": "integer"},
"nodes": {"type": "object", "enabled": False},
"edges": {"type": "object", "enabled": False},
"config_hash": {"type": "keyword"},
"computed_at": {"type": "date"},
}
}
class MultiplicatorsIndexClient:
def __init__(
self,
base_url: str | None = None,
api_key: str | None = None,
index: str = MULTIPLICATORS_INDEX,
transport: httpx.BaseTransport | None = None,
):
self.base_url = (base_url or INSE_URL).rstrip("/")
self.api_key = api_key if api_key is not None else INSE_KEY
self.index = index
self.client = httpx.Client(transport=transport, timeout=REQUEST_TIMEOUT)
if not self.base_url or not self.api_key:
raise SystemExit("Missing INSE cluster credentials (ELASTICSEARCH_INSE_*).")
def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
return self.client.request(
method,
f"{self.base_url}/{path.lstrip('/')}",
headers=_headers(self.api_key),
**kwargs,
)
def ensure_mapping(self, mapping: dict[str, Any] | None = None) -> None:
"""PUT the explicit mapping (additive; safe on every run). Never creates the index."""
response = self._request(
"PUT", f"{self.index}/_mapping", json=mapping or MAPPING
)
if not response.is_success:
raise RuntimeError(
f"Mapping update failed ({response.status_code}): {response.text[:500]}"
)
def count_for_institution(self, institution_short_id: str) -> int:
response = self._request(
"POST",
f"{self.index}/_count",
json={"query": {"term": {"institution_id": institution_short_id}}},
)
response.raise_for_status()
return response.json()["count"]
def _wait_for_count(self, institution_short_id: str, expected: int,
timeout_s: float = 30.0) -> int:
"""Poll _count until it reaches `expected` or timeout.
The API key is NOT allowed to call _refresh (indices:admin/refresh -> 403),
so visibility of deletes/writes depends on the index's auto-refresh
(default 1s). Polling is the only verification available to this key."""
deadline = time.time() + timeout_s
count = -1
while time.time() < deadline:
count = self.count_for_institution(institution_short_id)
if count == expected:
return count
time.sleep(1.0)
return count
def _collect_ids_for_institution(self, institution_short_id: str) -> list[str]:
"""All doc _ids for the institution, paginated with search_after (collected
BEFORE any deletes, so stale-visibility cannot inflate or loop the delete)."""
ids: list[str] = []
search_after = None
while True:
body: dict[str, Any] = {
"size": 1000,
"_source": False,
"query": {"term": {"institution_id": institution_short_id}},
"sort": [{"author_id": {"order": "asc"}}],
}
if search_after:
body["search_after"] = search_after
response = self._request("POST", f"{self.index}/_search", json=body)
response.raise_for_status()
hits = response.json()["hits"]["hits"]
if not hits:
break
ids.extend(h["_id"] for h in hits)
search_after = hits[-1]["sort"]
return ids
def delete_for_institution(self, institution_short_id: str) -> int:
"""Collect ids, then bulk-delete-by-id (the key rejects _delete_by_query
with 403). Returns the number of docs actually deleted."""
ids = self._collect_ids_for_institution(institution_short_id)
deleted = 0
for start in range(0, len(ids), BULK_CHUNK):
chunk = ids[start : start + BULK_CHUNK]
lines = "".join(
json.dumps({"delete": {"_index": self.index, "_id": doc_id}}) + "\n"
for doc_id in chunk
)
bulk = self.client.post(
f"{self.base_url}/_bulk",
headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"},
content=lines,
)
bulk.raise_for_status()
for item in bulk.json()["items"]:
result = item.get("delete", {})
if result.get("result") == "deleted":
deleted += 1
elif result.get("error"):
raise RuntimeError(f"Bulk delete error: {result['error']}")
if ids:
remaining = self._wait_for_count(institution_short_id, 0)
if remaining != 0:
raise RuntimeError(
f"{remaining} docs for {institution_short_id} still visible "
f"after delete (expected 0)"
)
return deleted
def index_rows(
self,
institution_short_id: str,
cohort_short_ids: list[str],
scored_rows: list[dict[str, Any]],
) -> int:
"""Delete-then-bulk-index all rows for the institution. Returns docs written."""
computed_at = datetime.now(timezone.utc).isoformat()
deleted = self.delete_for_institution(institution_short_id)
print(f"Deleted {deleted} existing docs for {institution_short_id}")
written = 0
for start in range(0, len(scored_rows), BULK_CHUNK):
chunk = scored_rows[start : start + BULK_CHUNK]
lines = []
for row in chunk:
doc = {
**row,
"institution_id": institution_short_id,
"cohort_institution_ids": cohort_short_ids,
"computed_at": computed_at,
}
doc_id = f"{institution_short_id}_{row['author_id']}"
lines.append(
json.dumps({"index": {"_index": self.index, "_id": doc_id}})
)
lines.append(json.dumps(doc, ensure_ascii=True))
bulk = self.client.post(
f"{self.base_url}/_bulk",
headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"},
content="\n".join(lines) + "\n",
)
bulk.raise_for_status()
result = bulk.json()
if result.get("errors"):
first_error = next(
(i["index"].get("error") for i in result["items"]
if i.get("index", {}).get("error")),
None,
)
raise RuntimeError(f"Bulk indexing reported errors, first: {first_error}")
written += len(chunk)
visible = self._wait_for_count(institution_short_id, written)
if visible != written:
raise RuntimeError(
f"Post-index count mismatch for {institution_short_id}: "
f"wrote {written}, index shows {visible} after 30s"
)
return written