Files
smartguide/service/scripts/test_keywords_matching.py
T
Kazgatari a6dc55a44d
LocationBasedServices/smartguide/pipeline/head This commit looks good
evaluation for topic index keywords & keyword index matching
2026-07-16 19:07:57 +02:00

146 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""
test_keywords_matching.py
Checks if the keywords inside the openalex-topics index
match the keywords inside the openalex-keywords index.
"""
from __future__ import annotations
import asyncio
import json
import logging
import sys
from pathlib import Path
current_dir = Path(__file__).resolve().parent
sys.path.insert(0, str(current_dir.parent / "src" / "main"))
from inse.integrations import elasticsearch
from inse.model import ESCluster
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
async def run() -> None:
topic_keywords = {}
count = 0
async for hit in elasticsearch.scan(
index="openalex-topics",
query={"match_all": {}},
source=["id", "display_name", "keywords"],
cluster=ESCluster.NES
):
source = hit.get("_source", {})
topic_id = source.get("id")
topic_name = source.get("display_name")
keywords = source.get("keywords") or []
for kw in keywords:
if kw not in topic_keywords:
topic_keywords[kw] = []
topic_keywords[kw].append({"id": topic_id, "display_name": topic_name})
count += 1
logger.info("Total topics processed: %d", count)
logger.info("Total unique keywords found in topics: %d", len(topic_keywords))
#Identify duplicates (keywords shown in multiple topics)
duplicate_keywords = {
kw: topics for kw, topics in topic_keywords.items() if len(topics) > 1
}
logger.info("Keywords appearing in multiple topics (duplicates): %d", len(duplicate_keywords))
# Query openalex-keywords to see if the keywords exist
logger.info("Step 3: Querying 'openalex-keywords' for matching keywords...")
unique_kws = list(topic_keywords.keys())
found_kws_exact = set()
batch_size = 1000
for i in range(0, len(unique_kws), batch_size):
batch = unique_kws[i : i + batch_size]
query = {
"query": {
"terms": {
"display_name.keyword": batch
}
},
"size": len(batch),
"_source": ["display_name"]
}
res = await elasticsearch.search(index="openalex-keywords", body=query, cluster=ESCluster.NES)
hits = res.get("hits", {}).get("hits", [])
for hit in hits:
display_name = hit.get("_source", {}).get("display_name")
if display_name:
found_kws_exact.add(display_name)
# Fetch all keywords from openalex-keywords to check case-insensitive matches
logger.info("Fetching all keywords from 'openalex-keywords' to check case-insensitive matches...")
all_es_keywords = {} # lowercase_name -> original_name
count_es = 0
async for hit in elasticsearch.scan(
index="openalex-keywords",
query={"match_all": {}},
source=["display_name"],
cluster=ESCluster.NES
):
display_name = hit.get("_source", {}).get("display_name")
if display_name:
all_es_keywords[display_name.lower()] = display_name
count_es += 1
logger.info("Total keywords in 'openalex-keywords' loaded: %d", count_es)
missing_exact = []
missing_case_insensitive = []
case_mismatches = []
for kw in unique_kws:
kw_lower = kw.lower()
if kw in found_kws_exact:
continue
# Check case-insensitive
if kw_lower in all_es_keywords:
es_kw = all_es_keywords[kw_lower]
case_mismatches.append({"topic_keyword": kw, "es_keyword": es_kw})
else:
missing_case_insensitive.append(kw)
missing_exact.append(kw)
logger.info("--- RESULTS SUMMARY ---")
logger.info("Total Unique Keywords in Topics: %d", len(topic_keywords))
logger.info("Keywords matching exactly in openalex-keywords: %d", len(found_kws_exact))
logger.info("Keywords matching case-insensitively but not exactly: %d", len(case_mismatches))
logger.info("Keywords completely missing from openalex-keywords: %d", len(missing_case_insensitive))
# Write detailed results
results = {
"summary": {
"total_topics_processed": count,
"total_unique_topic_keywords": len(topic_keywords),
"duplicate_topic_keywords_count": len(duplicate_keywords),
"exact_matches_count": len(found_kws_exact),
"case_mismatches_count": len(case_mismatches),
"completely_missing_count": len(missing_case_insensitive),
},
"duplicates": {
kw: [t["id"] for t in topics]
for kw, topics in sorted(duplicate_keywords.items(), key=lambda x: len(x[1]), reverse=True)
},
"case_mismatches": case_mismatches,
"completely_missing": sorted(missing_case_insensitive)
}
output_file = current_dir.parent / "src" / "data" / "keywords_comparison_results.json"
output_file.parent.mkdir(parents=True, exist_ok=True)
output_file.write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8")
def main() -> None:
asyncio.run(run())
if __name__ == "__main__":
main()