diff --git a/CLAUDE.md b/CLAUDE.md index e5e6352..b7bd128 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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/`) | @@ -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:`, 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` @@ -150,9 +156,9 @@ delete `README.html`. ## Branching - `claude/` 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, ...). diff --git a/DESCRIPTION b/DESCRIPTION index 921c720..941bfb6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -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")) diff --git a/NEWS.md b/NEWS.md index fe6008a..072b2af 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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/`, diff --git a/R/corpus.R b/R/corpus.R index ec59874..e0801e8 100644 --- a/R/corpus.R +++ b/R/corpus.R @@ -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. @@ -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")) @@ -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())" @@ -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 @@ -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 diff --git a/R/links.R b/R/links.R new file mode 100644 index 0000000..b510b52 --- /dev/null +++ b/R/links.R @@ -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 = ","), ']}') +} diff --git a/R/routes.R b/R/routes.R index 6945ddf..94c6933 100644 --- a/R/routes.R +++ b/R/routes.R @@ -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 @@ -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 ) @@ -160,6 +170,9 @@ 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) @@ -167,6 +180,7 @@ serve_corpus <- function( 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]), diff --git a/R/utils_duckdb.R b/R/utils_duckdb.R index 36a706d..518505c 100644 --- a/R/utils_duckdb.R +++ b/R/utils_duckdb.R @@ -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) } @@ -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)) +} diff --git a/README.Rmd b/README.Rmd index 886310b..53bf57b 100644 --- a/README.Rmd +++ b/README.Rmd @@ -15,7 +15,8 @@ knitr::opts_chunk$set( # openalexAPI -[![Status: alpha](https://img.shields.io/badge/status-alpha-red.svg)](https://github.com/openalexPro/openalexAPI) +[![r-universe](https://openalexpro.r-universe.dev/badges/openalexAPI)](https://openalexpro.r-universe.dev/openalexAPI) +[![Status: beta](https://img.shields.io/badge/status-beta-orange.svg)](https://github.com/openalexPro/openalexAPI) [![main](https://img.shields.io/github/r-package/v/openalexPro/openalexAPI/main?label=main)](https://github.com/openalexPro/openalexAPI/tree/main) [![CI main](https://img.shields.io/github/actions/workflow/status/openalexPro/openalexAPI/R-CMD-check.yaml?branch=main&label=CI%20main)](https://github.com/openalexPro/openalexAPI/actions/workflows/R-CMD-check.yaml?query=branch%3Amain) [![dev](https://img.shields.io/github/r-package/v/openalexPro/openalexAPI/dev?label=dev)](https://github.com/openalexPro/openalexAPI/tree/dev) @@ -25,9 +26,9 @@ knitr::opts_chunk$set( [![Docs](https://img.shields.io/badge/docs-pkgdown-blue)](https://openalexpro.github.io/openalexAPI/) -> **Alpha.** openalexAPI works and is tested, but its functions, arguments and -> the details of its responses may still change between versions. It is not on -> the openalexPro r-universe yet; install it from GitHub. +> **Beta.** openalexAPI works and is tested, and its functions and routes +> are settled; details of arguments and responses may still change between +> versions. **openalexAPI** serves a local Parquet corpus of OpenAlex works through a web API that answers like the [OpenAlex API](https://api.openalex.org). You can run @@ -50,21 +51,21 @@ It is meant for **project-sized corpora**, not the whole snapshot. ## Installation -openalexAPI is not on the openalexPro r-universe yet. Install it from GitHub; -its dependencies come along. openalexPro, to download from the server in R, is -installed separately (`pak::pak("openalexPro/openalexPro")`): +From the openalexPro r-universe, with its dependencies. openalexPro, to +download from the server in R, is installed the same way: ```{r} -# install.packages("pak") -pak::pak("openalexPro/openalexAPI") # main: the current alpha version -pak::pak("openalexPro/openalexAPI@dev") # dev: the newest changes +install.packages( + "openalexAPI", + repos = c("https://openalexpro.r-universe.dev", "https://cloud.r-project.org") +) ``` -Or with remotes: +The development version from GitHub: ```{r} -# install.packages("remotes") -remotes::install_github("openalexPro/openalexAPI") +# install.packages("pak") +pak::pak("openalexPro/openalexAPI@dev") ``` ## Quick start @@ -127,6 +128,10 @@ compiles the OQO into SQL. An OQO sent directly runs without network access. appear in order, proximity (`"a"~N~"b"`, `"a b"~N`) works, and wildcards work with `.exact`. Results are ranked by `relevance_score` (BM25). +- **`/links`** serves the corpus's link table (`links/` next to the corpus), + shaped like OpenAlex's `/links`, with all link types and relations the + source wrote (e.g. every related identifier of a Zenodo corpus), filters + on `origin`, `target`, `link_type`, `relation`, and `group_by`. - **Records** are returned as stored, including fields that are not OpenAlex's. You can use `select`, `sort`, `per_page`, `page`, `cursor` and `sample`/`seed`, and look up single works by ID or DOI. @@ -138,6 +143,9 @@ compiles the OQO into SQL. An OQO sent directly runs without network access. The stemmer folds more word forms than OpenAlex's, so stemmed counts can be higher. Proximity allows up to N words between the terms, an approximation of OpenAlex's. +- **Links** are those of the corpus's link table. A corpus from openalexPro + has none (its citations are in `referenced_works`), so `/links` is empty + there. - **Display names:** countries, languages and licenses use the code as the display name in `group_by` results ("AU" rather than "Australia"). - **Unsupported features** get a clear HTTP 400 that names them: OpenAlex diff --git a/README.md b/README.md index ef085ad..07628fb 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,9 @@ +[![r-universe](https://openalexpro.r-universe.dev/badges/openalexAPI)](https://openalexpro.r-universe.dev/openalexAPI) [![Status: -alpha](https://img.shields.io/badge/status-alpha-red.svg)](https://github.com/openalexPro/openalexAPI) +beta](https://img.shields.io/badge/status-beta-orange.svg)](https://github.com/openalexPro/openalexAPI) [![main](https://img.shields.io/github/r-package/v/openalexPro/openalexAPI/main?label=main)](https://github.com/openalexPro/openalexAPI/tree/main) [![CI main](https://img.shields.io/github/actions/workflow/status/openalexPro/openalexAPI/R-CMD-check.yaml?branch=main&label=CI%20main)](https://github.com/openalexPro/openalexAPI/actions/workflows/R-CMD-check.yaml?query=branch%3Amain) @@ -19,10 +20,9 @@ MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.or [![Docs](https://img.shields.io/badge/docs-pkgdown-blue)](https://openalexpro.github.io/openalexAPI/) -> **Alpha.** openalexAPI works and is tested, but its functions, -> arguments and the details of its responses may still change between -> versions. It is not on the openalexPro r-universe yet; install it from -> GitHub. +> **Beta.** openalexAPI works and is tested, and its functions and +> routes are settled; details of arguments and responses may still +> change between versions. **openalexAPI** serves a local Parquet corpus of OpenAlex works through a web API that answers like the [OpenAlex @@ -46,22 +46,21 @@ It is meant for **project-sized corpora**, not the whole snapshot. ## Installation -openalexAPI is not on the openalexPro r-universe yet. Install it from -GitHub; its dependencies come along. openalexPro, to download from the -server in R, is installed separately -(`pak::pak("openalexPro/openalexPro")`): +From the openalexPro r-universe, with its dependencies. openalexPro, to +download from the server in R, is installed the same way: ``` r -# install.packages("pak") -pak::pak("openalexPro/openalexAPI") # main: the current alpha version -pak::pak("openalexPro/openalexAPI@dev") # dev: the newest changes +install.packages( + "openalexAPI", + repos = c("https://openalexpro.r-universe.dev", "https://cloud.r-project.org") +) ``` -Or with remotes: +The development version from GitHub: ``` r -# install.packages("remotes") -remotes::install_github("openalexPro/openalexAPI") +# install.packages("pak") +pak::pak("openalexPro/openalexAPI@dev") ``` ## Quick start @@ -121,6 +120,11 @@ without network access. phrases must appear in order, proximity (`"a"~N~"b"`, `"a b"~N`) works, and wildcards work with `.exact`. Results are ranked by `relevance_score` (BM25). +- **`/links`** serves the corpus’s link table (`links/` next to the + corpus), shaped like OpenAlex’s `/links`, with all link types and + relations the source wrote (e.g. every related identifier of a Zenodo + corpus), filters on `origin`, `target`, `link_type`, `relation`, and + `group_by`. - **Records** are returned as stored, including fields that are not OpenAlex’s. You can use `select`, `sort`, `per_page`, `page`, `cursor` and `sample`/`seed`, and look up single works by ID or DOI. @@ -132,6 +136,9 @@ without network access. text. The stemmer folds more word forms than OpenAlex’s, so stemmed counts can be higher. Proximity allows up to N words between the terms, an approximation of OpenAlex’s. +- **Links** are those of the corpus’s link table. A corpus from + openalexPro has none (its citations are in `referenced_works`), so + `/links` is empty there. - **Display names:** countries, languages and licenses use the code as the display name in `group_by` results (“AU” rather than “Australia”). - **Unsupported features** get a clear HTTP 400 that names them: diff --git a/man/prepare_corpus.Rd b/man/prepare_corpus.Rd index d885136..7a0d823 100644 --- a/man/prepare_corpus.Rd +++ b/man/prepare_corpus.Rd @@ -39,4 +39,8 @@ The corpus can come from \code{openalexPro::pro_request_parquet()} (keeps \code{abstract_inverted_index} and adds \code{abstract}), from the JSONL path (only \code{abstract}), from a snapshot extraction, or from any source with the OpenAlex works schema. + +The link table of the ecosystem standard, \verb{links/} next to \code{corpus} (all +\verb{*.parquet} below it), is read into a second table and served by \verb{/links}. +Without it, \verb{/links} has no rows. } diff --git a/man/serve_corpus.Rd b/man/serve_corpus.Rd index 2df0174..3de2a83 100644 --- a/man/serve_corpus.Rd +++ b/man/serve_corpus.Rd @@ -46,6 +46,14 @@ value as the group \code{unknown}) \item \code{GET /works/{id}} (any ID form, or a DOI) \item \code{GET /?oql=...} and \code{GET /?oqo=...}, \verb{POST /} with \code{oqo} or \code{oql} and the view parameters \code{select}, \code{sort}, \code{per_page}, \code{page}, \code{cursor} +\item \code{GET /links?filter=...}: the corpus's link table (\verb{links/} next to +\code{corpus}), shaped like OpenAlex's \verb{/links}. Filters \code{origin}, \code{target} +(any ID form, or a DOI), \code{link_type} (\code{part} or the full URL), +\code{relation}, \code{origin_in_corpus}, \code{target_in_corpus}; \code{|} for any of +several values, \code{!} to negate, \code{null} for missing. Unlike OpenAlex, no +work needs to be named, and \code{group_by} takes \code{link_type}, \code{relation} or +the \verb{*_in_corpus} flags. Records are returned as stored, with all their +columns (e.g. \code{relation}, which OpenAlex does not return) \item \code{POST /query}: forwarded to OpenAlex (translation) \item \code{GET /corpus}: what is served (filters, group_by columns) and the partition keys of the corpus folders with the number of works per value diff --git a/tests/testthat/test-links.R b/tests/testthat/test-links.R new file mode 100644 index 0000000..75f4696 --- /dev/null +++ b/tests/testthat/test-links.R @@ -0,0 +1,138 @@ +# A project folder: corpus_jq as parquet/ and a link table next to it, with +# OpenAlex-typed links and Zenodo-style relations OpenAlex has no type for +local_links_project <- function(env = parent.frame()) { + dir <- withr::local_tempdir(.local_envir = env) + file.copy(fixture("corpus_jq"), dir, recursive = TRUE) + corpus <- file.path(dir, "parquet") + file.rename(file.path(dir, "corpus_jq"), corpus) + con <- openalexAPI:::.api_con() + on.exit(DBI::dbDisconnect(con, shutdown = TRUE)) + ids <- DBI::dbGetQuery(con, paste0( + "SELECT id FROM read_parquet('", corpus, "/**/*.parquet') ORDER BY id LIMIT 3" + ))$id + lt <- function(x) ifelse(is.na(x), NA, paste0("https://openalex.org/link-types/", x)) + links <- data.frame( + origin = c(ids[1], ids[2], ids[3], ids[1], "https://doi.org/10.5281/zenodo.1"), + target = c(ids[2], ids[3], "https://doi.org/10.1/X", "isbn:9780000000000", ids[1]), + link_type = lt(c("citation", "part", "part", NA, NA)), + relation = c(NA, "IsPartOf", "IsPartOf", "IsSupplementTo", "IsDocumentedBy"), + origin_in_corpus = c(TRUE, TRUE, TRUE, TRUE, FALSE), + target_in_corpus = c(TRUE, TRUE, FALSE, FALSE, TRUE), + zenodo_relation_declared = c(NA, "isPartOf", "isPartOf", "isSupplementTo", "documents") + ) + for (q in c("a", "b")) { # the same rows in two partitions: served once + d <- file.path(dir, "links", paste0("query=", q)) + dir.create(d, recursive = TRUE) + DBI::dbWriteTable(con, "l", links, overwrite = TRUE) + DBI::dbExecute(con, paste0("COPY l TO '", d, "/data.parquet' (FORMAT parquet)")) + } + list(corpus = corpus, ids = ids) +} + +local_links_ctx <- function(corpus, env = parent.frame()) { + db <- prepare_corpus(corpus, cache_dir = withr::local_tempdir(.local_envir = env)) + con <- openalexAPI:::.api_open(db) + withr::defer(DBI::dbDisconnect(con, shutdown = TRUE), envir = env) + served <- DBI::dbGetQuery(con, "DESCRIBE links")$column_name + list(con = con, links_served = served[!startsWith(served, "oaapi_")]) +} + +links_get <- function(ctx, ...) { + jsonlite::fromJSON(openalexAPI:::.api_links(ctx, list(...)), simplifyVector = FALSE) +} + +test_that("the link table next to the corpus is served, filtered and grouped", { + p <- local_links_project() + ctx <- local_links_ctx(p$corpus) + ids <- p$ids + + all <- links_get(ctx) + expect_equal(all$meta$count, 5) + expect_named(all$results[[1]], c("origin", "target", "link_type", "relation", + "origin_in_corpus", "target_in_corpus", + "zenodo_relation_declared")) + + # any ID form; a short link type + bare <- sub("^.*/", "", ids[2]) + expect_equal(links_get(ctx, filter = paste0("target:", bare))$meta$count, 1) + r <- links_get(ctx, filter = paste0("origin:", tolower(bare), ",link_type:part")) + expect_equal(r$meta$count, 1) + expect_equal(r$results[[1]]$target, ids[3]) + expect_equal(links_get(ctx, filter = "link_type:https://openalex.org/link-types/part")$meta$count, 2) + + # DOIs in any form, other schemes as stored + expect_equal(links_get(ctx, filter = "target:10.1/x")$meta$count, 1) + expect_equal(links_get(ctx, filter = "origin:doi:10.5281/ZENODO.1")$meta$count, 1) + expect_equal(links_get(ctx, filter = "target:isbn:9780000000000")$meta$count, 1) + + # relations OpenAlex has no type for; null, OR, negation (NULL-safe) + expect_equal(links_get(ctx, filter = "link_type:null")$meta$count, 2) + expect_equal(links_get(ctx, filter = "relation:issupplementto|IsDocumentedBy")$meta$count, 2) + expect_equal(links_get(ctx, filter = "relation:null")$meta$count, 1) + expect_equal(links_get(ctx, filter = "link_type:!part")$meta$count, 3) + expect_equal(links_get(ctx, filter = "target_in_corpus:false,origin_in_corpus:true")$meta$count, 2) + + # group_by, with missing values as `unknown` + g <- links_get(ctx, group_by = "link_type") + keys <- vapply(g$group_by, `[[`, "", "key") + counts <- vapply(g$group_by, `[[`, 0, "count") + expect_equal(stats::setNames(counts, keys), + c("https://openalex.org/link-types/part" = 2, unknown = 2, + "https://openalex.org/link-types/citation" = 1)) + expect_equal(g$group_by[[1]]$key_display_name, "part") + + # paging, select, sort + p1 <- links_get(ctx, per_page = "2", cursor = "*", select = "origin,target", sort = "target:desc") + expect_length(p1$results, 2) + expect_named(p1$results[[1]], c("origin", "target")) + p2 <- links_get(ctx, per_page = "2", cursor = p1$meta$next_cursor, select = "origin,target", + sort = "target:desc") + p3 <- links_get(ctx, per_page = "2", cursor = p2$meta$next_cursor, select = "origin,target", + sort = "target:desc") + expect_null(p3$meta$next_cursor) + targets <- vapply(c(p1$results, p2$results, p3$results), `[[`, "", "target") + expect_equal(targets, sort(targets, decreasing = TRUE, method = "radix")) +}) + +test_that("/links refuses what it does not know", { + p <- local_links_project() + ctx <- local_links_ctx(p$corpus) + expect_error(links_get(ctx, filter = "cites:W1"), "no filter `cites`") + expect_error(links_get(ctx, filter = "origin"), "key:value") + expect_error(links_get(ctx, filter = "origin_in_corpus:yes"), "true, false or null") + expect_error(links_get(ctx, group_by = "origin"), "cannot group by") + expect_error(links_get(ctx, search = "x"), "does not take `search`") + expect_error(links_get(ctx, sort = "zenodo_relation_declared"), "sorts by") +}) + +test_that("a corpus without a link table serves an empty one", { + ctx <- local_links_ctx(fixture("corpus_jq")) + r <- links_get(ctx) + expect_equal(r$meta$count, 0) + expect_length(r$results, 0) + expect_true(all(names(openalexAPI:::.api_links_columns) %in% ctx$links_served)) +}) + +test_that("link_key() in SQL and R agree", { + con <- openalexAPI:::.api_con() + on.exit(DBI::dbDisconnect(con, shutdown = TRUE)) + x <- c("https://openalex.org/W12", "w12", "https://doi.org/10.1/AB", "doi:10.1/ab", "10.1/Ab", + "isbn:978", "https://example.org/x", "zenodo:5") + sql <- DBI::dbGetQuery(con, paste0( + "SELECT link_key(x) AS k FROM (SELECT unnest(", openalexAPI:::.api_sql_list(con, x), + ") AS x, generate_subscripts(", openalexAPI:::.api_sql_list(con, x), ", 1) AS i) ORDER BY i" + ))$k + expect_equal(sql, openalexAPI:::.api_link_key(x)) + expect_equal(sql[1:5], c("W12", "W12", "doi:10.1/ab", "doi:10.1/ab", "doi:10.1/ab")) +}) + +test_that("GET /links and /corpus over HTTP", { + skip_on_cran() + p <- local_links_project() + url <- local_server(p$corpus) + r <- call_api(url, "/links?filter=link_type:part|null&group_by=relation") + expect_equal(r$status, 200) + expect_equal(r$json$meta$count, 4) + expect_equal(call_api(url, "/links?filter=nope:1")$status, 400) + expect_equal(call_api(url, "/corpus")$json$links, 5) +}) diff --git a/tests/testthat/test-server.R b/tests/testthat/test-server.R index 8d2d696..eede70b 100644 --- a/tests/testthat/test-server.R +++ b/tests/testthat/test-server.R @@ -114,7 +114,7 @@ test_that("openalexPro downloads from the server like from OpenAlex", { pages <- list.files(out, "^results_page_[0-9]+\\.parquet$", recursive = TRUE) expect_length(pages, ceiling(length(want) / 10)) got <- DBI::dbGetQuery(con, sprintf( - "SELECT id, abstract FROM read_parquet('%s/**/*.parquet')", out)) + "SELECT id, abstract FROM read_parquet('%s/parquet/**/*.parquet')", out)) expect_equal(sort(got$id), want, label = via) # openalexPro rebuilt the abstracts from the served inverted index expect_equal(sum(!is.na(got$abstract)), n_sql(con, sprintf( @@ -180,7 +180,7 @@ test_that("openalexPro downloads a sample spanning pages consistently", { verbose = FALSE) con <- DBI::dbConnect(duckdb::duckdb()) on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE) - DBI::dbGetQuery(con, sprintf("SELECT id FROM read_parquet('%s/**/*.parquet')", out))$id + DBI::dbGetQuery(con, sprintf("SELECT id FROM read_parquet('%s/parquet/**/*.parquet')", out))$id }) for (x in ids) { expect_length(x, 45) @@ -222,7 +222,7 @@ test_that("openalexPro downloads grouped results from the server", { out <- withr::local_tempdir() fetch(q, project_folder = out, via = via, progress = FALSE, verbose = FALSE) got <- DBI::dbGetQuery(con, sprintf( - "SELECT key, count FROM read_parquet('%s/**/*.parquet')", out)) + "SELECT key, count FROM read_parquet('%s/parquet/**/*.parquet')", out)) expect_setequal(got$key, want$key) expect_equal(got$count[match(want$key, got$key)], as.numeric(want$n), label = via) } @@ -239,7 +239,7 @@ test_that("openalexPro downloads grouped results from the server", { pages <- list.files(out, "^group_by_page_[0-9]+\\.parquet$", recursive = TRUE) expect_length(pages, ceiling(want / 5)) got <- DBI::dbGetQuery(con, sprintf( - "SELECT key FROM read_parquet('%s/**/*.parquet')", out))$key + "SELECT key FROM read_parquet('%s/parquet/**/*.parquet')", out))$key expect_length(got, want) expect_false(anyDuplicated(got) > 0) } @@ -283,7 +283,7 @@ test_that("openalexPro downloads search results from the server", { out <- withr::local_tempdir() fetch(q, project_folder = out, via = via, progress = FALSE, verbose = FALSE) got <- DBI::dbGetQuery(con, sprintf( - "SELECT id, relevance_score FROM read_parquet('%s/**/*.parquet')", out)) + "SELECT id, relevance_score FROM read_parquet('%s/parquet/**/*.parquet')", out)) expect_equal(sort(got$id), want, label = via) expect_true(all(!is.na(got$relevance_score)), label = via) } diff --git a/vignettes/openalexAPI.qmd b/vignettes/openalexAPI.qmd index fe8e42a..c6efb15 100644 --- a/vignettes/openalexAPI.qmd +++ b/vignettes/openalexAPI.qmd @@ -285,6 +285,43 @@ res$meta$count Each response carries the query that ran in `meta.x_query`: the OQL text (for translated queries) and the OQO. +## Links + +`/links` serves the corpus's link table (`links/` next to the corpus folder, +written by the corpus's source as the ecosystem standard asks), shaped like +OpenAlex's `/links`: one record per link, `origin` → `target`, with the +OpenAlex `link_type`. + +``` +/links?filter=target:W6931481510,link_type:part (what is part of the work) +/links?filter=origin:W6912726942 (what the work points to) +/links?filter=relation:IsSupplementTo|IsDocumentedBy +/links?filter=link_type:null (relations OpenAlex has no type for) +/links?group_by=relation +``` + +It serves everything the table holds, so it can give more than OpenAlex: + +- **all relations of the source:** a corpus from Zenodo + (openalexImportZenodo) has every related identifier Zenodo declares, + also those without an OpenAlex link type (`link_type` is then null; the + DataCite name is in `relation`); +- **all columns as stored:** `relation`, `origin_in_corpus`, + `target_in_corpus` and the source's own (e.g. `zenodo_relation_declared`); +- **no work has to be named**, and `group_by` takes `link_type`, `relation`, + `origin_in_corpus` or `target_in_corpus`. + +The filters are `origin` and `target` (any ID form, DOIs in any form, other +identifiers as stored, e.g. `isbn:978…`), `link_type` (`part` or the full +URL), `relation` (any case) and the two `*_in_corpus` flags; `|`, `!` and +`null` work as for works. OpenAlex's translator does not know `/links`, so +these are parsed locally. + +It can also give less: a corpus holds only the links its source wrote. A +corpus from openalexPro has an empty link table (its citations are in +`referenced_works`, which the `cites:` and `cited_by:` filters of `/works` +use), so `/links` answers with no records. + ## Responses Responses have the OpenAlex shape: