Files
smartguide/service/scripts/falkordb/README.md
T
arzani 552fa2daaf
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
Added fakordb tests
2026-11-03 13:50:10 +01:00

290 lines
17 KiB
Markdown

# FalkorDB example: a researcher graph from the INSE sources
`load_graph.py` builds a small knowledge graph in [FalkorDB](https://www.falkordb.com/) around a
couple of researchers from the predefined ("default") organizations in
`src/data/predefined_accounts.json`, i.e. Universität Duisburg-Essen (`I62318514`),
Ruhr-Universität Bochum (`I904495901`) and TU Dortmund (`I200332995`).
It does not talk to OpenAlex, EPO or CORDIS directly. Every fact comes from the backend's existing
source logic in `src/main/inse`, which reads the INSE Elasticsearch mirrors, so the graph shows
exactly what the REST API can already see:
| Source | Backend function | Graph |
| --- | --- | --- |
| OpenAlex authors (profile, ORCID, metrics, affiliations, topics) | `authors.v2.service.search_authors` / `get_author_by_id_strict_or_raise` | `Author`, `Institution`, `Topic`, `AFFILIATED_WITH`, `WORKS_ON` |
| OpenAlex works incl. co-authors and their institutions | `works.v2.service.get_author_works` | `Work`, `AUTHORED`, `HAS_TOPIC`, co-author `Author`s |
| CORDIS (EU) and DFG projects, bridged through publication DOIs | `works.logic.get_publication_dois_of_author`, `projects.projects_search_client.get_cordis_eu_project_ids_by_dois` / `get_dfg_project_ids_by_dois`, `get_enriched_cordis_project_by_id`, `get_dfg_project_by_id` | `Project`, `CONTRIBUTED_TO` |
| EPO + USPTO patents (name matching with institution guard) | `patents.authors.logic.get_patents_by_author_id` | `Patent`, `INVENTOR_OF`, `HAS_TOPIC` |
| Funders of the author's funded publications | `funders.logic.get_funders_by_author_id` | `Funder`, `FUNDED_BY` (author and work level) |
| News mentions (UDE "aktuell", CC-News) | `news.logic.get_news_by_author` | `NewsArticle`, `MENTIONED_IN`, `HAS_TOPIC` |
| Handelsregister officer matches | `company_connections.logic.get_company_connections_by_author_id` | `Company`, `OFFICER_OF` |
| Predefined organizations | `src/data/predefined_accounts.json`, `institutions.v2.service.get_institution_by_id` | `Organization`, `REPRESENTS`, `MEMBER_OF` |
Co-authorship is not computed in Python. After loading, one Cypher query derives
`(:Author)-[:CO_AUTHOR {weight, first_year, last_year}]->(:Author)` from the `AUTHORED` edges,
which is the part the in-service collaboration-graph API currently leaves to the client.
## Prerequisites
1. A FalkorDB server. The quickest way is the official image, which also serves a browser UI on
port 3000:
```bash
docker run -d --name falkordb -p 6379:6379 -p 3000:3000 falkordb/falkordb:latest
```
2. The service image `inse-service:1.0.0` (built by `./gradlew :service:createImage`, and already
present if you ever ran `./gradlew :service:serve`). The script imports the `inse` package, whose
`util` module pulls in sentence-transformers/torch, so the image is the easiest runtime that has
every dependency. `src/main/inse/.env` must contain the Elasticsearch credentials as usual.
## Run
```bash
cd service
scripts/falkordb/run.sh # 2 researchers per default organization
scripts/falkordb/run.sh --reset --organization Duisburg --per-org 3
scripts/falkordb/run.sh --author-id A5040796987 --author-id A5122994949 # explicit researchers, added incrementally
scripts/falkordb/run.sh --no-write --dump /scripts/falkordb/graph.json # collect only, inspect the JSON
scripts/falkordb/run.sh --help
```
`run.sh` starts a throwaway container from the service image, mounts `src/main`, `src/data` and
`scripts`, installs `falkordb` from `requirements.txt` and reaches the server on the host through
`host.docker.internal`. Override the target with `FALKORDB_HOST`, `FALKORDB_PORT`,
`FALKORDB_PASSWORD` and `FALKORDB_GRAPH` (default graph name `inse`).
Loads are idempotent: every node and edge is `MERGE`d on its `id`, so re-running or adding
researchers with `--author-id` extends the same graph. `--reset` drops the graph right before
writing, after all sources were collected. One failing source is logged and skipped, it does not
abort the load.
A default run (six researchers, 40 works each) takes a few minutes and ends with roughly 2,300 nodes
and 9,000 relationships. The slow parts are the DOI-to-project lookups (one detail query per hit)
and the EPO/USPTO scans for common names.
### How the researchers are picked
For each organization the script reuses the backend's active-cohort membership query
(`authors.institution_membership_query.build_institution_membership_query`, last known institution
plus an affiliation since the current year minus two) and then narrows the candidates so the graph
stays small and well disambiguated:
- `works_count` within `--min-works`/`--max-works` (default 20 to 300) to skip hyper-authorship
profiles from large collaborations,
- an ORCID unless `--no-require-orcid` is given,
- every last known institution inside the organization's OpenAlex lineage, which drops merged
profiles that also "currently" belong to unrelated institutions,
- sorted by `works_count`, then `cited_by_count`.
Works with more than `--max-authors-per-work` authors (default 30) keep their `Work` node but only
the seed researcher's own `AUTHORED` edge, so a single CERN paper cannot add a thousand co-authors.
## Schema
Node labels, all keyed by `id` (OpenAlex ids are stored without the `https://openalex.org/` prefix,
patents as `<source>:<patent_id>`, projects as `cordis:<id>` / `dfg:<id>`):
| Label | Properties |
| --- | --- |
| `Organization` | `name`, `openalex_institution_id` |
| `Institution` | `name`, `ror`, `country_code`, `type` |
| `Author` | `name`, `orcid`, `works_count`, `cited_by_count`, `h_index`, `i10_index`, `seed` (true for the selected researchers, false for co-authors) |
| `Work` | `title`, `year`, `type`, `language`, `cited_by_count`, `authors_count`, `hyperauthorship` |
| `Topic` | `name`, `subfield`, `field`, `domain` |
| `Project` | `source` (`cordis`/`dfg`), `source_id`, `title`, `acronym`, `start`, `end`, `funding_scheme`, `status`, `ec_max_contribution`, `url` |
| `Patent` | `patent_id`, `source` (EPO/USPTO), `title`, `year`, `publication_date`, `kind`, `status`, `country`, `ipc[]`, `assignees[]`, `inventors[]` |
| `Funder` | `name` |
| `NewsArticle` | `title`, `date`, `url` |
| `Company` | `name`, `status`, `registered_office`, `register` |
Relationships:
| Relationship | Properties |
| --- | --- |
| `(Organization)-[:REPRESENTS]->(Institution)` | |
| `(Author)-[:MEMBER_OF]->(Organization)` | |
| `(Author)-[:AFFILIATED_WITH]->(Institution)` | `years[]`, `last_known` (seed profiles only) |
| `(Author)-[:WORKS_ON]->(Topic)` | `score` |
| `(Author)-[:AUTHORED]->(Work)` | `position`, `corresponding` |
| `(Author)-[:CO_AUTHOR]->(Author)` | `weight`, `first_year`, `last_year` (derived in FalkorDB, `a.id < b.id`) |
| `(Work)-[:HAS_TOPIC]->(Topic)`, `(Patent)-[:HAS_TOPIC]->(Topic)`, `(NewsArticle)-[:HAS_TOPIC]->(Topic)` | `score` (works) |
| `(Author)-[:CONTRIBUTED_TO]->(Project)` | `via` = `publication_doi` |
| `(Author)-[:INVENTOR_OF]->(Patent)` | |
| `(Author)-[:FUNDED_BY]->(Funder)` | `publications` |
| `(Work)-[:FUNDED_BY]->(Funder)` | only for works that are in the graph |
| `(Author)-[:MENTIONED_IN]->(NewsArticle)` | `matching` = `display_name` |
| `(Author)-[:OFFICER_OF]->(Company)` | `positions[]`, `matching_method`, `common_name_warning` |
## Example queries
The queries for the whole-university graph `ude` are collected in [QUERIES.md](QUERIES.md).
The ones below target the small `inse` example graph.
Paste these into the FalkorDB browser (http://localhost:3000, graph `inse`) or run them with the
Python client (`FalkorDB(host="localhost").select_graph("inse").ro_query(...)`).
Everything around one researcher, for the visual explorer:
```cypher
MATCH (a:Author {seed: true})-[r]-(n) WHERE a.name STARTS WITH 'Nikolai' RETURN a, r, n LIMIT 200
```
Seed researchers per organization with counts per source:
```cypher
MATCH (o:Organization)<-[:MEMBER_OF]-(a:Author)
OPTIONAL MATCH (a)-[:AUTHORED]->(w:Work)
OPTIONAL MATCH (a)-[:CONTRIBUTED_TO]->(p:Project)
OPTIONAL MATCH (a)-[:INVENTOR_OF]->(pt:Patent)
OPTIONAL MATCH (a)-[:OFFICER_OF]->(c:Company)
RETURN o.name, a.name, count(DISTINCT w) AS works, count(DISTINCT p) AS projects,
count(DISTINCT pt) AS patents, count(DISTINCT c) AS companies
ORDER BY o.name, a.name
```
Strongest co-authors and where they sit:
```cypher
MATCH (s:Author {seed: true})-[c:CO_AUTHOR]-(o:Author)-[:AFFILIATED_WITH]->(i:Institution)
WITH s, o, c, collect(DISTINCT i.name) AS insts ORDER BY c.weight DESC
RETURN s.name, collect(o.name + ' (' + toString(c.weight) + ') @ ' + insts[0])[0..5] AS top
```
Topics shared by two of the selected researchers:
```cypher
MATCH (a:Author {seed: true})-[:WORKS_ON]->(t:Topic)<-[:WORKS_ON]-(b:Author {seed: true})
WHERE a.id < b.id RETURN a.name, b.name, collect(t.name) AS topics
```
Funders that several selected researchers share:
```cypher
MATCH (a:Author {seed: true})-[:FUNDED_BY]->(f:Funder)<-[:FUNDED_BY]-(b:Author {seed: true})
WHERE a.id < b.id
RETURN f.name, collect(DISTINCT a.name + ' & ' + b.name) AS pairs ORDER BY size(pairs) DESC LIMIT 5
```
Projects per source and patents with their OpenAlex topics:
```cypher
MATCH (a:Author)-[:CONTRIBUTED_TO]->(p:Project) RETURN p.source, count(DISTINCT p), collect(DISTINCT a.name)
```
```cypher
MATCH (a:Author)-[:INVENTOR_OF]->(p:Patent)
OPTIONAL MATCH (p)-[:HAS_TOPIC]->(t:Topic)
RETURN a.name, p.source, p.year, left(p.title, 60), collect(t.name)[0..2] ORDER BY p.year DESC LIMIT 10
```
Company links, showing which ones rest on a common name:
```cypher
MATCH (a:Author)-[r:OFFICER_OF]->(c:Company)
RETURN a.name, r.common_name_warning, count(c) AS companies, collect(c.name)[0..3] AS sample
```
Cross-organization paths through up to two co-authorship hops:
```cypher
MATCH path = (o1:Organization)<-[:MEMBER_OF]-(:Author)-[:CO_AUTHOR*1..2]-(:Author)-[:MEMBER_OF]->(o2:Organization)
WHERE o1.name < o2.name RETURN o1.name, o2.name, count(path)
```
## Whole-university graph: `bulk_load.py`
`load_graph.py` is the per-researcher example. `bulk_load.py` builds the graph for a whole
organization by scanning each Elasticsearch source once and streaming into FalkorDB:
```bash
scripts/falkordb/run.sh bulk --graph ude --reset # full UDE cohort, all phases
scripts/falkordb/run.sh bulk --graph ude_test --reset --limit-authors 25 # smoke test, a few seconds
scripts/falkordb/run.sh bulk --graph ude --phases projects derive # re-run selected phases (idempotent)
```
Phases, in order (`--phases` selects a subset; later phases reload cohort and works from the graph):
| Phase | Source | Adds |
| --- | --- | --- |
| `cohort` | active researchers via `build_institution_membership_query` (last known institution + affiliation in the last two years) | `Author` with extra label `Cohort`, `MEMBER_OF`, `AFFILIATED_WITH {years, last_known}`, `WORKS_ON`, `Institution` lineage as `PART_OF` |
| `works` | one `scan` of the works index for every work of every cohort researcher | `Work` (incl. `doi`, `is_oa`, `fwci`), every authorship as `AUTHORED`, co-author `Author`s, `AFFILIATED_WITH`, `HAS_TOPIC`, `Venue` + `PUBLISHED_IN`, `Funder` + `FUNDED_BY {awards}` |
| `institutions` | `openalex-institutions` index | names, countries and types for institutions that only appeared as lineage ancestors |
| `affiliations` | second, lighter scan of the works index | `AUTHORED.institution_ids` (institutions on that authorship) and `Work-[:INVOLVES {authors}]->Institution`, the per-work view that author-level `AFFILIATED_WITH` cannot give |
| `classifications` | `work-classifications` index (LLM) | `Work.primary_category`, `pasteur_quadrant`, `applied_orientation_score`, `classification_confidence` |
| `projects` | CORDIS publications and DFG project publications by DOI; CORDIS organisations and DFG institutes of the organization; DFG persons by ORCID; project details | `Project {source: cordis/dfg}`, `Work-[:OUTPUT_OF]->Project`, `Institution-[:PARTICIPATES_IN {role, ec_contribution}]->Project`, `Author-[:DFG_ROLE {role}]->Project`, `EuOrganization-[:PARTICIPATES_IN]->Project` (consortium partners) |
| `patents` | `org_patents` index (pre-matched by `index_org_patents.py`) | `Patent`, `Author-[:INVENTOR_OF {match_type}]->Patent`, `HAS_TOPIC` |
| `news` | `aktuell_postproc` author names matched exactly to cohort display names (the rule the news API uses), articles from `aktuell`, topics from `aktuell_openalex_topics` | `NewsArticle`, `MENTIONED_IN {ambiguous}`, `HAS_TOPIC {keyword}` |
| `companies` | `get_company_connections_by_author_id` per researcher, 8 in parallel | `Company`, `OFFICER_OF`; common-name matches are only counted on the Author (`hr_company_matches`, `hr_common_name_warning`) unless `--include-ambiguous-companies` |
| `hierarchy` | `get_topic_hierarchy()` | `Domain`, `Field`, `Subfield`, `IN_DOMAIN`, `IN_FIELD`, `IN_SUBFIELD` |
| `derive` | Cypher inside FalkorDB | `CO_AUTHOR {weight, first_year, last_year}`, `Author-[:FUNDED_BY {publications}]->Funder`, `Author-[:CONTRIBUTED_TO {works}]->Project` for cohort members |
| `profile` | aggregation over the cohort's works | `Institution-[:ACTIVE_IN {level, works, researchers}]->Topic/Subfield/Field/Domain`, the drawable research profile |
Co-author policy: every authorship is an `AUTHORED` edge, including 5,000-author collaboration
papers. `CO_AUTHOR` pairs are derived for all author pairs on works with at most `--pair-cap`
authors (default 30) and, on larger works, only for pairs that involve a cohort member. All pairs
on the UDE cohort's works would be 2.9 billion edges; the anchored policy gives about 10 million.
Edges always point from the smaller to the larger author id, so treat them as undirected.
Writes go through `GraphWriter`: rows are buffered per label / relationship type and flushed with
`UNWIND ... MERGE` in batches of 2,000, node buffers before edge buffers. Cohort profiles use
`SET`, co-author stubs use `ON CREATE SET`, so a researcher who is both keeps the full profile.
One failing phase is logged and the next phase still runs. The script ends with `BGSAVE`.
### Result for Universität Duisburg-Essen (2026-09-15)
Cohort of 6,176 active researchers, every work of every cohort member, no author cap. The load
ran in about 12 minutes of pipeline time (works scan 6.5 min, derive 100 s, everything else under
a minute each); FalkorDB holds it in 1.04 GB and the RDB snapshot is 264 MB.
| Nodes | | Relationships | |
| --- | --- | --- | --- |
| Author | 693,487 (6,176 also `:Cohort`) | AUTHORED | 4,112,809 (2,376,034 with `institution_ids`) |
| Work | 204,110 | CO_AUTHOR | 3,782,011 |
| Institution | 26,246 | AFFILIATED_WITH / INVOLVES | 1,072,837 / 784,212 |
| Venue | 16,534 | HAS_TOPIC | 571,906 |
| Funder | 7,493 | FUNDED_BY (work + author level) | 229,219 |
| EuOrganization | 5,469 | PUBLISHED_IN | 173,495 |
| Topic | 4,516 | WORKS_ON | 27,255 |
| NewsArticle | 4,402 | PARTICIPATES_IN | 17,046 |
| Project | 3,664 | MENTIONED_IN | 11,251 |
| Company | 547 | PART_OF | 11,045 |
| Patent | 366 | OUTPUT_OF / CONTRIBUTED_TO | 8,292 / 6,723 |
| Subfield / Field / Domain | 252 / 26 / 4 | OFFICER_OF / DFG_ROLE / INVENTOR_OF | 700 / 548 / 367 |
| | | ACTIVE_IN (institution research profile) | 4,618 |
Source coverage of the cohort: all 6,176 have works, 1,741 are linked to projects, 1,925 are
mentioned in news, 406 have unambiguous company links, 163 hold indexed patents, 164 were matched to
DFG persons through their ORCID. 187,000 works carry an LLM classification.
Two server behaviours matter at this scale and are handled in the script: FalkorDB caps every
result set at `RESULTSET_SIZE` rows (10,000 in the default container), so whole-graph reads are
paged (`GraphWriter.ro_all`); and write queries ignore timeouts, which is why the co-author
derivation computes pairs in Python and bulk-creates edges instead of running
`MATCH ... MERGE` inside the graph (that took over a minute per 2,000 works).
## Caveats worth knowing
- In the whole-university graph, common-name company matches are not written as edges by default
(406 researchers have unambiguous links, the rest only carry `hr_company_matches`).
- News and Handelsregister links are name matches, exactly as in the REST API. The `OFFICER_OF`
edge carries `common_name_warning`; a researcher named Thomas Kaiser gets 92 companies with the
flag set, Ahmet Karkar gets one without it.
- Patents are matched by inventor name with the institution guard from `patents.authors.logic`;
the backend logs `search_completeness=truncated_inconclusive` for common names.
- The project bridge is DOI based: a researcher is linked to every CORDIS/DFG project that lists one
of their publications, regardless of author position.
- OpenAlex profiles can be merged across institutions. The lineage filter above avoids most of
them for the automatic selection, `--author-id` takes whatever you give it.
- `Author.topics` in the mirror carry a `score` where OpenAlex has a `count`; the value is stored
as-is on `WORKS_ON`.
## Running without Docker
Create a Python 3.12 environment with the service dependencies (`pip install -e` is not set up, so
install `fastapi httpx pydantic pydantic-settings sqlmodel python-dotenv pyyaml pyjwt openai pandas
pypdf sentence-transformers torch` matching `pyproject.toml`) plus `falkordb`, then run
`python scripts/falkordb/load_graph.py` from `service/`. The script locates `src/main/inse` and its
`.env` relative to its own path.