Skip to contents

Introduction

A project corpus downloaded with openalexPro (or extracted from the OpenAlex snapshot) is a folder of Parquet files. You could query it with SQL, but you already know how to ask OpenAlex for what you want: filters, search, OQL, group_by. openalexAPI lets you ask your local corpus the same questions, in the same languages, and get the same kind of answers.

serve_corpus() starts a local web server that behaves like https://api.openalex.org for the works in your corpus:

  • the query languages are exactly OpenAlex’s. Classic URLs and OQL are translated by OpenAlex’s own (free) /query endpoint into an OQO, which is then run locally;
  • the responses have OpenAlex’s shape, so openalexPro downloads from the local server as from OpenAlex. You can filter a large corpus into a smaller one, or group it, without spending credits;
  • a web page runs the queries in the browser.

Preparing a corpus

library(openalexAPI)
db <- prepare_corpus("my_project/parquet")

prepare_corpus() reads every Parquet file below the folder into one DuckDB database and caches it under tools::R_user_dir("openalexAPI", "cache"). It is rebuilt only when the files change (paths, sizes, modification times) or a new version of openalexAPI changes the layout. serve_corpus() calls it, so you rarely need it yourself, except to build the database ahead of time for a large corpus.

What it accepts and does:

  • Any works corpus. That includes the output of openalexPro::pro_request_parquet() / pro_fetch(), the older JSONL path (which keeps abstract but not abstract_inverted_index), snapshot extractions, and other sources with the OpenAlex works schema.
  • Only files that hold works (an id and a title or display_name). Other tables in the folder, such as openalexSnowball edges or the members/ of a collection, are skipped with a message.
  • One record per work. Works repeated across query= partitions are served once, and hive partition columns are not read.
  • IDs and DOIs in any form. https://openalex.org/W123, W123, w123 and other prefixes (ABC123) all match each other; so do https://doi.org/10.…, doi:10.… and 10.….
  • Abstracts. The abstract text is indexed for search. abstract_inverted_index is served as in OpenAlex, and rebuilt from abstract for corpora that only have the text.
  • Mixed types. A column whose type differs between files (a number in one download, text in another) is reported. The columns that filters compare as numbers, dates or booleans are converted back, with a count of values that could not be read.
  • Extra columns that are not OpenAlex fields are served as they are, and can be selected, but not filtered on.

Serving

serve_corpus("my_project/parquet", port = 8000)

The server blocks the R session. Run it in a terminal (Rscript -e 'openalexAPI::serve_corpus("my_project/parquet")') or in a background process to keep working in R:

srv <- callr::r_bg(function() openalexAPI::serve_corpus("my_project/parquet", port = 8000))
# ... later
srv$kill()

By default the server listens on 127.0.0.1, so it is reachable only from your computer. Another host makes the corpus available on the network, and you get a warning. Requests are handled one at a time.

Classic URLs and OQL need the network for translation: OpenAlex’s /query is free and costs no credits. A query sent as an OQO runs fully offline.

Running on a server

The same process serves the API and the web page, so a server needs only R, openalexAPI and the corpus on a local disk:

serve_corpus("/data/corpus", host = "0.0.0.0", port = 8000,
             cache_dir = "/data/cache")
  • Network: the server needs outbound access to api.openalex.org to translate classic URLs and OQL.
  • First start: it builds the database cache, which takes minutes for a large corpus. To avoid this, build it beforehand with prepare_corpus() (on the server or elsewhere, then copy cache_dir).
  • Keeping it running: use a systemd service or a container that restarts the process after a crash or reboot.
  • Login and HTTPS: the server has neither, so anyone who reaches the port can query the corpus. Put a reverse proxy in front. The database is opened read-only, so users cannot change it.
  • One request at a time: a heavy query (a search with many terms on a large corpus) holds up everyone else while it runs. That is fine for a group, not for public traffic.
  • Its own host name or port: the page loads /corpus and /assets/… from the root of its host. It works at openalex.example.org or example.org:8000, not under a sub-path such as example.org/openalex/. For the same reason the page cannot be hosted on another server than the API.
  • api_key: a key passed to serve_corpus() is used for translation requests from users who send none.

A Caddy configuration with automatic HTTPS and a password (create the hash with caddy hash-password):

openalex.example.org {
    basic_auth {
        team <password hash>
    }
    reverse_proxy 127.0.0.1:8000
}

With a proxy on the same machine, keep the default host = "127.0.0.1", so the corpus is reachable only through the proxy. openalexPro clients then use endpoint = "https://openalex.example.org". openalexPro sends no password, so if scripts should reach the server too, restrict it by network (a VPN or Caddy’s remote_ip matcher) instead of a password.

With Docker

Each release is published as a Docker image for x86 and ARM servers, ghcr.io/openalexpro/openalexapi (tags latest and the version, e.g. 0.1.2). The image holds R, openalexAPI and DuckDB’s extensions.

The corpus is not part of the image. It is mounted read-only at /corpus, and the database goes into a volume at /cache, so it survives restarts and image updates. The image (about 3 GB, 0.8 GB to download) is the same for every corpus. To update the corpus, replace its Parquet files and restart. The database is rebuilt because its cache key includes the files’ sizes and modification times.

Server with HTTPS. The server needs Docker, ports 80 and 443 open, and a DNS name pointing at it. Copy the corpus to it (e.g. with rsync -av my_corpus/ server:/data/my_corpus/). On the server, download the two configuration files into a folder and start:

mkdir openalexapi && cd openalexapi
curl -fsSLO https://raw.githubusercontent.com/openalexPro/openalexAPI/main/docker/compose.yaml
curl -fsSLO https://raw.githubusercontent.com/openalexPro/openalexAPI/main/docker/Caddyfile
export OAAPI_CORPUS_DIR=/data/my_corpus   # folder with the Parquet files
export OAAPI_DOMAIN=openalex.example.org  # Caddy gets a certificate for it
docker compose run --rm openalexapi prepare   # build the database once
docker compose up -d
  • compose.yaml runs two containers: openalexAPI, reachable only from the server itself, and Caddy, the web server that faces the internet. Caddy gets and renews a free HTTPS certificate (Let’s Encrypt) for OAAPI_DOMAIN and passes the requests on to openalexAPI.
  • Caddyfile is Caddy’s configuration: the domain and where to pass requests to. For a password, uncomment its basic_auth block.
  • prepare builds the database before the server starts. Without it, the first start builds it, and the server answers only once that is done.
  • Without OAAPI_DOMAIN, Caddy serves https://localhost with its own certificate, for trying it out.
  • To update openalexAPI: docker compose pull && docker compose up -d. A version is pinned with OAAPI_IMAGE=ghcr.io/openalexpro/openalexapi:0.1.2.

Only the API container, for example behind a proxy you already have:

docker run -d --restart unless-stopped -p 127.0.0.1:8000:8000 \
  -v /data/my_corpus:/corpus:ro -v oaapi-cache:/cache \
  ghcr.io/openalexpro/openalexapi

Settings are environment variables (-e): OPENALEX_API_KEY (see api_key above), OAAPI_PORT (default 8000).

Building the image yourself from a clone of the repository (for the development version, or changes of your own):

git clone https://github.com/openalexPro/openalexAPI && cd openalexAPI
docker compose -f docker/compose.yaml -f docker/compose.build.yaml up -d --build

Memory. Give the container the memory the corpus needs (see the README’s section “Corpus size and memory”). DuckDB respects a Docker memory limit (--memory, or mem_limit in Compose) and uses 80 % of it. A database larger than that is read from disk and queries get slow. Keep the oaapi-cache volume on a fast local disk: a network drive slows every query.

A corpus inside the image. For a small corpus that is shipped as one file (to a place without the Parquet files), build an image on top that contains the corpus and its database:

FROM ghcr.io/openalexpro/openalexapi:0.1.2
COPY --chown=oaapi my_corpus/ /corpus/
RUN Rscript /usr/local/bin/oaapi-serve.R prepare

Run it without the volumes. The image is then about the size of the database plus 3 GB, and changes to the corpus need a new image, so keep this for corpora that do not change.

Asking questions

Classic URLs

