add get authors based on keywords
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
from typing import Any, List
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster
|
||||
from .. import config
|
||||
from .model import KeywordOperator, RankedAuthor
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
MAX_AUTHOR_BUCKETS = 20
|
||||
|
||||
|
||||
def _keyword_clause(keyword: str) -> dict:
|
||||
"""A single nested clause that matches one keyword on a work."""
|
||||
return {
|
||||
"nested": {
|
||||
"path": "keywords",
|
||||
"query": {
|
||||
"term": {"keywords.display_name.keyword": keyword},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_keyword_query(keywords: List[str], operator: KeywordOperator) -> dict:
|
||||
"""Combines the keyword clauses according to the operator.
|
||||
|
||||
AND: a work must carry all keywords (every clause is required).
|
||||
OR: a work must carry at least one of the keywords.
|
||||
"""
|
||||
clauses = []
|
||||
for keyword in keywords:
|
||||
clauses.append(_keyword_clause(keyword))
|
||||
|
||||
if operator == KeywordOperator.OR:
|
||||
return {
|
||||
"bool": {
|
||||
"should": clauses,
|
||||
"minimum_should_match": 1,
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
"bool": {
|
||||
"must": clauses,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _institution_filter(uni_id: str) -> dict:
|
||||
"""Keeps only works with an authorship affiliated with the given university.
|
||||
|
||||
The institutions are nested below the authorships.
|
||||
"""
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"term": {"authorships.institutions.id": uni_id},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_query(keywords: List[str], operator: KeywordOperator, uni_id: str) -> dict:
|
||||
|
||||
return {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
_build_keyword_query(keywords, operator),
|
||||
_institution_filter(uni_id),
|
||||
],
|
||||
},
|
||||
},
|
||||
"aggs": {
|
||||
"authors": {
|
||||
"nested": {"path": "authorships"},
|
||||
"aggs": {
|
||||
"by_author": {
|
||||
"terms": {
|
||||
"field": "authorships.author.id",
|
||||
"size": MAX_AUTHOR_BUCKETS,
|
||||
},
|
||||
"aggs": {
|
||||
"author_name": {
|
||||
"terms": {
|
||||
"field": "authorships.author.display_name.keyword",
|
||||
"size": 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _display_name_from_bucket(author_bucket: dict) -> str:
|
||||
"""Reads the author's display name out of the name sub-aggregation."""
|
||||
name_buckets = author_bucket.get("author_name", {}).get("buckets", [])
|
||||
if name_buckets:
|
||||
return name_buckets[0].get("key", "")
|
||||
return ""
|
||||
|
||||
|
||||
def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor:
|
||||
return RankedAuthor(
|
||||
author_id=author_bucket.get("key", ""),
|
||||
display_name=_display_name_from_bucket(author_bucket),
|
||||
works_count=author_bucket.get("doc_count", 0),
|
||||
)
|
||||
|
||||
|
||||
async def rank_authors_by_keywords(
|
||||
keywords: List[str],
|
||||
operator: KeywordOperator,
|
||||
uni_id: str,
|
||||
) -> List[RankedAuthor]:
|
||||
"""Ranks the university's authors by the number of works carrying the keywords."""
|
||||
query_body = _build_query(keywords, operator, uni_id)
|
||||
|
||||
response: dict[str, Any] = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=query_body,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
author_buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("authors", {})
|
||||
.get("by_author", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
|
||||
ranked_authors = []
|
||||
for author_bucket in author_buckets:
|
||||
ranked_authors.append(_bucket_to_ranked_author(author_bucket))
|
||||
|
||||
return ranked_authors
|
||||
@@ -34,3 +34,9 @@ class KeywordToAuthorRequest(BaseModel):
|
||||
if isinstance(value, str):
|
||||
return value.lower()
|
||||
return value
|
||||
|
||||
|
||||
class RankedAuthor(BaseModel):
|
||||
author_id: str = Field(description="The OpenAlex ID of the author.")
|
||||
display_name: str = Field(description="The name of the author.")
|
||||
works_count: int = Field(description="Number of matching works by this author.")
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import logging
|
||||
from typing import List
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from inse.tags import Tags
|
||||
from .model import KeywordToAuthorRequest
|
||||
from . import logic
|
||||
from .model import KeywordToAuthorRequest, RankedAuthor
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -13,7 +15,7 @@ router = APIRouter(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/rank-author")
|
||||
@router.post("/rank-author", response_model=List[RankedAuthor])
|
||||
async def rank_author(request: KeywordToAuthorRequest):
|
||||
logger.info(
|
||||
"rank-author keywords=%s operator=%s uni_id=%s",
|
||||
@@ -21,4 +23,8 @@ async def rank_author(request: KeywordToAuthorRequest):
|
||||
request.operator,
|
||||
request.uni_id,
|
||||
)
|
||||
return {"status": "ok"}
|
||||
return await logic.rank_authors_by_keywords(
|
||||
request.keywords,
|
||||
request.operator,
|
||||
request.uni_id,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user