Add company counts to author ranking and enhance search client for bulk queries
This commit is contained in:
@@ -73,6 +73,24 @@ async def get_company_connections_by_author_id(
|
||||
)
|
||||
|
||||
|
||||
async def get_company_counts_by_names(
|
||||
names: list[str],
|
||||
client: CompanyConnectionsSearchClient | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Bulk variant of the per-author lookup for the ranking pipeline.
|
||||
|
||||
Returns a mapping ``display_name -> company_count`` for the given names in a
|
||||
single Elasticsearch aggregation. Names without a match are absent from the
|
||||
mapping (callers should treat them as 0).
|
||||
"""
|
||||
search_client = client or CompanyConnectionsSearchClient()
|
||||
cleaned = [name for name in (_clean(n) for n in names) if name]
|
||||
if not cleaned:
|
||||
return {}
|
||||
|
||||
return await search_client.count_companies_by_founder_names(cleaned)
|
||||
|
||||
|
||||
def _get_ude_institution_scope(source: dict[str, Any]) -> tuple[str | None, list[str]]:
|
||||
institutions = source.get("last_known_institutions") or []
|
||||
|
||||
|
||||
@@ -58,6 +58,94 @@ class CompanyConnectionsSearchClient:
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
async def count_companies_by_founder_names(
|
||||
self,
|
||||
founder_names: list[str],
|
||||
) -> dict[str, int]:
|
||||
"""Returns the number of companies they are linked to a author.
|
||||
"""
|
||||
names = sorted({name for name in founder_names if name})
|
||||
if not names:
|
||||
return {}
|
||||
|
||||
payload = self.handelsregister_founder_counts_query(names)
|
||||
response = await elasticsearch.search(
|
||||
index=self.handelsregister_index,
|
||||
body=payload,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("founders", {})
|
||||
.get("matched", {})
|
||||
.get("by_name", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
|
||||
counts: dict[str, int] = {}
|
||||
for bucket in buckets:
|
||||
name = bucket.get("key", "")
|
||||
if not name:
|
||||
continue
|
||||
counts[name] = int(bucket.get("companies", {}).get("doc_count", 0))
|
||||
|
||||
return counts
|
||||
|
||||
@staticmethod
|
||||
def handelsregister_founder_counts_query(
|
||||
founder_names: list[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Aggregation that counts distinct companies per founder name.
|
||||
|
||||
The ``matched`` filter keeps only the founders whose name is one of the
|
||||
candidates, then ``reverse_nested`` steps back to the company level so the
|
||||
per-name ``doc_count`` is a company count, not a founder-occurrence count.
|
||||
"""
|
||||
return {
|
||||
"size": 0,
|
||||
"track_total_hits": False,
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "officers",
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"term": {"officers.type": "person"}},
|
||||
{"terms": {"officers.name.keyword": founder_names}},
|
||||
]
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"founders": {
|
||||
"nested": {"path": "officers"},
|
||||
"aggs": {
|
||||
"matched": {
|
||||
"filter": {
|
||||
"terms": {"officers.name.keyword": founder_names},
|
||||
},
|
||||
"aggs": {
|
||||
"by_name": {
|
||||
"terms": {
|
||||
"field": "officers.name.keyword",
|
||||
"size": len(founder_names),
|
||||
"execution_hint": "map",
|
||||
},
|
||||
"aggs": {
|
||||
# step back to the company (parent) level so
|
||||
# the count is distinct companies per name
|
||||
"companies": {"reverse_nested": {}},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def handelsregister_officer_name_query(
|
||||
officer_name: str,
|
||||
|
||||
@@ -10,6 +10,7 @@ import pandas as pd
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from inse.persons.logic import _classify_career_stage
|
||||
from inse.company_connections.logic import get_company_counts_by_names
|
||||
from .. import config
|
||||
from .model import (
|
||||
AuthorCorrespondingCount,
|
||||
@@ -588,26 +589,35 @@ def _min_max_normalize(values: pd.Series) -> pd.Series:
|
||||
|
||||
|
||||
def _apply_scores(authors: List[RankedAuthor], weights: RankingWeights) -> None:
|
||||
"""Normalizes works and citations to [0, 1] and sets each author's weighted score."""
|
||||
"""Normalizes works, citations and company connections to [0, 1] and sets each author's weighted score."""
|
||||
if not authors:
|
||||
return
|
||||
|
||||
works_counts = []
|
||||
citations_counts = []
|
||||
companies_counts = []
|
||||
for author in authors:
|
||||
works_counts.append(author.works_count)
|
||||
citations_counts.append(author.citations_count)
|
||||
companies_counts.append(author.companies_count)
|
||||
|
||||
frame = pd.DataFrame({
|
||||
"works": works_counts,
|
||||
"citations": citations_counts,
|
||||
"companies": companies_counts,
|
||||
})
|
||||
|
||||
frame["works"] = frame["works"].clip(upper=frame["works"].quantile(0.95))
|
||||
frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(0.95))
|
||||
frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(0.95))
|
||||
works_normalized = _min_max_normalize(frame["works"])
|
||||
citations_normalized = _min_max_normalize(frame["citations"])
|
||||
scores = works_normalized * weights.works + citations_normalized * weights.citation
|
||||
companies_normalized = _min_max_normalize(frame["companies"])
|
||||
scores = (
|
||||
works_normalized * weights.works
|
||||
+ citations_normalized * weights.citation
|
||||
+ companies_normalized * weights.companies
|
||||
)
|
||||
|
||||
for index, author in enumerate(authors):
|
||||
author.score = float(scores.iloc[index])
|
||||
@@ -696,6 +706,22 @@ async def _career_stages_for_authors(author_ids: List[str]) -> dict:
|
||||
return stages
|
||||
|
||||
|
||||
async def _enrich_with_company_counts(authors: List[RankedAuthor]) -> None:
|
||||
"""Sets each author's company_count from a single bulk Handelsregister query.
|
||||
|
||||
Matching is by exact display name (same as the company-connections feature), so
|
||||
authors without a name match keep a count of 0.
|
||||
"""
|
||||
if not authors:
|
||||
return
|
||||
|
||||
names = [author.display_name for author in authors if author.display_name]
|
||||
counts = await get_company_counts_by_names(names)
|
||||
|
||||
for author in authors:
|
||||
author.companies_count = counts.get(author.display_name, 0)
|
||||
|
||||
|
||||
async def rank_authors_by_keywords(
|
||||
keywords: List[str],
|
||||
operator: KeywordOperator,
|
||||
@@ -742,6 +768,11 @@ async def rank_authors_by_keywords(
|
||||
for author_bucket in author_buckets:
|
||||
ranked_authors.append(_bucket_to_ranked_author(author_bucket))
|
||||
|
||||
# Company connections are only fetched when they actually influence the score,
|
||||
# avoiding an extra Handelsregister query for the common works/citations case.
|
||||
if weights.companies > 0:
|
||||
await _enrich_with_company_counts(ranked_authors)
|
||||
|
||||
_apply_scores(ranked_authors, weights)
|
||||
|
||||
# Sort by the weighted score, highest first.
|
||||
|
||||
@@ -69,6 +69,12 @@ class RankingWeights(BaseModel):
|
||||
le=1.0,
|
||||
description="Weight for the works metric (0.0 - 1.0).",
|
||||
)
|
||||
companies: float = Field(
|
||||
default=0.0,
|
||||
ge=0.0,
|
||||
le=1.0,
|
||||
description="Weight for the company-foundations metric (0.0 - 1.0).",
|
||||
)
|
||||
|
||||
|
||||
class KeywordToAuthorRequest(BaseModel):
|
||||
@@ -180,6 +186,11 @@ class RankedAuthor(BaseModel):
|
||||
citations_count: int = Field(
|
||||
description="Total citations across this author's matching works.",
|
||||
)
|
||||
companies_count: int = Field(
|
||||
default=0,
|
||||
description="Number of Handelsregister company connections matched by the "
|
||||
"author's name (proxy for company foundations).",
|
||||
)
|
||||
score: float = Field(
|
||||
default=0.0,
|
||||
description="Normalized weighted score used for ranking.",
|
||||
|
||||
Reference in New Issue
Block a user