Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ OQO --> oqo_to_sql() (registry) --> .api_execute() / .api_execute_groups() --> J
| `R/oqo_to_sql.R` | tree walk: AND/OR/negation, NULL-safe leaves, sort, group spec, relevance score |
| `R/execute.R` | records and grouped responses, paging, sample, single works |
| `R/translate.R` | OpenAlex `/query` calls (httr2), cache |
| `R/links.R` | `/links`: local filter parser (no OpenAlex translation), records and groups |
| `R/routes.R` | plumber2 app, `serve_corpus()`, the page (`/app`, `/assets/`) |
| `inst/www/` | page: `index.html` (template, `{{v}}` = asset stamp), `query.js` (pure, tested), `app.js` (DOM) |
| `inst/extdata/oqo_translations.*` | recorded `/query` survey (see `tools/`) |
Expand Down Expand Up @@ -69,6 +70,11 @@ OQO --> oqo_to_sql() (registry) --> .api_execute() / .api_execute_groups() --> J
cast back (`.api_column_types`). The snapshot's `abstract_inverted_index` is a JSON string: cast to
`MAP(VARCHAR, BIGINT[])` via JSON; records with repeated keys (~0.6 %) fail that cast and are
merged by `.api_merge_duplicate_keys()` (`json_each`).
- **Links**: `links/` next to the corpus (STANDARD.md §7) -> table `links` (DISTINCT over
partitions; missing K1 columns added as NULL; empty table when there is none), ends matched by
`link_key()` (DOI -> `doi:<doi_key>`, OpenAlex URL or bare ID -> `id_key`, else as stored,
e.g. `zenodo:123`). Its files are part of the cache key. OpenAlex's `/query` does not
translate `/links`, so `.api_links_where()` parses `key:value` itself.
- **`.api_build_version`** is part of the cache key: **bump it whenever `.api_build()` (or
anything it creates) changes**, or users keep a stale cache.
- **Search**: two FTS tables (`oaapi_docs_stem` Porter + English stop words, `oaapi_docs_exact`
Expand Down Expand Up @@ -150,9 +156,9 @@ delete `README.html`.
## Branching

- `claude/<description>` branches from `dev`; merge into `dev`; `main` gets release commits only.
- Public since 0.1.0 (alpha); archived on Zenodo, concept DOI 10.5281/zenodo.24514237 (cite that one). Not on the openalexPro r-universe (it is not in the r-universe
registry; add it there only when it leaves alpha); installed from GitHub. Listed on the org
landing page (openalexpro.github.io) and org profile (dot-github) as Alpha.
- Public since 0.1.0 (alpha), beta and on the openalexPro r-universe (from `main`) since 0.1.6;
archived on Zenodo, concept DOI 10.5281/zenodo.24514237 (cite that one). Listed on the org
landing page (openalexpro.github.io) and org profile (dot-github) as Beta.
- Stacked PRs, merge in order: #1 filters, #2 group_by, #3 search, #4 page, #5 docs,
#6 performance, #7 more filters (lineage, funders, affiliation/author search, proximity, ...).

Expand Down
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Package: openalexAPI
Title: Local OpenAlex-Compatible Web API over a Parquet Corpus
Version: 0.1.5
Version: 0.1.6
Authors@R:
person("Rainer M", "Krug", , "Rainer@krugs.de", role = c("aut", "cre"),
comment = c(ORCID = "0000-0002-7490-0066"))
Expand Down
16 changes: 16 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
# openalexAPI 0.1.6

- Status: beta (was alpha). openalexAPI is now on the openalexPro r-universe:
`install.packages("openalexAPI", repos = c("https://openalexpro.r-universe.dev", "https://cloud.r-project.org"))`.

- New route `GET /links`: the corpus's link table (`links/` next to the
corpus, STANDARD.md §7), shaped like OpenAlex's `/links`. Records come as
stored, so all link types and relations of the source are served (e.g.
every related identifier of an openalexImportZenodo corpus, also those
without an OpenAlex link type) with their extra columns. Filters `origin`,
`target` (any ID or DOI form), `link_type` (short or URL), `relation`,
`origin_in_corpus`, `target_in_corpus`, with `|`, `!` and `null`; parsed
locally. No work needs to be named; `group_by` on `link_type`, `relation`
and the `*_in_corpus` flags; `sort`, `select`, paging. `/corpus` reports
the number of links. Cached databases are rebuilt once.