The /works endpoint takes OpenAlex’s parameters:

/works?filter=type:article,publication_year:>2015
/works?filter=authorships.countries:ch|de,type:!dataset&sort=cited_by_count:desc
/works?search=coral bleaching&filter=open_access.is_oa:true
/works?filter=primary_topic.id:null              (works without a primary topic)
/works?filter=type:article&group_by=publication_year
/works?select=id,display_name,doi&per_page=200&cursor=*
/works/W2741809807                               (or a DOI: /works/10.7717/peerj.4375)

The filter names are OpenAlex’s, aliases included (is_oa, cites, author.id, institutions.country_code, title.search, …): OpenAlex translates them.

OQL and OQO

OQL and OQO queries go to the root, as on OpenAlex:

/?oql=works where type is article and year >= 2015
/?oql=get the count of all works by country
library(httr2)
oqo <- list(
  get_rows = "works",
  filter_rows = list(
    list(column_id = "type", value = "article"),
    list(join = "or", filters = list(
      list(column_id = "authorships.countries", value = "CH"),
      list(column_id = "authorships.countries", value = "DE")
    ))
  ),
  sort_by = list(list(column_id = "cited_by_count", direction = "desc"))
)
res <- request("http://127.0.0.1:8000") |>
  req_body_json(list(oqo = oqo, per_page = 10, select = "id,display_name")) |>
  req_perform() |>
  resp_body_json()
res$meta$count

Each response carries the query that ran in meta.x_query: the OQL text (for translated queries) and the OQO.

Responses

Responses have the OpenAlex shape:

  • records: {"meta": {count, page, per_page, next_cursor, …}, "results": […]};
  • groups: {"meta": {count, groups_count, …}, "group_by": [{key, key_display_name, count}]};
  • a single work: the record itself.

Paging works with page or cursor, at up to 200 per page. A sample (with or without seed) is the same on every page.

Errors are HTTP 400 with OpenAlex’s own validation message for queries it cannot translate. For queries the local corpus cannot answer, they are {"error", "message"}, for example a filter that is not supported here. OpenAlex’s /query being unreachable is a 503.

Downloading with openalexPro

Point openalexPro at the local server with endpoint. Everything else works as it does with OpenAlex: paging, via = "url" or via = "oqo", grouped results, search, conversion to Parquet.

library(openalexPro)
ep <- "http://127.0.0.1:8000"

# a subset of the corpus, as a new Parquet corpus
pro_fetch(
  pro_query(entity = "works", type = "article", publication_year = ">2015",
            search = "coral bleaching", endpoint = ep),
  project_folder = "subset"
)

# counts per country
pro_fetch(
  pro_query(entity = "works", group_by = "authorships.countries", endpoint = ep),
  project_folder = "by_country"
)

The web page’s Copy API URL button gives the URL of the query shown, ready for pro_fetch().

Filters

/corpus lists what the served corpus supports. These filters are available (as OQO column names; classic URLs may use OpenAlex’s aliases):

Area Filters
work type, publication_year, publication_date, from_publication_date, to_publication_date, from_created_date, to_created_date, language, is_retracted, is_paratext, has_doi, has_abstract, has_references
open access open_access.is_oa, open_access.oa_status, open_access.any_repository_has_fulltext, best_oa_location.license
counts cited_by_count, fwci, authors_count, citation_normalized_percentile.value, citation_normalized_percentile.is_in_top_1_percent, citation_normalized_percentile.is_in_top_10_percent
people and places authorships.author.id, authorships.author.orcid, authorships.institutions.id, authorships.institutions.lineage, authorships.institutions.country_code, authorships.institutions.type, authorships.countries, funders.id
source and topics primary_location.source.id, primary_location.source.type, primary_location.source.issn, primary_location.source.publisher_lineage (= host_organization_lineage), primary_topic.id, primary_topic.subfield.id, primary_topic.field.id, primary_topic.domain.id, topics.id, keywords.id, sustainable_development_goals.id
identifiers and citations ids.openalex, ids.pmid, ids.pmcid, doi, referenced_works (cites:), cited_by

