| Title: | Providing a more advanced access to OpenAlex for the power user |
|---|---|
| Description: | Retrieves large result sets from the 'OpenAlex' API (<https://openalex.org>) without holding them in memory. Queries are built and validated with classic filters and search, or written in 'OpenAlex' query language (OQL) or its JSON form (OQO). Results are downloaded page by page to JSON files, with cursor paging, parallel downloads, retries and resume, and converted per page with 'DuckDB' to a partitioned 'Apache Parquet' dataset that includes reconstructed abstracts and citation strings. Query results can be saved as 'OpenAlex' collections, shareable and reusable sets of IDs that are kept in sync with their queries. Full-text PDFs and TEI XML can be downloaded, and the daily API budget can be inspected. |
| Authors: | Rainer M Krug [aut, cre] (ORCID: <https://orcid.org/0000-0002-7490-0066>) |
| Maintainer: | Rainer M Krug <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.18.1 |
| Built: | 2026-11-20 08:30:04 UTC |
| Source: | https://github.com/openalexPro/openalexPro |
Renders the Quarto report at 'system.file("compatibility.qmd", package = "openalexPro") and opens the resulting HTML in your default browser.
compatibility_report( output_dir = "Compatibility Report", open = TRUE, quiet = FALSE )compatibility_report( output_dir = "Compatibility Report", open = TRUE, quiet = FALSE )
output_dir |
Directory to write the rendered HTML and the data into. Defaults to the flder './Compatibility Report'. |
open |
Logical; if 'TRUE' (default) opens the rendered HTML in the system browser. |
quiet |
Logical; suppress rendering output if 'TRUE'. Default: 'FALSE'. |
This report is designed to help you validate client-API compatibility in real time. During rendering, the report performs live requests against the OpenAlex API and compares the responses to the package's expected behavior. No cached data are used: every section issues fresh API calls so that the output reflects the current state of the upstream service. The report summarizes differences in fields, types, pagination and response shapes to surface potential regressions from upstream changes or local client updates.
Note: Because it depends on live API calls, rendering may take longer and requires network access. Be mindful of API rate limits when running the report repeatedly.
Invisibly returns the path to the rendered HTML file.
Extracts DOIs or specific DOI components (resolver, prefix, or suffix) from a character vector. Assumes that each element of 'x' contains at most one DOI (with or without resolver).
extract_doi( x, non_doi_value = "", normalize = TRUE, lower = TRUE, what = c("doi", "resolver", "prefix", "suffix") )extract_doi( x, non_doi_value = "", normalize = TRUE, lower = TRUE, what = c("doi", "resolver", "prefix", "suffix") )
x |
A character vector potentially containing DOIs (e.g., raw DOIs, DOI URLs, or strings with embedded DOIs). |
non_doi_value |
Value to use for elements where no DOI or component is found. If 'NULL', only matched elements are returned. |
normalize |
Logical. If 'TRUE' (default), convert extracted DOIs and suffixes to lowercase and trim surrounding whitespace. Has no effect for 'what = "prefix"' or 'what = "resolver"'. |
lower |
Logical. With 'normalize = TRUE', convert to lowercase (default). 'FALSE' keeps the upper and lower case of the input, e.g. to compare the cleaned DOI with the field it came from. |
what |
What to extract from each element. One of:
|
Percent-encoded characters are decoded first, also when encoded twice (' encoded line break (' not an encoding, such as the unfilled placeholders in '10.18461/ijfsd.v2i4. or '10.37002/biobrasil.v cut short to something that looks valid. A full stop or semicolon at the end is taken as punctuation and dropped.
A character vector: - If 'non_doi_value' is not 'NULL', a vector of the same length as 'x', with unmatched entries replaced. - If 'non_doi_value' is 'NULL', a vector of only matched entries.
x <- c( "https://doi.org/10.5281/zenodo.1234567", " 10.1000/XYZ456 ", "no doi here", NA ) extract_doi(x) # Full DOIs (default) extract_doi(x, what = "resolver") extract_doi(x, what = "prefix") extract_doi(x, what = "suffix") extract_doi(x, non_doi_value = NA_character_) extract_doi(x, non_doi_value = NULL)x <- c( "https://doi.org/10.5281/zenodo.1234567", " 10.1000/XYZ456 ", "no doi here", NA ) extract_doi(x) # Full DOIs (default) extract_doi(x, what = "resolver") extract_doi(x, what = "prefix") extract_doi(x, what = "suffix") extract_doi(x, non_doi_value = NA_character_) extract_doi(x, non_doi_value = NULL)
This function computes the ID block partition key from OpenAlex IDs. The ID block is calculated as the trailing numeric portion of the ID divided by 10,000.
id_block(ids)id_block(ids)
ids |
Character vector of OpenAlex IDs in any format:
|
OpenAlex IDs come in several formats:
Standard: https://openalex.org/{type}{number} (e.g., W1234567890)
Path-based: https://openalex.org/{entity_type}/{number} (e.g., domains/2, subfields/2208)
The ID block is computed as floor(number / 10000), where number is
the trailing numeric portion of the ID. This groups approximately 10,000
IDs into each block, useful for partitioning large datasets.
Integer vector of ID blocks.
# Short form IDs id_block(c("W2741809807", "W2741809808", "W1234567890")) # Returns: c(274180, 274180, 123456) # Long form IDs id_block("https://openalex.org/W2741809807") # Returns: 274180 # Path-based IDs id_block("https://openalex.org/domains/2") # Returns: 0 # Works with any entity type id_block(c("A123456789", "I987654321")) # Returns: c(12345, 98765)# Short form IDs id_block(c("W2741809807", "W2741809808", "W1234567890")) # Returns: c(274180, 274180, 123456) # Long form IDs id_block("https://openalex.org/W2741809807") # Returns: 274180 # Path-based IDs id_block("https://openalex.org/domains/2") # Returns: 0 # Works with any entity type id_block(c("A123456789", "I987654321")) # Returns: c(12345, 98765)
Infers the schema of each JSON/NDJSON file individually via DuckDB's 'read_json_auto()' and merges the results using type-widening rules. Processing files one at a time avoids the out-of-memory errors that occur when opening all files in a single DuckDB query.
infer_json_schema( con, files, sample_size = 20, extra_options = "", verbose = TRUE, schema_cache_dir = NULL )infer_json_schema( con, files, sample_size = 20, extra_options = "", verbose = TRUE, schema_cache_dir = NULL )
con |
An active DuckDB connection ('DBI::dbConnect(duckdb::duckdb())') with the JSON extension loaded ('LOAD json'). |
files |
Character vector of paths to JSON or NDJSON ('.gz') files. |
sample_size |
Number of files to sample for schema inference. Higher values give more accurate schemas but take longer. Use '0' or 'NULL' to use all files. Default is '20'. |
extra_options |
Additional options appended to the 'read_json_auto' SQL call, e.g. '", maximum_object_size=1000000000"' for large JSON objects. Default is '""'. |
verbose |
If 'TRUE', print progress messages and a progress bar. Default is 'TRUE'. |
schema_cache_dir |
Path to a directory for caching per-file and unified schemas. The directory is created if it does not exist. 'NULL' (default) disables caching. |
The returned columns clause can be passed directly to 'read_json(..., columns = <result>)' or 'read_json_auto(..., columns = <result>)' in subsequent DuckDB queries to enforce a consistent schema across all files.
A DuckDB columns clause string (e.g.
"{'col1': 'VARCHAR', 'col2': 'BIGINT', ...}") suitable for use as
the 'columns' argument to 'read_json()'. Returns 'NULL' if schema
inference fails for all files.
When 'schema_cache_dir' is provided, two levels of caching apply: - **Unified schema** ('unified_schema.csv'): if present, loaded and returned immediately - no DuckDB queries needed. Delete this file to force re-inference. - **Per-file schemas** (‘<update_date>_<part_name>.csv'): each file’s schema is saved as it is inferred. On restart, already-cached files are skipped, enabling mid-run resume for large file sets.
When a column has different types across files, the unified type is chosen by these rules (in order): 1. All identical -> keep as-is. 2. Any 'STRUCT'/'LIST'/'MAP' vs simpler type -> complex type wins. 3. Multiple 'STRUCT' types -> pick the one with the most fields. 4. All types numeric -> widest type wins ('TINYINT < SMALLINT < INTEGER < BIGINT < HUGEINT < FLOAT < DOUBLE'). 'JSON', which DuckDB infers for a column that is null throughout a file, is ignored here. 5. Fallback -> 'VARCHAR'.
[pro_request_jsonl_parquet()] (deprecated), which uses this function internally.
## Not run: con <- DBI::dbConnect(duckdb::duckdb()) DBI::dbExecute(con, "LOAD json") files <- list.files("path/to/snapshot/works", pattern = "\\.gz$", recursive = TRUE, full.names = TRUE) schema <- infer_json_schema(con, files, sample_size = 50, schema_cache_dir = "path/to/cache") DBI::dbDisconnect(con, shutdown = TRUE) # schema is now a string like: {'id': 'VARCHAR', 'title': 'VARCHAR', ...} ## End(Not run)## Not run: con <- DBI::dbConnect(duckdb::duckdb()) DBI::dbExecute(con, "LOAD json") files <- list.files("path/to/snapshot/works", pattern = "\\.gz$", recursive = TRUE, full.names = TRUE) schema <- infer_json_schema(con, files, sample_size = 50, schema_cache_dir = "path/to/cache") DBI::dbDisconnect(con, shutdown = TRUE) # schema is now a string like: {'id': 'VARCHAR', 'title': 'VARCHAR', ...} ## End(Not run)
This function runs a jq filter to extract records from the "results" array
(or from the root if type = "single"), reconstruct the abstract text,
generate a citation string, and optionally add a page field. It writes the
result as newline-delimited JSON (.jsonl), suitable for Arrow or DuckDB. For
details on the jq filter logic, see the vignette("jq", package
= "openalexPro").
jq_execute( input_json, output_jsonl, add_columns = list(), jq_filter = NULL, page = NULL, type = c("results", "single", "group_by") )jq_execute( input_json, output_jsonl, add_columns = list(), jq_filter = NULL, page = NULL, type = c("results", "single", "group_by") )
input_json |
Path to the input JSON file |
output_jsonl |
Path to the output .jsonl file |
add_columns |
List of additional fields to be added to the output. They nave to be provided as a named list, e./g. 'list(column_1 = "value_1", column_2 = 2)'. Only Scalar values are supported. |
jq_filter |
Optional custom jq filter string. If NULL, the default filter is used. |
page |
Optional integer to be added as a "page" field in each output record |
type |
Either "results" (default, expects a .results[] array) or "single" (treat input as array of records directly) |
Invisibly returns the output path
Uppercases SQL type keywords (BIGINT, VARCHAR,
STRUCT, ...) while preserving the case of struct field
identifiers.
oa_normalize_duckdb_type(t)oa_normalize_duckdb_type(t)
t |
A character scalar: a raw DuckDB type string, e.g.
|
A character scalar with normalised type keywords.
Returns the baseline column schema for an OpenAlex entity (used by
pro_request_parquet(schema = "auto") to resolve ambiguous
DuckDB JSON types), and optionally refreshes the user-level cache from a
local Parquet corpus.
oa_schema( entity = NULL, parquet_dir = NULL, entities = "all", overwrite = FALSE, update = FALSE, verbose = TRUE )oa_schema( entity = NULL, parquet_dir = NULL, entities = "all", overwrite = FALSE, update = FALSE, verbose = TRUE )
entity |
Character scalar. Entity name, e.g. |
parquet_dir |
Character scalar. Root Parquet directory containing one
sub-directory per entity, e.g. |
entities |
Character vector or |
overwrite |
Logical. When |
update |
Logical. When |
verbose |
Logical. Print progress messages? Default |
update = FALSE: a data.frame with columns col_name
and col_type, or NULL if no schema is found for
entity.update = TRUE: the path to the schemata cache directory
(invisibly).
update = FALSE) User cache (tools::R_user_dir("openalexPro","cache")/schemata/<entity>.csv)
Schemas bundled with the package (inst/extdata/schemata/<entity>.csv)
update = TRUE)Reads the schema of each entity corpus from parquet_dir using
DuckDB and writes the result to the user cache. After updating, the new
schema is available to subsequent calls with update = FALSE and to
pro_request_parquet(schema = "auto"). Run periodically to pick up
new fields added by OpenAlex.
pro_request_parquet for the schema parameter.
abstract_inverted_index column in OpenAlex works data.The expression walks the map, collects (position, word) pairs, sorts by
position ascending, and joins words with single spaces. Returns NULL when
abstract_inverted_index is NULL.
oa_works_abstract_sql()oa_works_abstract_sql()
abstract_inverted_index is normalised to MAP(VARCHAR, BIGINT[])
via a double JSON cast (::JSON::MAP(VARCHAR, BIGINT[])) before
map_entries() is called. This makes the expression safe regardless
of whether DuckDB inferred the column as MAP, STRUCT, or
VARCHAR (raw JSON text): all three round-trip through the JSON
representation identically.
A character scalar containing the SQL expression.
authorships and publication_year columns in OpenAlex
works data.Format: "Author (year)" / "A & B (year)" /
"A et al. (year)".
Null year renders as "(n.d.)".
Null or empty authorships yields NULL.
oa_works_citation_sql()oa_works_citation_sql()
A character scalar containing the SQL expression.
Get API key for OpenAlex API
opt_api_key(api_key)opt_api_key(api_key)
api_key |
character vector or NULL. If specified, value to assign to the api key option. Default is 'NULL'. |
The API key, if 'api_key' is not specified the current one, otherwise the old one.
Valid filter names differ between entities (e.g. 'country_code' is a filter for institutions but not for works). The list is taken from the error message OpenAlex returns for an invalid filter, which names exactly the filters it accepts for that entity; error responses cost no credits. Each entity's list is cached for the R session.
opt_filter_names(update = FALSE, entity = "works")opt_filter_names(update = FALSE, entity = "works")
update |
logical. If 'TRUE' update the existing value. Default is 'FALSE'. |
entity |
OpenAlex entity, e.g. '"works"' (default), '"authors"', '"institutions"'. Use the same value as 'entity' in [pro_query()]. |
A character vector of available filter names. Empty if OpenAlex does not return a list for 'entity' (e.g. the retired '"venues"').
Valid select fields differ between entities (e.g. 'orcid' for authors). The list is taken from the error message OpenAlex returns for an invalid select field, which names exactly the fields it accepts for that entity; error responses cost no credits. Each entity's list is cached for the R session.
opt_select_fields(update = FALSE, entity = "works")opt_select_fields(update = FALSE, entity = "works")
update |
logical. If 'TRUE' update the existing value. Default is 'FALSE'. |
entity |
OpenAlex entity, e.g. '"works"' (default), '"authors"', '"institutions"'. Use the same value as 'entity' in [pro_query()]. |
A character vector of available select fields. Empty if OpenAlex does not return a list for 'entity' (e.g. the retired '"venues"').
Retrieves the OpenAlex Pro API key from one of several locations, checked in the following order:
pro_api_key()pro_api_key()
The R option openalexPro$api_key
The environment variable openalexPro.api_key
The system keyring via the keyring package (only if the package keyring is installed)
If no API key is found, NULL or an empty string may be returned,
depending on the environment variable state.
A character string containing the API key, or NULL if no key
could be found.
## Not run: pro_api_key() options(openalexPro = list(api_key = "my-key")) pro_api_key() ## End(Not run)## Not run: pro_api_key() options(openalexPro = list(api_key = "my-key")) pro_api_key() ## End(Not run)
Turns each query into an OpenAlex
collection: a saved set of IDs
on OpenAlex's servers that can be reused in later queries
(pro_query(collection = "col_...")) and combined with other collections.
OpenAlex runs the query itself (an import); pro_collection() waits for
it and then downloads what select asks for.
pro_collection( query_url, name = NULL, project_folder, select = "id", refresh = FALSE, access = NULL, api_key = pro_api_key(), verbose = FALSE, progress = TRUE, ... )pro_collection( query_url, name = NULL, project_folder, select = "id", refresh = FALSE, access = NULL, api_key = pro_api_key(), verbose = FALSE, progress = TRUE, ... )
query_url |
A query from |
name |
Name of the collection (and of its folder). Required for a
single query. For a list: |
project_folder |
Directory for the |
select |
What to download: |
refresh |
If |
access |
Who can see the collection: |
api_key |
A personal OpenAlex API key. |
verbose |
Print the collection ID(s). |
progress |
Show the steps and import progress. |
... |
Passed to |
Each query gets a folder <project_folder>/<name>.collection/ with
_collection.jsonthe query (URL, OQL, OQO), the collection
(collection_id, display_name, entity_type, member_count, ...),
each import, the credits used and the select that was downloaded.
_query_oql.txt, _query_oql.html
the query in readable OQL.
_parts.parquetfor a list of queries in one collection (see
Several queries in one collection): the name and URL of each query.
_collection.json then holds no queries, so it stays small however
long the list is.
members/parquet/the member IDs (id, added_at).
records/the records when select asks for more than id
(the pro_fetch() layout).
Running it again with the same project_folder and name:
Same query: the collection is kept (same ID). An import still
running (e.g. after an interruption) is waited for. Only the downloads
are brought in line with select: removed fields are dropped locally
(no requests), added fields re-download the records. Credits are
charged per request, not per field, so fetching only the new fields
would cost the same.
refresh = TRUE, with the same or a changed query: the
collection keeps its ID, and its members are made to match the query
now: the query's IDs are fetched with
pro_fetch() (select = "id", same credits as an import), new ones
are added and members no longer found are removed (free, 10,000 added
or 100 removed per request). Everything is then downloaded again.
Changed query without refresh: the old collection is deleted
and a new one is created under the same name (it gets a new ID).
So refresh = TRUE always keeps the ID (links and saved searches keep
working). Only when the collection is gone on OpenAlex, or holds another
entity, is a new one created.
Local folder gone: a collection with the same name that exists in
your account but is not recorded in project_folder is never deleted.
Without refresh, pro_collection() stops. With refresh = TRUE it takes
that collection over: the ID stays, its members are synced to the query
as above, and the folder is written again. Names match ignoring case, and
the collection must hold the same entity.
Costs: creating and managing collections and downloading the member
IDs are free. An import costs the same credits as paging through the
results yourself (one list request per 200 results). Imports run at about
200 results per second (measured November 2026), so a collection of the
maximum 1,000,000 members takes over an hour. Interrupting pro_collection()
does not stop the import on the server; running it again waits for it.
Several queries in one collection: OpenAlex imports a query of at
most 20,000 characters of OQL (about 600 to 800 DOIs); a longer single
query stops before anything is created. For long ID or DOI lists, split
them into chunks, e.g. pro_query(doi = dois, chunk_limit = 200), and pass
the list with name. The queries are then not imported: they are fetched
with pro_fetch() (select = "id", in parallel with workers) and the
IDs are added to the collection (member_ids, 10,000 per request, free).
This costs the same credits as imports and was about five times faster
with workers = 8 (3,000 DOIs: 8.5 s instead of 45 to 55 s, November
2026). Fields in select beyond id are fetched in the same pass, from
the queries themselves, so the records do not depend on the collection
filter limit. An interrupted run resumes the fetch and syncs the members
again (syncing is idempotent). A changed query re-creates the collection
unless refresh = TRUE, which keeps it, fetches everything again and
syncs the members.
Limits: 1,000,000 members per collection, 500 collections per
account, names up to 100 characters and unique per account. A collection
with more than 300,000 members (100,000 for authors) cannot be used as a
filter, so its records cannot be downloaded with select; its member IDs
can. Queries with group_by or sample cannot be imported.
Core and expansion works: a collection holds all its members, and the
member IDs in members/ include expansion works (DataCite, repositories).
A filter by a works collection returns only its core works unless
corpus = "all" is set, so the records in records/ are fetched with
corpus = "all", and later queries should set it too:
pro_query(collection = id, options = list(corpus = "all")). Whether
expansion works get into the collection depends on the query that fills
it (options = list(corpus = "all") in pro_query()).
API key: collections need a personal OpenAlex API key; organisation keys and some older keys are refused (HTTP 401) even when they work for queries.
Invisibly, the path of the .collection folder, or a named
character vector of paths for a list of queries without name.
pro_fetch(), pro_query(), vignette("collections").
## Not run: q <- pro_query(search = "coral bleaching", publication_year = 2024) f <- pro_collection(q, name = "coral bleaching 2024", project_folder = "proj") id <- jsonlite::read_json(file.path(f, "_collection.json"))$collection_id # Later: records of the collection that are open access. corpus = "all": # without it, the filter returns only the core works pro_fetch(pro_query(collection = id, is_oa = TRUE, options = list(corpus = "all")), project_folder = "oa") # Let anyone with the link or ID use it pro_collection(q, name = "coral bleaching 2024", project_folder = "proj", access = "shared_by_link") # Add titles to the download (re-downloads the records) pro_collection(q, name = "coral bleaching 2024", project_folder = "proj", select = c("id", "title")) # A long DOI list in one collection: the chunks are fetched in parallel # and their IDs added as members pro_collection(pro_query(doi = dois, chunk_limit = 200), name = "my dois", project_folder = "proj", workers = 8) ## End(Not run)## Not run: q <- pro_query(search = "coral bleaching", publication_year = 2024) f <- pro_collection(q, name = "coral bleaching 2024", project_folder = "proj") id <- jsonlite::read_json(file.path(f, "_collection.json"))$collection_id # Later: records of the collection that are open access. corpus = "all": # without it, the filter returns only the core works pro_fetch(pro_query(collection = id, is_oa = TRUE, options = list(corpus = "all")), project_folder = "oa") # Let anyone with the link or ID use it pro_collection(q, name = "coral bleaching 2024", project_folder = "proj", access = "shared_by_link") # Add titles to the download (re-downloads the records) pro_collection(q, name = "coral bleaching 2024", project_folder = "proj", select = c("id", "title")) # A long DOI list in one collection: the chunks are fetched in parallel # and their IDs added as members pro_collection(pro_query(doi = dois, chunk_limit = 200), name = "my dois", project_folder = "proj", workers = 8) ## End(Not run)
pro_request_parquet() writes one Parquet file per API page (up to 200
records). That keeps the conversion parallel and resumable, but a large
query becomes thousands of small files, which are slow to read.
pro_compact_parquet() combines them into files of up to rows records.
Records, columns and their order do not change.
pro_compact_parquet(parquet_dir, rows, verbose = TRUE)pro_compact_parquet(parquet_dir, rows, verbose = TRUE)
parquet_dir |
Output directory of |
rows |
Maximum number of records per compacted file, e.g. |
verbose |
Logical. Report what was compacted. Default |
Measured for 1.1 million works (5,460 page files): compaction took about
20 seconds; afterwards aggregates and lookups by ID ran 35 to 50 times
faster, reading full records with DuckDB 4 times faster, and the dataset
was 40% smaller. Files of 50,000 to 1 million records made no difference
to read speed; rows = 250000 is a good choice (about 0.25 GB of full
works records; newer works with abstracts and long reference lists are
larger).
Each query's partition (query=<name>/) is compacted on its own; its
_query.json and _query_oql.* files stay.
A compacted file holds whole consecutive pages, in download order, and is
named after them: pages 1 to 1250 become results_pages_1-1250.parquet.
A page with more than rows records becomes a file of its own. The
page column is kept.
Files are compacted one at a time: each is written to a .part file, its
record count checked, renamed, and only then are its pages deleted. If
interrupted, run it again: it completes what was started.
Files compacted before are left as they are; only page files are combined.
If a partition cannot be compacted (for example because its pages have conflicting column types), a warning says so and its page files stay: the dataset is complete either way.
Indexes built by openalexSnapshot::build_corpus_index() or
build_doi_index() point to files and row numbers, and would be wrong
after compaction. If such an index exists next to parquet_dir, the
function stops: delete the index, compact, and build it again.
parquet_dir (invisibly).
The compact_parquet argument of pro_request_parquet() and
pro_fetch(), which compacts right after the conversion.
## Not run: pro_compact_parquet("my_project/parquet", rows = 250000) ## End(Not run)## Not run: pro_compact_parquet("my_project/parquet", rows = 250000) ## End(Not run)
Downloads full-text content from the OpenAlex content endpoint
(content.openalex.org) for a vector of work IDs. One file is written
per ID. Downloads can be parallelised via the workers argument.
pro_download_content( ids, format = c("pdf", "grobid-xml"), output = ".", workers = 1L, api_key = pro_api_key(), endpoint = "https://content.openalex.org" )pro_download_content( ids, format = c("pdf", "grobid-xml"), output = ".", workers = 1L, api_key = pro_api_key(), endpoint = "https://content.openalex.org" )
ids |
Character vector of OpenAlex work IDs (e.g.
|
format |
File format to download. One of |
output |
Directory to save downloaded files into. Defaults to the current working directory. Created if it does not exist. |
workers |
Number of parallel download workers. Defaults to |
api_key |
OpenAlex API key (character string) or 'NULL'. Defaults to
|
endpoint |
Base URL of the content endpoint. Defaults to
|
A data frame with one row per ID and columns:
idThe (normalised) work ID.
fileFull path to the saved file, or NA if not
downloaded.
statusOne of "ok", "not_found" (HTTP 404),
or "error".
messageError message, or NA on success.
Content downloads cost $0.01 per file - 10x the cost of a
metadata search query. Use has_content.pdf:true or
has_content.grobid-xml:true as filter arguments to pro_query()
to discover which works have downloadable content before downloading.
"pdf"Full-text PDF (~60 million files available).
"grobid-xml"Machine-readable TEI XML parsed by Grobid (~43 million files). Suitable for structured text extraction.
PDFs and XMLs retain their original copyright. OpenAlex does not grant
additional rights. Check the best_oa_location.license field of each
work for the applicable licence.
## Not run: # Download a single PDF result <- pro_download_content( ids = "W2741809807", format = "pdf", output = tempdir() ) # Find works with PDFs available, then download them urls <- pro_query( entity = "works", has_content.pdf = TRUE, from_publication_date = "2023-01-01", options = list(per_page = 10) ) works <- pro_request(urls, output = tempdir()) # ... extract IDs from works data, then: result <- pro_download_content(ids = work_ids, format = "pdf", workers = 4) # XPAC works: discover via pro_query() with include_xpac = TRUE, then download # (pro_download_content() works with any valid OpenAlex ID, including XPAC IDs) urls_xpac <- pro_query( entity = "works", has_content.pdf = TRUE, from_publication_date = "2023-01-01", options = list(include_xpac = TRUE, per_page = 10) ) works_xpac <- pro_request(urls_xpac, output = tempdir()) # ... extract IDs from works_xpac data, then: result_xpac <- pro_download_content(ids = xpac_ids, format = "pdf", workers = 4) ## End(Not run)## Not run: # Download a single PDF result <- pro_download_content( ids = "W2741809807", format = "pdf", output = tempdir() ) # Find works with PDFs available, then download them urls <- pro_query( entity = "works", has_content.pdf = TRUE, from_publication_date = "2023-01-01", options = list(per_page = 10) ) works <- pro_request(urls, output = tempdir()) # ... extract IDs from works data, then: result <- pro_download_content(ids = work_ids, format = "pdf", workers = 4) # XPAC works: discover via pro_query() with include_xpac = TRUE, then download # (pro_download_content() works with any valid OpenAlex ID, including XPAC IDs) urls_xpac <- pro_query( entity = "works", has_content.pdf = TRUE, from_publication_date = "2023-01-01", options = list(include_xpac = TRUE, per_page = 10) ) works_xpac <- pro_request(urls_xpac, output = tempdir()) # ... extract IDs from works_xpac data, then: result_xpac <- pro_download_content(ids = xpac_ids, format = "pdf", workers = 4) ## End(Not run)
Convenience wrapper that downloads records from OpenAlex via
pro_request() and converts them directly to an Apache Parquet
dataset via pro_request_parquet(). No intermediate JSONL
files are written.
pro_fetch( query_url, pages = 10000, project_folder = NULL, overwrite = FALSE, api_key = pro_api_key(), delete_input = TRUE, workers = 1, download_workers = workers, verbose = FALSE, progress = TRUE, enrich = TRUE, count_only, error_log = NULL, resume = FALSE, via = c("oqo", "url"), inconsistency_on_resume = c("error", "warning", "ignore", "oldest", "newest"), compact_parquet = NULL, hive_names = NULL )pro_fetch( query_url, pages = 10000, project_folder = NULL, overwrite = FALSE, api_key = pro_api_key(), delete_input = TRUE, workers = 1, download_workers = workers, verbose = FALSE, progress = TRUE, enrich = TRUE, count_only, error_log = NULL, resume = FALSE, via = c("oqo", "url"), inconsistency_on_resume = c("error", "warning", "ignore", "oldest", "newest"), compact_parquet = NULL, hive_names = NULL )
query_url |
The URL of the API query or a list of URLs returned from |
pages |
The maximum number of pages (of 200 records) downloaded per
query; for a list, the limit applies to each leaf query. 100000 pages
are 20,000,000 records; for more, use the snapshot instead. If |
project_folder |
Directory where intermediate ( |
overwrite |
Logical. If |
api_key |
Character string API key or |
delete_input |
Logical. If |
workers |
Number of parallel workers for the conversion to Parquet (CPU and memory bound), and by default also for the download. Default 1. |
download_workers |
Number of parallel workers for the download, used
when |
verbose |
Logical indicating whether to show verbose messages. |
progress |
Logical indicating whether to show a progress bar. Default |
enrich |
Logical. When |
count_only |
Do not use it here. The function will abort if set to
|
error_log |
location of error log of API calls. (default: |
resume |
Logical. When |
via |
How each query is sent. |
inconsistency_on_resume |
What to do when a query that was resumed in
the middle turns out inconsistent, because OpenAlex's data changed between
the sessions: records that appear twice (found exactly, by work ID) or
missing records (only as a net difference to OpenAlex's current count –
a record lost and another added cancel out). |
compact_parquet |
|
hive_names |
Character vector of Hive partition keys, one per nesting
level of a list of queries: |
The function
downloads records from OpenAlex via pro_request() into a
"json" subfolder of project_folder, and
converts the JSON files to an Apache Parquet dataset via
pro_request_parquet() into a "parquet" subfolder.
This function assumes count_only == FALSE
Invisibly, the normalised path of the parquet subfolder
inside project_folder.
pro_request() for the download step,
pro_request_parquet() for the conversion step,
pro_compact_parquet() to compact an existing dataset.
## Not run: # Combine each query's page files into files of up to 250,000 records, # which are much faster to read pro_fetch( pro_query(search = "coral reef", from_publication_date = "2020-01-01"), project_folder = "coral_reef", compact_parquet = 250000 ) ## End(Not run)## Not run: # Combine each query's page files into files of up to 250,000 records, # which are much faster to read pro_fetch( pro_query(search = "coral reef", from_publication_date = "2020-01-01"), project_folder = "coral_reef", compact_parquet = 250000 ) ## End(Not run)
Construct an httr2 request for the OpenAlex API. All filters must be
supplied as named ... arguments (e.g., from_publication_date = "2020-01-01").
pro_query( entity = c("works", "authors", "venues", "institutions", "concepts", "publishers", "funders", "sources", "topics", "locations"), id = NULL, doi = NULL, search = NULL, search.exact = NULL, search.semantic = NULL, group_by = NULL, select = NULL, options = NULL, endpoint = "https://api.openalex.org", chunk_limit = 50L, oql = NULL, oqo = NULL, ... )pro_query( entity = c("works", "authors", "venues", "institutions", "concepts", "publishers", "funders", "sources", "topics", "locations"), id = NULL, doi = NULL, search = NULL, search.exact = NULL, search.semantic = NULL, group_by = NULL, select = NULL, options = NULL, endpoint = "https://api.openalex.org", chunk_limit = 50L, oql = NULL, oqo = NULL, ... )
entity |
Character; one of |
id |
Optional ID or vector of IDs (e.g., |
doi |
Optional DOI or vector of DOIs (e.g., |
search |
Optional full-text search string. Applies stemming and
stop-word removal. Supports boolean operators ( |
search.exact |
Optional full-text search without stemming or stop-word
removal. Supports the boolean/phrase/proximity syntax of |
search.semantic |
Optional semantic (AI-powered) search string. Uses embeddings to match conceptual meaning rather than exact keywords. Limited to 1 request per second and returns at most 50 results per query. |
group_by |
Optional field to group by (facets), e.g. |
select |
Optional character vector of fields to return. |
options |
Optional named list of additional query parameters (e.g.,
|
endpoint |
Base API URL. Defaults to |
chunk_limit |
Number of DOIS or ids per chunk if chunked. Default: 50 |
oql |
Optional OQL (OpenAlex Query Language) query string, e.g.
|
oqo |
Optional OQO (OpenAlex Query Object): a nested list, or a JSON
string. A list of OQOs (lists or JSON strings), or a character vector of
JSON strings, gives a named list of URLs as for |
... |
Filters as named arguments. Values may be scalars or vectors (vectors
are collapsed with |
Filter names are validated against opt_filter_names(entity = entity)
and select fields against opt_select_fields(entity = entity),
i.e. against the names OpenAlex accepts for the queried entity.
If multiple more then 50 'doi' or openalex 'id's are provided, the request is automatically split into chunks of 50 and a named list of URLs is returned.
An individual URL or a list of URLs.
All three search parameters (search, search.exact,
search.semantic) accept a query string. For search and
search.exact, the following syntax is supported:
Boolean: biodiversity AND finance, climate OR weather,
ocean NOT pollution (operators must be uppercase); group with
parentheses. Words without an operator between them are combined with
AND.
Exact phrase: "biodiversity finance" (double quotes).
Proximity: "biodiversity finance"~5 (words within 5
positions), or two phrases near each other:
"machine learning"~5~"neural network".
Only with search.exact (the stemmed search rejects wildcards
with HTTP 400, and stemming distorts fuzzy terms):
Wildcard: microbio* (zero or more characters),
organi?ation (exactly one). At least 3 characters before the
wildcard; no leading wildcard.
Fuzzy: biodiversty~1 (up to N character edits, N = 0–2;
at least 3 characters before the ~).
See https://help.openalex.org/api/searching/.
search.semantic does not use keyword syntax; pass a natural-language
phrase or even a full abstract. It returns at most 50 results per call.
OpenAlex's query language (oql) and its JSON form (oqo)
express queries the classic filter syntax cannot, such as nested
and / or conditions. The entity, all conditions, grouping
(group by), sample and corpus belong inside the query,
so entity, id, doi, the search arguments,
group_by and filters in ... cannot be combined with it –
OpenAlex would silently ignore them. select and options
(e.g. sort) are passed alongside. The URL targets the API root
(https://api.openalex.org/?oql=...) and works with
pro_request(), pro_count() and pro_fetch() as usual.
An invalid query fails at request time with OpenAlex's parse error.
See https://help.openalex.org/api/oql/.
Filter arguments with a .search suffix (e.g.
title_and_abstract.search = "biodiversity") are deprecated by the
OpenAlex API. They still work but emit a warning. Use the search,
search.exact, or search.semantic parameters instead. See
https://help.openalex.org/api/searching/ for details.
## Not run: url <- pro_query( entity = "works", search = "biodiversity", from_publication_date = "2020-01-01", language = c("en","de"), select = c("id","title","publication_year"), options = list(per_page = 5) ) # OQL: nested conditions the filter syntax cannot express url <- pro_query( oql = "works where year >= (2020) and (title has (coral) or title has (reef))" ) # OQO: the same kind of query as a nested list url <- pro_query(oqo = list( get_rows = "works", filter_rows = list(list(column_id = "publication_year", value = 2020)) )) ## End(Not run)## Not run: url <- pro_query( entity = "works", search = "biodiversity", from_publication_date = "2020-01-01", language = c("en","de"), select = c("id","title","publication_year"), options = list(per_page = 5) ) # OQL: nested conditions the filter syntax cannot express url <- pro_query( oql = "works where year >= (2020) and (title has (coral) or title has (reef))" ) # OQO: the same kind of query as a nested list url <- pro_query(oqo = list( get_rows = "works", filter_rows = list(list(column_id = "publication_year", value = 2020)) )) ## End(Not run)
Queries the OpenAlex rate-limit endpoint and returns current API usage and remaining budget as a parsed list.
pro_rate_limit_status(api_key = pro_api_key(), verbose = TRUE)pro_rate_limit_status(api_key = pro_api_key(), verbose = TRUE)
api_key |
API key (character string) or 'NULL'. Defaults to
|
verbose |
Logical. If |
Invisibly, the parsed JSON list with all rate limit fields; FALSE
if the API key is missing or invalid; or NULL if the request failed due
to a network error.
All returned values from OpenAlex will be saved as
json files in the output directory and the return value is the directory of the
json files.
pro_request( query_url, pages = 1e+05, output = NULL, overwrite = FALSE, api_key = pro_api_key(), workers = 1, verbose = FALSE, progress = TRUE, count_only = FALSE, error_log = NULL, resume = FALSE, via = c("oqo", "url"), inconsistency_on_resume = c("error", "warning", "ignore", "oldest", "newest") )pro_request( query_url, pages = 1e+05, output = NULL, overwrite = FALSE, api_key = pro_api_key(), workers = 1, verbose = FALSE, progress = TRUE, count_only = FALSE, error_log = NULL, resume = FALSE, via = c("oqo", "url"), inconsistency_on_resume = c("error", "warning", "ignore", "oldest", "newest") )
query_url |
The URL of the API query or a list of URLs returned from |
pages |
The maximum number of pages (of 200 records) downloaded per
query; for a list, the limit applies to each leaf query. 100000 pages
are 20,000,000 records; for more, use the snapshot instead. If |
output |
directory where the JSON files are saved. Required (the
default |
overwrite |
Logical. If |
api_key |
Character string API key or |
workers |
Number of parallel workers to use if |
verbose |
Logical indicating whether to show verbose messages. |
progress |
Logical indicating whether to show a progress bar. Default |
count_only |
return count only as a data.frame. |
error_log |
location of error log of API calls. (default: |
resume |
Logical. When |
via |
How each query is sent. |
inconsistency_on_resume |
What to do when a query that was resumed in
the middle turns out inconsistent, because OpenAlex's data changed between
the sessions: records that appear twice (found exactly, by work ID) or
missing records (only as a net difference to OpenAlex's current count –
a record lost and another added cancel out). |
If query_url is a list, the function is called for each element of the list in parallel
using a maximum of workers parallel R sessions. The results from the individual URLs
in the list are returned in a folder named after the names of the list elements in the
output folder.
When starting the download, a file 00_in.progress which is deleted upon completion.
If one query of a list fails (e.g. HTTP 404 for an ID that does not exist),
the other queries still complete. At the end, one error names each failed
query with OpenAlex's reason. The failed queries keep their
00_in.progress, so resume = TRUE fetches only them again.
Pages are fetched with cursor paging. A per_page in the query is kept;
page and cursor are replaced, with a warning. A sample is fetched by
page number, as OpenAlex ends cursor paging of a sample after the first
page; if it spans several pages and has no seed, one is chosen and
reported. Semantic search (search.semantic) is fetched as its single page
of at most 50 results.
Each query directory also gets a record of the query: _query.json (the
URL, how it was sent, the query as OpenAlex ran it as OQL and OQO, records,
requests, credits, cost, time), and for papers _query_oql.txt and a
formatted, self-contained _query_oql.html with the query in OpenAlex's
readable query language (OQL). The OQL is translated back and compared with
the query that ran; the files say whether it reproduces it exactly. Single
records get only _query.json. For a list of queries, _queries_oql.txt
and _queries_oql.html at the top of output summarise all queries
(records, exactness, OQL), e.g. for a paper's supplement.
If count_only is FALSE (the default) the complete path to the expanded and
normalized output. If count_only is TRUE, a data.frame with metadata about
the query (count, db_response_time_ms, page, per_page, error). When query_url is
a list, an additional query column identifies each query.
The function takes a directory of JSON files as written from a call to
pro_request(...) and is preparing the json files to be
processed further using DuckDB by converting them to jsonl files.
The subfolders in input_json are preserved in output, i.e.
results of a list of initial queries passed to pro_request() are maintained.
pro_request_jsonl( input_json = NULL, output = NULL, add_columns = list(), overwrite = FALSE, verbose = TRUE, progress = TRUE, delete_input = FALSE, workers = 1 )pro_request_jsonl( input_json = NULL, output = NULL, add_columns = list(), overwrite = FALSE, verbose = TRUE, progress = TRUE, delete_input = FALSE, workers = 1 )
input_json |
The directory of JSON files returned from |
output |
output directory for the jsonl files as created by calls to 'jq_execute(). |
add_columns |
List of additional fields to be added to the output. They
nave to be provided as a named list, e./g. |
overwrite |
Logical indicating whether to overwrite |
verbose |
Logical indicating whether to show a verbose information.
Defaults to |
progress |
Logical indicating whether to show a progress bar. Default |
delete_input |
Determines if the |
workers |
Number of parallel workers to use. Defaults to 1. |
See jq_execute or the vignette("jq",
package = "openalexPro") for more information on the conversion of the
JSON files.
The folder/filename is converted to a value named page
As an example:
the subfolder in the output folder is called Chunk_1
the page othe json file represents is 2
The resulting cvalus for page will be Chunk_1_2
When starting the conversion, a file 00_in.progress which is deleted upon completion.
The function uses DuckDB to read the JSON files and to create the Apache Parquet files. The function creates a DuckDB connection in memory and readsds the JSON files into DuckDB when needed. Then it creates a SQL query to convert the JSON files to Apache Parquet files and to copy the result to the specified directory.
The function does returns the output invisibly.
## Not run: source_to_parquet( input_json = "json", source_type = "snapshot", output = "parquet" ) ## End(Not run)## Not run: source_to_parquet( input_json = "json", source_type = "snapshot", output = "parquet" ) ## End(Not run)
The function takes a directory of JSONL files as written from a call to
pro_request_jsonl(...) and converts each file individually to a Parquet file.
The subfolder structure from the input is preserved in the output, so files
in Chunk_1/ will be written to Chunk_1/ in the output directory.
pro_request_jsonl_parquet( input_jsonl = NULL, output = NULL, overwrite = FALSE, verbose = TRUE, delete_input = FALSE, sample_size = 1000, workers = NULL )pro_request_jsonl_parquet( input_jsonl = NULL, output = NULL, overwrite = FALSE, verbose = TRUE, delete_input = FALSE, sample_size = 1000, workers = NULL )
input_jsonl |
The directory of JSON files returned from
|
output |
output directory for the parquet dataset; default: temporary directory. |
overwrite |
Logical indicating whether to overwrite |
verbose |
Logical indicating whether to show verbose information.
Defaults to |
delete_input |
Determines if the |
sample_size |
Number of records to sample from each file when inferring the unified schema. Higher values give more accurate schema inference but use more memory. Default is 1000. Set to -1 to read all records (may be slow for large files). |
workers |
Number of parallel workers for file conversion via
|
The page column (added by pro_request_jsonl()) is preserved as a regular
column in the Parquet data.
When starting the conversion, a file 00_in.progress is created which is
deleted upon completion.
The function uses DuckDB to read the JSON files and to create the
Apache Parquet files. Each JSON file is converted individually using its own
DuckDB connection, which enables parallel processing via
future.apply::future_lapply().
To ensure consistent schemas across all Parquet files, the function first
infers a unified schema by sampling records from all JSONL files. This
prevents type mismatches (e.g., a column being struct in one file but
string in another) that would cause errors when reading the combined
Parquet dataset.
The function returns the output path invisibly.
Single-step replacement for the two-step
pro_request_jsonl() + pro_request_jsonl_parquet() pipeline.
Reads the JSON files written by pro_request() and converts each one to a
Parquet file using DuckDB, with no intermediate JSONL on disk.
pro_request_parquet( input_json = NULL, output = NULL, add_columns = list(), overwrite = FALSE, verbose = TRUE, progress = TRUE, delete_input = FALSE, sample_size = 1000, workers = NULL, enrich = TRUE, schema = "auto", resume = FALSE, on_error = c("error", "warn", "ignore"), memory_limit = NULL, retry_memory_limit = NULL, compact_parquet = NULL, hive_names = NULL )pro_request_parquet( input_json = NULL, output = NULL, add_columns = list(), overwrite = FALSE, verbose = TRUE, progress = TRUE, delete_input = FALSE, sample_size = 1000, workers = NULL, enrich = TRUE, schema = "auto", resume = FALSE, on_error = c("error", "warn", "ignore"), memory_limit = NULL, retry_memory_limit = NULL, compact_parquet = NULL, hive_names = NULL )
input_json |
Directory of JSON files returned by |
output |
Output directory for the Parquet dataset. |
add_columns |
Named list of scalar constant columns to embed in every
output record (e.g. |
overwrite |
Logical. Overwrite |
verbose |
Logical. Show progress messages. Default |
progress |
Logical. Show a progress bar. Default |
delete_input |
Logical. Delete |
sample_size |
Integer. Number of records per file passed to DuckDB's
|
workers |
Integer. Number of parallel workers.
|
enrich |
Logical. When |
schema |
Controls use of a pre-built baseline schema for type resolution. Possible values:
|
resume |
Logical. When |
on_error |
How to handle files that still fail after the sequential
retry: Before 0.12.0 failures were only |
memory_limit |
DuckDB |
retry_memory_limit |
|
compact_parquet |
|
hive_names |
Character vector of Hive partition keys, one per nesting
level of a list of queries: |
For works entities the function detects the presence of
abstract_inverted_index, authorships, and publication_year in the
inferred schema and, when enrich = TRUE (the default), adds two computed
columns:
abstract - plain text reconstructed from abstract_inverted_index.
citation - "Author (year)" / "A & B (year)" / "A et al. (year)".
Output directory path (invisibly).
pro_request() writes one JSON file per API page. For paginated queries
each file has the structure {"results": [...], "meta": {...}}. For
group-by queries the array field is "group_by". For single-record lookups
the file is a bare JSON object. All three formats are handled automatically.
The subdirectory structure of input_json is preserved, with hive-partition
naming (query=<name>/, query_l2=<name>/, ...) so that Arrow/DuckDB can
read the result as a partitioned dataset. A page column is added to each
record with a value derived from the source filename (or subdirectory for
multi-query inputs).
With compact_parquet, the page files of each query are combined into
files of up to that many records after the conversion (see
pro_compact_parquet()).
pro_request() to download the JSON files,
pro_compact_parquet() to compact an existing dataset,
pro_request_jsonl() and pro_request_jsonl_parquet() for the older
two-step pipeline (now deprecated).
## Not run: pro_request_parquet("my_project/json", "my_project/parquet", compact_parquet = 250000) ## End(Not run)## Not run: pro_request_parquet("my_project/json", "my_project/parquet", compact_parquet = 250000) ## End(Not run)
Makes a minimal API request to verify that the api_key is valid.
pro_validate_credentials(api_key = pro_api_key(), show_credentials = FALSE)pro_validate_credentials(api_key = pro_api_key(), show_credentials = FALSE)
api_key |
API key to validate (character string) or 'NULL'. |
show_credentials |
shows the api_key using 'message()'. USE WITH CAUTION! |
TRUE if credentials work, FALSE otherwise
This function reads a corpus in Apache Parquet format and returns an
ArrowObject representing the corpus which can be fed into a dplyr
pipeline or a tibble which contains all the data.
read_corpus(corpus, return_data = FALSE)read_corpus(corpus, return_data = FALSE)
corpus |
The directory of the Parquet files. |
return_data |
Logical indicating whether to return an |
An ArrowObject representing the corpus or a tibble.
Draw a uniform random sample of n rows from one or more Parquet files
using DuckDB's SQL USING SAMPLE reservoir(n ROWS) clause.
The sampling is performed entirely inside DuckDB, so the full dataset
is never loaded into R.
This is well-suited for large Parquet corpora (e.g. OpenAlex works) where you want a random subset of rows without materialising the whole table.
sample_parquet_n(path, n, seed = NULL, con = NULL, select = NULL)sample_parquet_n(path, n, seed = NULL, con = NULL, select = NULL)
path |
Character scalar. Path or glob pointing to one or more Parquet
files, as understood by DuckDB's |
n |
Integer scalar. Number of rows to sample. If |
seed |
Optional integer scalar. If supplied, a |
con |
Optional |
select |
Optional character vector of column names to return. If
|
The function delegates to the following SQL pattern (simplified):
SELECT [columns]
FROM parquet_scan('path/to/files/*.parquet')
USING SAMPLE reservoir(n ROWS)
[REPEATABLE (seed)]
Using reservoir(n ROWS) gives an exact uniform sample of size
n from all rows in the dataset (unless n exceeds the total
row count, in which case all rows are returned).
Note that the path argument is passed directly to DuckDB's
parquet_scan() function, so you can use:
A single Parquet file:
"works.parquet"
A glob for many files:
"works/*.parquet"
A directory, depending on your DuckDB version/configuration.
When con is NULL, the function creates an in-memory DuckDB
database. If you want to reuse the same DuckDB instance for multiple queries
(for performance reasons or to control pragmas), you can create a DuckDB
connection yourself and pass it via con.
A data.frame with up to n rows, containing a uniform random
sample from the union of all Parquet files matched by path, restricted
to the columns specified in select (or all columns if select is
NULL).
## Not run: # Sample 1,000 rows from a directory of Parquet files sample_df <- sample_parquet_duckdb( path = "spc_corpus/output/chapter_3/corpus/*.parquet", n = 10000L, seed = 1234 ) # Sample only a subset of columns sample_df_small <- sample_parquet_duckdb( path = "spc_corpus/output/chapter_3/corpus/*.parquet", n = 10000L, seed = 1234, select = c("id", "doi", "citation", "author_abbr", "display_name", "ab") ) # Reuse a DuckDB connection for multiple samples con <- DBI::dbConnect(duckdb::duckdb()) on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE) s1 <- sample_parquet_duckdb( path = "openalex_works/*.parquet", n = 500L, seed = 42, con = con ) s2 <- sample_parquet_duckdb( path = "openalex_works/*.parquet", n = 500L, seed = 777, con = con ) ## End(Not run)## Not run: # Sample 1,000 rows from a directory of Parquet files sample_df <- sample_parquet_duckdb( path = "spc_corpus/output/chapter_3/corpus/*.parquet", n = 10000L, seed = 1234 ) # Sample only a subset of columns sample_df_small <- sample_parquet_duckdb( path = "spc_corpus/output/chapter_3/corpus/*.parquet", n = 10000L, seed = 1234, select = c("id", "doi", "citation", "author_abbr", "display_name", "ab") ) # Reuse a DuckDB connection for multiple samples con <- DBI::dbConnect(duckdb::duckdb()) on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE) s1 <- sample_parquet_duckdb( path = "openalex_works/*.parquet", n = 500L, seed = 42, con = con ) s2 <- sample_parquet_duckdb( path = "openalex_works/*.parquet", n = 500L, seed = 777, con = con ) ## End(Not run)