# openalexAPI 0.1.5

- The Hive partition keys of the corpus folders (`query=a/`, `year=2020/`,
Expand Down
57 changes: 54 additions & 3 deletions R/corpus.R
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
#' `abstract`), from a snapshot extraction, or from any source with the
#' OpenAlex works schema.
#'
#' The link table of the ecosystem standard, `links/` next to `corpus` (all
#' `*.parquet` below it), is read into a second table and served by `/links`.
#' Without it, `/links` has no rows.
#'
#' @param corpus Directory with the corpus Parquet files (searched
#' recursively).
#' @param rebuild Rebuild the database even if a cached one exists.
Expand All @@ -33,10 +37,11 @@ prepare_corpus <- function(
if (!length(files)) {
stop("No Parquet files found in `", corpus, "`.", call. = FALSE)
}
info <- file.info(files)
links <- .api_links_files(corpus)
info <- file.info(c(files, links))
key <- .api_md5(c(.api_build_version, corpus,
# whole seconds: image layers and some file systems drop the fraction
paste(files, info$size, floor(as.numeric(info$mtime)))))
paste(c(files, links), info$size, floor(as.numeric(info$mtime)))))
# one prefix per corpus, so the databases of older states can be found and removed
prefix <- paste0("oaapi_", substr(.api_md5(corpus), 1, 8), "_")
db <- file.path(cache_dir, paste0(prefix, key, ".duckdb"))
Expand All @@ -49,6 +54,7 @@ prepare_corpus <- function(
con <- .api_con(tmp)
on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE)
.api_build(con, files, corpus)
.api_build_links(con, links)
DBI::dbExecute(con, "CREATE TABLE oaapi_meta (corpus VARCHAR, built TIMESTAMP)")
DBI::dbExecute(con, paste0(
"INSERT INTO oaapi_meta VALUES (", DBI::dbQuoteLiteral(con, corpus), ", now())"
Expand All @@ -66,7 +72,7 @@ prepare_corpus <- function(
#' a version with another layout is rebuilt. Bump it when `.api_build()` changes.
#' @keywords internal
#' @noRd
.api_build_version <- "7"
.api_build_version <- "8"

#' Columns added by openalexPro or a query, not OpenAlex fields: never served
#' @keywords internal
Expand Down Expand Up @@ -146,6 +152,51 @@ prepare_corpus <- function(
invisible(con)
}

#' The link table's files: `*.parquet` below `links/` next to the corpus
#' @keywords internal
#' @noRd
.api_links_files <- function(corpus) {
list.files(file.path(dirname(corpus), "links"), "\\.parquet$", recursive = TRUE,
full.names = TRUE)
}

#' Columns every link table has (STANDARD.md K1)
#' @keywords internal
#' @noRd
.api_links_columns <- c(origin = "VARCHAR", target = "VARCHAR", link_type = "VARCHAR",
relation = "VARCHAR", origin_in_corpus = "BOOLEAN",
target_in_corpus = "BOOLEAN")

#' Build the `links` table: all link rows (repeats across partitions removed),
#' plus `oaapi_origin` / `oaapi_target` for matching ends in any form
#'
#' Missing standard columns are added as NULL, so every route can rely on
#' them; extra columns (e.g. `zenodo_relation_declared`) are served as stored.
#' @keywords internal
#' @noRd
.api_build_links <- function(con, files) {
std <- paste0("NULL::", .api_links_columns, " AS ", names(.api_links_columns))
if (!length(files)) {
DBI::dbExecute(con, paste("CREATE TABLE links AS SELECT", paste(std, collapse = ", "),
"WHERE false"))
} else {
src <- paste0("read_parquet(", .api_sql_list(con, files),
", union_by_name = true, hive_partitioning = false)")
cols <- DBI::dbGetQuery(con, paste("DESCRIBE SELECT * FROM", src))$column_name
add <- std[!names(.api_links_columns) %in% cols]
DBI::dbExecute(con, paste0(
"CREATE TABLE links AS SELECT DISTINCT *", if (length(add)) paste0(", ", add, collapse = ""),
" FROM ", src
))
}
DBI::dbExecute(con, paste(
"ALTER TABLE links ADD COLUMN oaapi_origin VARCHAR;",
"ALTER TABLE links ADD COLUMN oaapi_target VARCHAR;",
"UPDATE links SET oaapi_origin = link_key(origin), oaapi_target = link_key(target)"
))
invisible(con)
}

#' Hive partition keys of each file: `key=value` folders below `corpus`
#'
#' Any key at any depth; values are URL-decoded as in Hive. A data frame
Expand Down
151 changes: 151 additions & 0 deletions R/links.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# `/links`: the corpus's link table (STANDARD.md §7), shaped like OpenAlex's
# `/links`. OpenAlex's translator does not know these filters, so they are
# parsed here: `key:value` pairs joined by `,`, values joined by `|` (any of
# them), `!` negates, `null` means "missing".

#' Columns `/links` filters on, and those it groups by
#' @keywords internal
#' @noRd
.api_links_filters <- c("origin", "target", "link_type", "relation",
"origin_in_corpus", "target_in_corpus")

#' @keywords internal
#' @noRd
.api_links_groups <- c("link_type", "relation", "origin_in_corpus", "target_in_corpus")

#' A `link_type` value as the OpenAlex URL (`part` or the full URL)
#' @keywords internal
#' @noRd
.api_link_type <- function(x) {
ifelse(grepl("^https?://", x), x, paste0("https://openalex.org/link-types/", x))
}

#' The WHERE clause of a `/links` `filter=` value
#'
#' ponytail: values are split on `,` and `|`, so a value containing either
#' (rare in IDs and DOIs) cannot be filtered on; quote-aware splitting if needed.
#' @keywords internal
#' @noRd
.api_links_where <- function(con, filter) {
if (is.null(filter) || !nzchar(filter)) return("true")
conds <- vapply(strsplit(filter, ",", fixed = TRUE)[[1]], function(p) {
if (!grepl(":", p, fixed = TRUE)) {
.api_abort(sprintf("Filter `%s` needs the form `key:value`.", p))
}
key <- sub(":.*$", "", p)
value <- sub("^[^:]*:", "", p)
if (!key %in% .api_links_filters) {
.api_abort(sprintf("/links has no filter `%s`. Use one of: %s.", key,
paste(.api_links_filters, collapse = ", ")))
}
neg <- startsWith(value, "!")
vals <- strsplit(sub("^!", "", value), "|", fixed = TRUE)[[1]]
if (!length(vals) || any(!nzchar(vals))) {
.api_abort(sprintf("Filter `%s` has an empty value.", p))
}
is_null <- tolower(vals) == "null"
vals <- vals[!is_null]
col <- switch(key, origin = "oaapi_origin", target = "oaapi_target",
relation = "lower(relation)", key)
if (key %in% c("origin", "target")) vals <- .api_link_key(vals)
if (key == "link_type") vals <- .api_link_type(vals)
if (key == "relation") vals <- tolower(vals)
if (endsWith(key, "_in_corpus")) {
if (!all(tolower(vals) %in% c("true", "false"))) {
.api_abort(sprintf("Filter `%s` takes true, false or null.", key))
}
vals <- toupper(vals)
lit <- vals
} else {
lit <- DBI::dbQuoteLiteral(con, vals)
}
parts <- c(if (length(vals)) paste0(col, " IN (", paste(lit, collapse = ", "), ")"),
if (any(is_null)) paste(sub("^lower\\((.*)\\)$", "\\1", col), "IS NULL"))
cond <- paste0("(", paste(parts, collapse = " OR "), ")")
# as for works: a negated filter matches links where the value is missing
if (neg) paste0("NOT coalesce(", cond, ", false)") else cond
}, "")
paste(conds, collapse = " AND ")
}

#' Answer `GET /links`: records, or groups with `group_by`
#'
#' @param ctx The server context.
#' @param q The query parameters (list).
#' @return A JSON string.
#' @keywords internal
#' @noRd
.api_links <- function(ctx, q) {
t0 <- Sys.time()
con <- ctx$con
bad <- setdiff(names(q), c("filter", "group_by", .api_view_params))
if (length(bad)) {
.api_abort(sprintf("/links does not take `%s`.", paste(bad, collapse = "`, `")))
}
where <- .api_links_where(con, q$filter)
ms <- function() round(as.numeric(Sys.time() - t0, units = "secs") * 1000)
count <- DBI::dbGetQuery(con, paste("SELECT count(*) AS n FROM links WHERE", where))$n

if (!is.null(q$group_by)) {
g <- sub(":include_unknown$", "", q$group_by) # missing values always show as `unknown`
if (!g %in% .api_links_groups) {
.api_abort(sprintf("/links cannot group by `%s`. Use one of: %s.", g,
paste(.api_links_groups, collapse = ", ")))
}
per_page <- .api_int(q$per_page, "per_page", 200L, max = 200L)
offset <- .api_offset(q, per_page)
order <- if (!is.null(q$sort)) {
vapply(.api_parse_sort(q$sort), function(s) {
if (!s$column_id %in% c("key", "count") || !tolower(s$direction) %in% c("asc", "desc")) {
.api_abort("Groups sort by `key` or `count`, `asc` or `desc`.")
}
paste(if (s$column_id == "key") "k" else "n", toupper(s$direction))
}, "")
} else {
"n DESC"
}
rows <- DBI::dbGetQuery(con, paste0(
"SELECT coalesce(CAST(", g, " AS VARCHAR), 'unknown') AS k, count(*) AS n FROM links ",
"WHERE ", where, " GROUP BY ALL ORDER BY ", paste(c(order, "k ASC"), collapse = ", "),
" LIMIT ", per_page, " OFFSET ", offset
))
n_groups <- DBI::dbGetQuery(con, paste0(
"SELECT count(DISTINCT coalesce(CAST(", g, " AS VARCHAR), 'unknown')) AS n FROM links ",
"WHERE ", where
))$n
groups <- data.frame(key = rows$k, key_display_name = sub("^.*/", "", rows$k),
count = as.integer(rows$n))
meta <- list(count = count, db_response_time_ms = ms(),
page = if (is.null(q$cursor)) offset %/% per_page + 1L, per_page = per_page,
next_cursor = if (!is.null(q$cursor) && offset + per_page < n_groups)
jsonlite::base64_enc(as.character(offset + per_page)),
groups_count = nrow(groups))
return(paste0('{"meta":', .api_json(meta), ',"group_by":',
if (nrow(groups)) .api_json(groups, na = "null") else "[]", '}'))
}

per_page <- .api_int(q$per_page, "per_page", 25L, max = 200L)
offset <- .api_offset(q, per_page)
order <- if (!is.null(q$sort)) {
vapply(.api_parse_sort(q$sort), function(s) {
if (!s$column_id %in% .api_links_filters || !tolower(s$direction) %in% c("asc", "desc")) {
.api_abort(sprintf("/links sorts by %s, `asc` or `desc`.",
paste(.api_links_filters, collapse = ", ")))
}
paste(DBI::dbQuoteIdentifier(con, s$column_id), toupper(s$direction), "NULLS LAST")
}, "")
}
order <- c(order, "origin", "target", "link_type", "relation") # stable paging
cols <- DBI::dbQuoteIdentifier(con, .api_select(q$select, ctx$links_served))
rows <- DBI::dbGetQuery(con, paste0(
"SELECT to_json(struct_pack(", paste0(cols, " := ", cols, collapse = ", "), "))::VARCHAR AS j ",
"FROM links WHERE ", where, " ORDER BY ", paste(order, collapse = ", "),
" LIMIT ", per_page, " OFFSET ", offset
))$j
meta <- list(count = count, db_response_time_ms = ms(),
page = if (is.null(q$cursor)) offset %/% per_page + 1L, per_page = per_page,
next_cursor = if (!is.null(q$cursor) && offset + per_page < count)
jsonlite::base64_enc(as.character(offset + per_page)),
groups_count = NULL)
paste0('{"meta":', .api_json(meta), ',"results":[', paste(rows, collapse = ","), ']}')
}
14 changes: 14 additions & 0 deletions R/routes.R
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@
#' * `GET /works/{id}` (any ID form, or a DOI)
#' * `GET /?oql=...` and `GET /?oqo=...`, `POST /` with `oqo` or `oql` and the
#' view parameters `select`, `sort`, `per_page`, `page`, `cursor`
#' * `GET /links?filter=...`: the corpus's link table (`links/` next to
#' `corpus`), shaped like OpenAlex's `/links`. Filters `origin`, `target`
#' (any ID form, or a DOI), `link_type` (`part` or the full URL),
#' `relation`, `origin_in_corpus`, `target_in_corpus`; `|` for any of
#' several values, `!` to negate, `null` for missing. Unlike OpenAlex, no
#' work needs to be named, and `group_by` takes `link_type`, `relation` or
#' the `*_in_corpus` flags. Records are returned as stored, with all their
#' columns (e.g. `relation`, which OpenAlex does not return)
#' * `POST /query`: forwarded to OpenAlex (translation)
#' * `GET /corpus`: what is served (filters, group_by columns) and the
#' partition keys of the corpus folders with the number of works per value
Expand Down Expand Up @@ -80,6 +88,8 @@ serve_corpus <- function(
columns <- DBI::dbGetQuery(con, "DESCRIBE works")$column_name
ctx <- list(
con = con, db = db, columns = columns, served = .api_served_columns(con),
links_served = grep("^oaapi_", DBI::dbGetQuery(con, "DESCRIBE links")$column_name,
value = TRUE, invert = TRUE),
root = root, api_key = api_key,
corpus = DBI::dbGetQuery(con, "SELECT corpus FROM oaapi_meta")$corpus
)
Expand Down Expand Up @@ -160,13 +170,17 @@ serve_corpus <- function(
id <- utils::URLdecode(sub("^/works/", "", request$path))
json_ok(response, .api_single(ctx, id, query_of(request)$select))
}), serializers = raw) |>
plumber2::api_get("/links", guard(function(request, response, ...) {
json_ok(response, .api_links(ctx, query_of(request)))
}), serializers = raw) |>
plumber2::api_get("/corpus", guard(function(request, response, ...) {
reg <- .api_registry_works()
ok <- vapply(reg, function(e) all(e$need %in% ctx$columns), TRUE)
json_ok(response, .api_json(list(
corpus = ctx$corpus,
works = DBI::dbGetQuery(ctx$con, "SELECT count(*) AS n FROM works")$n,
columns = ctx$served,
links = DBI::dbGetQuery(ctx$con, "SELECT count(*) AS n FROM links")$n,
partitions = .api_partitions(ctx$con),
filters = sort(names(reg)[ok]),
filters_unavailable = sort(names(reg)[!ok]),
Expand Down
19 changes: 19 additions & 0 deletions R/utils_duckdb.R
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@
"lower(regexp_replace(CAST(x AS VARCHAR),",
"'^(https?://(dx\\.)?doi\\.org/|doi:)', '', 'i'))"
))
# a link end (K4): a DOI, an OpenAlex or bare ID, or anything else as is
DBI::dbExecute(con, paste(
"CREATE OR REPLACE TEMP MACRO link_key(x) AS CASE",
"WHEN regexp_matches(CAST(x AS VARCHAR), '^(https?://(dx\\.)?doi\\.org/|doi:|10\\.)', 'i')",
"THEN 'doi:' || doi_key(x)",
"WHEN regexp_matches(CAST(x AS VARCHAR), '^https?://openalex\\.org/', 'i')",
" OR NOT regexp_matches(CAST(x AS VARCHAR), '[:/]') THEN id_key(x)",
"ELSE CAST(x AS VARCHAR) END"
))
invisible(con)
}

Expand All @@ -90,3 +99,13 @@
ignore.case = TRUE
))
}

#' @keywords internal
#' @noRd
.api_link_key <- function(x) {
x <- as.character(x)
ifelse(grepl("^(https?://(dx\\.)?doi\\.org/|doi:|10\\.)", x, ignore.case = TRUE),
paste0("doi:", .api_doi_key(x)),
ifelse(grepl("^https?://openalex\\.org/", x, ignore.case = TRUE) | !grepl("[:/]", x),
.api_id_key(x), x))
}
Loading
Loading