The query structure is the same as in OpenAlex:

  • all filters combine with AND;
  • a|b gives OR, and !a negates;
  • >, < and 2000-2010 give ranges;
  • null matches works where the field is missing.

A negated filter also matches works without the field, as in OpenAlex. cites and cited_by work within the corpus: cited_by:W1 lists the works of the corpus that W1 cites. authorships.institutions.lineage matches an institution and every institution below it (a university finds its faculties).

group_by

One group_by dimension per query is supported, on the columns /corpus lists under group_by. Dates, fwci, doi and cited_by cannot be grouped by, as in OpenAlex.

  • Counting: each work counts once per key. List columns (countries, authors, topics, …) are unpacked first. Filters and search apply before grouping.
  • Keys: as in OpenAlex. That means https://openalex.org/types/article, https://openalex.org/countries/CH, entity IDs, and plain years, counts and true/false. An ID stored in several forms is one group.
  • Sorting: by count (largest first), or with sort=key:asc (numeric keys sort as numbers), count:asc or count:desc.
  • Missing values: group_by=column:include_unknown adds the works without a value as the group unknown.
  • Display names for countries, languages and licenses are their codes (“CH”), where OpenAlex shows the full name (“Switzerland”): the corpus has no names for them.

There is no full text locally. The searches run over title and abstract:

Parameter or filter Searches
search=, fulltext.search, default.search title and abstract
filter=title_and_abstract.search: title and abstract
filter=title.search: (display_name.search) title
filter=abstract.search: abstract
search.exact= and the .search.exact filters the same, without stemming or stop words
filter=raw_affiliation_strings.search: the authors’ affiliation strings
filter=raw_author_name.search: the authors’ names as printed

The search rules follow OpenAlex:

  • Words: all words must match. coral bleaching finds works with both.
  • Phrases: "coral bleaching" must appear in this order.
  • Boolean operators: AND, OR and NOT work between terms.
  • Proximity: "coral"~3~"bleaching" finds the terms with up to 3 words between them, in either order. The classic "coral bleaching"~3 keeps the order.
  • Wildcards: bleach* works with the exact search only.
  • Relevance: results are ranked by relevance_score (BM25), which each record carries. It is the default sort when searching, and sort=relevance_score:desc|asc works too.

The differences from OpenAlex:

  • the stemmer (Porter) folds more word forms than OpenAlex’s, so stemmed counts can be higher; exact searches are closer;
  • proximity is “up to N words between the terms” (N up to 1000), an approximation of OpenAlex’s slop; in a chain ("a"~3~"b"~2~"c") each pair has its distance;
  • in the stemmed searches, phrases and proximity match word stems ("coral reefs" also finds “coral reef”);
  • affiliation and author-name searches match whole words, without stemming, and add nothing to relevance_score. As in OpenAlex, unquoted words may come from different affiliations of a work, a quoted phrase must be within one;
  • searches of fields the corpus does not index (e.g. affiliation strings) are a 400.

The web page

http://127.0.0.1:8000/ opens a page with two modes:

  • Search & filters: a search box (with an “exact” switch), a filter string in OpenAlex syntax, and a clickable list of the supported filters.
  • OQL: a box for an OQL query.

Records show title, authors, year, type, citations and relevance, with paging. Grouped results show as bars, and clicking a bar narrows the filters to that group. The page also shows the translated OQL, OpenAlex’s error messages, and the Copy API URL button. It works in light and dark mode and at phone width.

Using the compiler directly

oqo_to_sql() shows the SQL a query becomes:

con <- DBI::dbConnect(duckdb::duckdb())
s <- oqo_to_sql(list(get_rows = "works", filter_rows = list(
  list(column_id = "type", value = "article"),
  list(column_id = "fulltext.search", value = "coral bleaching", operator = "has")
)), con)
s$prelude # run first: each search term's matches, as a temp table
s$where   # the condition on the `works` table
s$score   # the relevance score

The connection is used to quote values and to stem words. The SQL refers to the database prepare_corpus() builds, its helper columns, and the id_key() / doi_key() macros and full-text indexes that serve_corpus() loads, and a search’s where refers to the temp tables its prelude creates. Use it to see what a query does; to run queries, use the server.