Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/Keyword_search_rework
This commit is contained in:
@@ -69,11 +69,29 @@ for idx in cordis_eu_fp7_euroscivoc cordis_eu_horizon_2020_euroscivoc cordis_eu_
|
||||
done
|
||||
```
|
||||
|
||||
DFG (keyword is the `fach` subject classification, potentially several per
|
||||
project, project id in the `project_id` field). `--text-field` takes a dotted
|
||||
path into the `subject_classifications` array of objects:
|
||||
|
||||
```bash
|
||||
python map_project_topics.py \
|
||||
--source-index dfg_projects_2.0 \
|
||||
--text-field subject_classifications.fach \
|
||||
--project-id-field project_id \
|
||||
--output-index projects_dfg_openalex_topics
|
||||
```
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Resumable**: source documents whose id already exists in the output index
|
||||
are skipped; the coverage is logged at startup (`Coverage: X/Y already in
|
||||
index, Z still to be processed`). Just rerun after an interruption.
|
||||
- **Multi-valued text fields**: a dotted `--text-field` (e.g.
|
||||
`subject_classifications.fach`) descends into arrays of objects and produces
|
||||
one output document per distinct value. Documents with a single value keep
|
||||
the source `_id` as output id; documents with several values get
|
||||
`<source_id>::<sha1(value)[:12]>` per value, so resumability works per
|
||||
(project, keyword) pair.
|
||||
- **Incremental**: each unique keyword is searched once, results are
|
||||
bulk-indexed chunk by chunk with progress logs.
|
||||
- **Fail-fast**: exits immediately with a clear message if the backend or the
|
||||
|
||||
@@ -5,7 +5,9 @@ map_project_topics.py — Map project keywords to OpenAlex topics.
|
||||
Streams all documents from a source index, reads a configurable text field
|
||||
(the "project-specific keyword"), matches every unique keyword against
|
||||
OpenAlex topics, and persists one document per (project, keyword) pair into
|
||||
the output index using mapping.PROJECT_TOPICS_MAPPING:
|
||||
the output index using mapping.PROJECT_TOPICS_MAPPING. The text field may be
|
||||
a dotted path into arrays of objects (e.g. subject_classifications.fach);
|
||||
every distinct value then yields its own output document:
|
||||
|
||||
{project_id, keyword, source_index, source_field, topic_matches[],
|
||||
match_method, model_name, built_at}
|
||||
@@ -28,6 +30,14 @@ Usage (EU EuroSciVoc, project id in the projectID source field):
|
||||
--project-id-field projectID \
|
||||
--output-index projects_eu_openalex_topics
|
||||
|
||||
Usage (DFG, keyword is the fach subject classification, several per project,
|
||||
project id in the project_id source field):
|
||||
python map_project_topics.py \
|
||||
--source-index dfg_projects_2.0 \
|
||||
--text-field subject_classifications.fach \
|
||||
--project-id-field project_id \
|
||||
--output-index projects_dfg_openalex_topics
|
||||
|
||||
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY (and for
|
||||
--*-cluster nes: ELASTICSEARCH_URL/ELASTICSEARCH_API_KEY) in the environment
|
||||
or in the service .env, plus a running backend serving
|
||||
@@ -37,6 +47,7 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -49,12 +60,12 @@ import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from service.scripts.projects.topic_mapper.mapping import PROJECT_TOPICS_MAPPING
|
||||
from mapping import PROJECT_TOPICS_MAPPING
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_ENV_FILE = Path(__file__).resolve().parents[2] / "src" / "main" / "inse" / ".env"
|
||||
DEFAULT_ENV_FILE = Path(__file__).resolve().parents[3] / "src" / "main" / "inse" / ".env"
|
||||
DEFAULT_API_BASE_URL = "http://localhost:8000" #backend TODO replace with env variable
|
||||
VECTOR_SEARCH_PATH = "/api/topics/vector-search"
|
||||
MATCH_METHOD = "sentence_transformer"
|
||||
@@ -198,12 +209,47 @@ async def ensure_index(index: str, cluster: str) -> None:
|
||||
logger.info("Created output index '%s' with explicit mapping.", index)
|
||||
|
||||
|
||||
def extract_text_values(source: dict, field_path: str) -> list[str]:
|
||||
"""Collects every non-empty value at a dotted field path as strings.
|
||||
|
||||
Descends into arrays of objects at any level (e.g.
|
||||
subject_classifications.fach) and deduplicates while preserving order.
|
||||
A flat scalar field yields at most one value, as before.
|
||||
"""
|
||||
values: list[Any] = [source]
|
||||
for part in field_path.split("."):
|
||||
next_values: list[Any] = []
|
||||
for value in values:
|
||||
for item in value if isinstance(value, list) else [value]:
|
||||
if isinstance(item, dict) and part in item:
|
||||
next_values.append(item[part])
|
||||
values = next_values
|
||||
|
||||
texts: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for value in values:
|
||||
for item in value if isinstance(value, list) else [value]:
|
||||
text = "" if item is None else str(item).strip()
|
||||
if text and text not in seen:
|
||||
seen.add(text)
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
async def fetch_source_entries(
|
||||
index: str, cluster: str, text_field: str, id_field: str | None, max_docs: int | None
|
||||
) -> dict[str, tuple[str, str]]:
|
||||
"""Returns doc_id -> (project_id, keyword) for every source document."""
|
||||
"""Returns output_doc_id -> (project_id, keyword) for every source document.
|
||||
|
||||
Documents with a single text value keep their source _id as output id
|
||||
(backwards compatible with existing output indices); documents with
|
||||
several values (e.g. multiple subject classifications) get one entry per
|
||||
value with the id "<source_id>::<sha1(keyword)[:12]>", so resumability
|
||||
keeps working per (project, keyword) pair.
|
||||
"""
|
||||
entries: dict[str, tuple[str, str]] = {}
|
||||
total = 0
|
||||
docs_with_text = 0
|
||||
if id_field == "_id":
|
||||
id_field = None
|
||||
source_fields = [text_field] + ([id_field] if id_field else [])
|
||||
@@ -216,10 +262,21 @@ async def fetch_source_entries(
|
||||
):
|
||||
total += 1
|
||||
doc_source = hit.get("_source", {})
|
||||
text = str(doc_source.get(text_field) or "").strip()
|
||||
project_id = str(doc_source.get(id_field) or "").strip() if id_field else hit["_id"]
|
||||
if text and project_id:
|
||||
entries[hit["_id"]] = (project_id, text)
|
||||
keywords = extract_text_values(doc_source, text_field)
|
||||
if id_field:
|
||||
id_values = extract_text_values(doc_source, id_field)
|
||||
project_id = id_values[0] if id_values else ""
|
||||
else:
|
||||
project_id = hit["_id"]
|
||||
if keywords and project_id:
|
||||
docs_with_text += 1
|
||||
for keyword in keywords:
|
||||
if len(keywords) == 1:
|
||||
out_id = hit["_id"]
|
||||
else:
|
||||
digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12]
|
||||
out_id = f"{hit['_id']}::{digest}"
|
||||
entries[out_id] = (project_id, keyword)
|
||||
if total % 50000 == 0:
|
||||
logger.info("Scanned %d source documents...", total)
|
||||
if max_docs and total >= max_docs:
|
||||
@@ -227,11 +284,12 @@ async def fetch_source_entries(
|
||||
break
|
||||
|
||||
logger.info(
|
||||
"Scanned %d documents from '%s', %d with a non-empty '%s'.",
|
||||
"Scanned %d documents from '%s', %d with a non-empty '%s' (%d project/keyword pairs).",
|
||||
total,
|
||||
index,
|
||||
len(entries),
|
||||
docs_with_text,
|
||||
text_field,
|
||||
len(entries),
|
||||
)
|
||||
return entries
|
||||
|
||||
@@ -463,14 +521,21 @@ def main() -> None:
|
||||
" python map_project_topics.py --source-index projects_bund_v1 "
|
||||
"--text-field Leistungsplansystematik_fullname --output-index projects_bund_openalex_topics\n"
|
||||
" python map_project_topics.py --source-index cordis_eu_fp7_euroscivoc "
|
||||
"--text-field title --project-id-field projectID --output-index projects_eu_openalex_topics"
|
||||
"--text-field title --project-id-field projectID --output-index projects_eu_openalex_topics\n"
|
||||
" python map_project_topics.py --source-index dfg_projects_2.0 "
|
||||
"--text-field subject_classifications.fach --project-id-field project_id "
|
||||
"--output-index projects_dfg_openalex_topics"
|
||||
),
|
||||
)
|
||||
parser.add_argument("--source-index", required=True, help="Index to read projects from")
|
||||
parser.add_argument(
|
||||
"--text-field",
|
||||
required=True,
|
||||
help="Source field holding the project-specific keyword to match",
|
||||
help=(
|
||||
"Source field holding the project-specific keyword to match; dotted "
|
||||
"paths descend into arrays of objects and map every distinct value "
|
||||
"(e.g. subject_classifications.fach for dfg_projects_2.0)"
|
||||
),
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output-index", required=True, help="Index to persist the topic mappings into"
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
One document per (project, keyword) pair. For sources where the keyword field
|
||||
is unique per project (e.g. projects_bund_v1 Leistungsplansystematik_fullname)
|
||||
this means one document per project.
|
||||
this means one document per project; for multi-valued sources (e.g.
|
||||
dfg_projects_2.0 subject_classifications.fach) several documents per project.
|
||||
"""
|
||||
|
||||
PROJECT_TOPICS_MAPPING = {
|
||||
|
||||
Reference in New Issue
Block a user