blob: 85f1e8fe5ba2791270fe4e210c043659f91b8f4d [file] [log] [blame]
Marc Kupietza8c40f42025-06-24 15:49:52 +02001#' KorAPQuery class (internal)
Marc Kupietze95108e2019-09-18 13:23:58 +02002#'
Marc Kupietza8c40f42025-06-24 15:49:52 +02003#' Internal class for query state management. Users work with `corpusQuery()`, `fetchAll()`, and `fetchNext()` instead.
Marc Kupietze95108e2019-09-18 13:23:58 +02004#'
Marc Kupietza8c40f42025-06-24 15:49:52 +02005#' @keywords internal
Marc Kupietze95108e2019-09-18 13:23:58 +02006#' @include KorAPConnection.R
Marc Kupietz6dfeed92025-06-03 11:58:06 +02007#' @include logging.R
Marc Kupietzf9129592025-01-26 19:17:54 +01008#' @import httr2
Marc Kupietze95108e2019-09-18 13:23:58 +02009#'
Marc Kupietza6e4ee62021-03-05 09:00:15 +010010#' @include RKorAPClient-package.R
Marc Kupietz5bbc9db2019-08-30 16:30:45 +020011
Marc Kupietze95108e2019-09-18 13:23:58 +020012#' @export
13KorAPQuery <- setClass("KorAPQuery", slots = c(
Marc Kupietzb8972182019-09-20 21:33:46 +020014 "korapConnection",
Marc Kupietze95108e2019-09-18 13:23:58 +020015 "request",
16 "vc",
17 "totalResults",
18 "nextStartIndex",
19 "fields",
20 "requestUrl",
21 "webUIRequestUrl",
22 "apiResponse",
23 "collectedMatches",
Marc Kupietza29f3d42025-07-18 10:14:43 +020024 "hasMoreMatches"
Marc Kupietze95108e2019-09-18 13:23:58 +020025))
Marc Kupietz5bbc9db2019-08-30 16:30:45 +020026
Marc Kupietza8c40f42025-06-24 15:49:52 +020027#' Initialize KorAPQuery object
28#' @keywords internal
Marc Kupietze95108e2019-09-18 13:23:58 +020029#' @param .Object …
Marc Kupietzb8972182019-09-20 21:33:46 +020030#' @param korapConnection KorAPConnection object
Marc Kupietze95108e2019-09-18 13:23:58 +020031#' @param request query part of the request URL
32#' @param vc definition of a virtual corpus
33#' @param totalResults number of hits the query has yielded
34#' @param nextStartIndex at what index to start the next fetch of query results
35#' @param fields what data / metadata fields should be collected
36#' @param requestUrl complete URL of the API request
37#' @param webUIRequestUrl URL of a web frontend request corresponding to the API request
38#' @param apiResponse data-frame representation of the JSON response of the API request
Marc Kupietz7776dec2019-09-27 16:59:02 +020039#' @param hasMoreMatches logical that signals if more query results can be fetched
Marc Kupietze95108e2019-09-18 13:23:58 +020040#' @param collectedMatches matches already fetched from the KorAP-API-server
Marc Kupietz97a1bca2019-10-04 22:52:09 +020041#'
42#' @importFrom tibble tibble
Marc Kupietze95108e2019-09-18 13:23:58 +020043#' @export
Marc Kupietzd8851222025-05-01 10:57:19 +020044setMethod(
45 "initialize", "KorAPQuery",
46 function(.Object, korapConnection = NULL, request = NULL, vc = "", totalResults = 0, nextStartIndex = 0, fields = c(
47 "corpusSigle", "textSigle", "pubDate", "pubPlace",
48 "availability", "textClass", "snippet", "tokens"
49 ),
Marc Kupietza29f3d42025-07-18 10:14:43 +020050 requestUrl = "", webUIRequestUrl = "", apiResponse = NULL, hasMoreMatches = FALSE, collectedMatches = NULL) {
Marc Kupietzd8851222025-05-01 10:57:19 +020051 .Object <- callNextMethod()
52 .Object@korapConnection <- korapConnection
53 .Object@request <- request
54 .Object@vc <- vc
55 .Object@totalResults <- totalResults
56 .Object@nextStartIndex <- nextStartIndex
57 .Object@fields <- fields
58 .Object@requestUrl <- requestUrl
59 .Object@webUIRequestUrl <- webUIRequestUrl
60 .Object@apiResponse <- apiResponse
61 .Object@hasMoreMatches <- hasMoreMatches
62 .Object@collectedMatches <- collectedMatches
63 .Object
64 }
65)
Marc Kupietz632cbd42019-09-06 16:04:51 +020066
Marc Kupietzd8851222025-05-01 10:57:19 +020067setGeneric("corpusQuery", function(kco, ...) standardGeneric("corpusQuery"))
68setGeneric("fetchAll", function(kqo, ...) standardGeneric("fetchAll"))
69setGeneric("fetchNext", function(kqo, ...) standardGeneric("fetchNext"))
70setGeneric("fetchRest", function(kqo, ...) standardGeneric("fetchRest"))
Marc Kupietz0af75932025-09-09 18:14:16 +020071setGeneric(
72 "fetchAnnotations",
73 function(kqo,
74 foundry = "tt",
75 overwrite = FALSE,
76 verbose = kqo@korapConnection@verbose) standardGeneric("fetchAnnotations")
77)
Marc Kupietzd8851222025-05-01 10:57:19 +020078setGeneric("frequencyQuery", function(kco, ...) standardGeneric("frequencyQuery"))
Marc Kupietze95108e2019-09-18 13:23:58 +020079
80maxResultsPerPage <- 50
Marc Kupietz62da2b52019-09-12 17:43:34 +020081
Marc Kupietz4de53ec2019-10-04 09:12:00 +020082## quiets concerns of R CMD check re: the .'s that appear in pipelines
Marc Kupietzef1ef4a2025-02-19 12:12:40 +010083utils::globalVariables(c("."))
Marc Kupietz632cbd42019-09-06 16:04:51 +020084
Marc Kupietza8c40f42025-06-24 15:49:52 +020085#' Search corpus for query terms
Marc Kupietzdbd431a2021-08-29 12:17:45 +020086#'
Marc Kupietz67edcb52021-09-20 21:54:24 +020087#' **`corpusQuery`** performs a corpus query via a connection to a KorAP-API-server
Marc Kupietze95108e2019-09-18 13:23:58 +020088#'
Marc Kupietza8c40f42025-06-24 15:49:52 +020089#' @family corpus search functions
Marc Kupietzdbd431a2021-08-29 12:17:45 +020090#' @aliases corpusQuery
91#'
92#' @importFrom urltools url_encode
93#' @importFrom purrr pmap
Marc Kupietzea34b812025-06-25 15:49:00 +020094#' @importFrom dplyr bind_rows group_by
Marc Kupietzdbd431a2021-08-29 12:17:45 +020095#'
Marc Kupietz617266d2025-02-27 10:43:07 +010096#' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()`
Marc Kupietz67edcb52021-09-20 21:54:24 +020097#' @param query string that contains the corpus query. The query language depends on the `ql` parameter. Either `query` must be provided or `KorAPUrl`.
Marc Kupietz632cbd42019-09-06 16:04:51 +020098#' @param vc string describing the virtual corpus in which the query should be performed. An empty string (default) means the whole corpus, as far as it is license-wise accessible.
Marc Kupietz67edcb52021-09-20 21:54:24 +020099#' @param KorAPUrl instead of providing the query and vc string parameters, you can also simply copy a KorAP query URL from your browser and use it here (and in `KorAPConnection`) to provide all necessary information for the query.
Marc Kupietz132f0052023-04-16 14:23:05 +0200100#' @param metadataOnly logical that determines whether queries should return only metadata without any snippets. This can also be useful to prevent access rewrites. Note that the default value is TRUE.
101#' If you want your corpus queries to return not only metadata, but also KWICS, you need to authorize
102#' your RKorAPClient application as explained in the
103#' [authorization section](https://github.com/KorAP/RKorAPClient#authorization)
104#' of the RKorAPClient Readme on GitHub and set the `metadataOnly` parameter to
105#' `FALSE`.
Marc Kupietz67edcb52021-09-20 21:54:24 +0200106#' @param ql string to choose the query language (see [section on Query Parameters](https://github.com/KorAP/Kustvakt/wiki/Service:-Search-GET#user-content-parameters) in the Kustvakt-Wiki for possible values.
Marc Kupietz1623fe82025-06-24 16:31:46 +0200107#' @param fields character vector specifying which metadata fields to retrieve for each match.
108#' Available fields depend on the corpus. For DeReKo (German Reference Corpus), possible fields include:
109#' \describe{
110#' \item{**Text identification**:}{`textSigle`, `docSigle`, `corpusSigle` - hierarchical text identifiers}
111#' \item{**Publication info**:}{`author`, `editor`, `title`, `docTitle`, `corpusTitle` - authorship and titles}
112#' \item{**Temporal data**:}{`pubDate`, `creationDate` - when text was published/created}
113#' \item{**Publication details**:}{`pubPlace`, `publisher`, `reference` - where/how published}
114#' \item{**Text classification**:}{`textClass`, `textType`, `textTypeArt`, `textDomain`, `textColumn` - topic domain, genre, text type and column}
115#' \item{**Adminstrative and technical info**:}{`corpusEditor`, `availability`, `language`, `foundries` - access rights and annotations}
116#' \item{**Content data**:}{`snippet`, `tokens`, `tokenSource`, `externalLink` - actual text content, tokenization, and link to source text}
117#' \item{**System data**:}{`indexCreationDate`, `indexLastModified` - corpus indexing info}
118#' }
119#' Use `c("textSigle", "pubDate", "author")` to retrieve multiple fields.
120#' Default fields provide basic text identification and publication metadata. The actual text content (`snippet` and `tokens`) are activated by default if `metadataOnly` is set to `FALSE`.
Marc Kupietz43a6ade2020-02-18 17:01:44 +0100121#' @param accessRewriteFatal abort if query or given vc had to be rewritten due to insufficient rights (not yet implemented).
Marc Kupietz25aebc32019-09-16 18:40:50 +0200122#' @param verbose print some info
Marc Kupietz4de53ec2019-10-04 09:12:00 +0200123#' @param as.df return result as data frame instead of as S4 object?
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200124#' @param expand logical that decides if `query` and `vc` parameters are expanded to all of their combinations. Defaults to `TRUE`, iff `query` and `vc` have different lengths
Marc Kupietzd9b2fd72023-04-17 19:08:50 +0200125#' @param context string that specifies the size of the left and the right context returned in `snippet`
126#' (provided that `metadataOnly` is set to `false` and that the necessary access right are met).
127#' The format of the context size specifcation (e.g. `3-token,3-token`) is described in the [Service: Search GET documentation of the Kustvakt Wiki](https://github.com/KorAP/Kustvakt/wiki/Service:-Search-GET).
128#' If the parameter is not set, the default context size secification of the KorAP server instance will be used.
129#' Note that you cannot overrule the maximum context size set in the KorAP server instance,
130#' as this is typically legally motivated.
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200131#' @return Depending on the `as.df` parameter, a tibble or a [KorAPQuery()] object that, among other information, contains the total number of results in `@totalResults`. The resulting object can be used to fetch all query results (with [fetchAll()]) or the next page of results (with [fetchNext()]).
Marc Kupietz67edcb52021-09-20 21:54:24 +0200132#' A corresponding URL to be used within a web browser is contained in `@webUIRequestUrl`
133#' Please make sure to check `$collection$rewrites` to see if any unforeseen access rewrites of the query's virtual corpus had to be performed.
Marc Kupietz632cbd42019-09-06 16:04:51 +0200134#'
135#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200136#' \dontrun{
137#'
Marc Kupietz1623fe82025-06-24 16:31:46 +0200138#' # Fetch basic metadata for "Ameisenplage"
Marc Kupietzd3526422025-06-25 09:16:15 +0200139#' KorAPConnection() |>
140#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200141#' fetchAll()
Marc Kupietz1623fe82025-06-24 16:31:46 +0200142#'
143#' # Fetch specific metadata fields for bibliographic analysis
Marc Kupietzd3526422025-06-25 09:16:15 +0200144#' query <- KorAPConnection() |>
Marc Kupietz1623fe82025-06-24 16:31:46 +0200145#' corpusQuery("Ameisenplage",
146#' fields = c("textSigle", "author", "title", "pubDate", "pubPlace", "textType"))
147#' results <- fetchAll(query)
148#' results@collectedMatches
Marc Kupietz657d8e72020-02-25 18:31:50 +0100149#' }
Marc Kupietz3c531f62019-09-13 12:17:24 +0200150#'
Marc Kupietz6ae76052021-09-21 10:34:00 +0200151#' \dontrun{
152#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200153#' # Use the copy of a KorAP-web-frontend URL for an API query of "Ameise" in a virtual corpus
154#' # and show the number of query hits (but don't fetch them).
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200155#'
Marc Kupietzd3526422025-06-25 09:16:15 +0200156#' KorAPConnection(verbose = TRUE) |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200157#' corpusQuery(
158#' KorAPUrl =
159#' "https://korap.ids-mannheim.de/?q=Ameise&cq=pubDate+since+2017&ql=poliqarp"
160#' )
Marc Kupietz6ae76052021-09-21 10:34:00 +0200161#' }
162#'
163#' \dontrun{
Marc Kupietz3c531f62019-09-13 12:17:24 +0200164#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200165#' # Plot the time/frequency curve of "Ameisenplage"
Marc Kupietzd3526422025-06-25 09:16:15 +0200166#' KorAPConnection(verbose = TRUE) |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200167#' {
168#' . ->> kco
Marc Kupietzd3526422025-06-25 09:16:15 +0200169#' } |>
170#' corpusQuery("Ameisenplage") |>
171#' fetchAll() |>
172#' slot("collectedMatches") |>
173#' mutate(year = lubridate::year(pubDate)) |>
174#' dplyr::select(year) |>
175#' group_by(year) |>
176#' summarise(Count = dplyr::n()) |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200177#' mutate(Freq = mapply(function(f, y) {
178#' f / corpusStats(kco, paste("pubDate in", y))@tokens
Marc Kupietzd3526422025-06-25 09:16:15 +0200179#' }, Count, year)) |>
180#' dplyr::select(-Count) |>
181#' complete(year = min(year):max(year), fill = list(Freq = 0)) |>
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200182#' plot(type = "l")
Marc Kupietz05b22772020-02-18 21:58:42 +0100183#' }
Marc Kupietz67edcb52021-09-20 21:54:24 +0200184#' @seealso [KorAPConnection()], [fetchNext()], [fetchRest()], [fetchAll()], [corpusStats()]
Marc Kupietz632cbd42019-09-06 16:04:51 +0200185#'
186#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200187#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz632cbd42019-09-06 16:04:51 +0200188#'
189#' @export
Marc Kupietzd8851222025-05-01 10:57:19 +0200190setMethod(
191 "corpusQuery", "KorAPConnection",
192 function(kco,
193 query = if (missing(KorAPUrl)) {
194 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
195 } else {
196 httr2::url_parse(KorAPUrl)$query$q
197 },
198 vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq,
199 KorAPUrl,
200 metadataOnly = TRUE,
201 ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql,
202 fields = c(
203 "corpusSigle",
204 "textSigle",
205 "pubDate",
206 "pubPlace",
207 "availability",
208 "textClass",
209 "snippet",
210 "tokens"
211 ),
212 accessRewriteFatal = TRUE,
213 verbose = kco@verbose,
214 expand = length(vc) != length(query),
215 as.df = FALSE,
216 context = NULL) {
217 if (length(query) > 1 || length(vc) > 1) {
Marc Kupietzf632fe32026-09-08 07:58:46 +0200218 # expand_grid() and tibble() drop the names of vc, so the labels the
219 # caller gave their virtual corpora are carried along as a column
220 vcLabel <- vcLabels(vc)
Marc Kupietzd8851222025-05-01 10:57:19 +0200221 grid <- if (expand) expand_grid(query = query, vc = vc) else tibble(query = query, vc = vc)
Marc Kupietzf632fe32026-09-08 07:58:46 +0200222 if (!is.null(vcLabel)) {
223 grid$label <- if (expand) rep(vcLabel, times = length(query)) else vcLabel
224 }
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200225
226 # Initialize timing variables for ETA calculation
227 total_queries <- nrow(grid)
228 current_query <- 0
229 start_time <- Sys.time()
230
Marc Kupietzf632fe32026-09-08 07:58:46 +0200231 results <- purrr::pmap(grid, function(query, vc, label = NULL, ...) {
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200232 current_query <<- current_query + 1
233
234 # Execute the single query directly (avoiding recursive call)
235 contentFields <- c("snippet", "tokens")
236 query_fields <- fields
237 if (metadataOnly) {
238 query_fields <- query_fields[!query_fields %in% contentFields]
239 }
240 if (!"textSigle" %in% query_fields) {
241 query_fields <- c(query_fields, "textSigle")
242 }
243 request <-
244 paste0(
245 "?q=",
246 url_encode(enc2utf8(query)),
247 ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""),
248 ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""),
249 ifelse(!metadataOnly, "&show-tokens=true", ""),
250 "&ql=", ql
251 )
252 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
253 requestUrl <- paste0(
254 kco@apiUrl,
255 "search",
256 request,
257 "&fields=",
258 paste(query_fields, collapse = ","),
259 if (metadataOnly) "&access-rewrite-disabled=true" else ""
260 )
261
262 # Show individual query progress
263 log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"", sep = "")
Marc Kupietz10eff992026-09-14 08:31:41 +0200264 queryStart <- Sys.time()
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200265 res <- apiCall(kco, paste0(requestUrl, "&count=0"))
Marc Kupietz10eff992026-09-14 08:31:41 +0200266 queryDuration <- as.numeric(difftime(Sys.time(), queryStart, units = "secs"))
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200267 if (is.null(res)) {
Marc Kupietz10eff992026-09-14 08:31:41 +0200268 log_info(verbose, ": API call failed after ", sprintf("%.1f", queryDuration), "s\n")
269 warning("The request for query \u201c", query, "\u201d failed; the reported results are unreliable.", call. = FALSE)
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200270 totalResults <- 0
271 } else {
272 totalResults <- as.integer(res$meta$totalResults)
273 log_info(verbose, ": ", totalResults, " hits")
274 if (!is.null(res$meta$cached)) {
275 log_info(verbose, " [cached]")
Marc Kupietz10eff992026-09-14 08:31:41 +0200276 }
277 log_info(verbose, ", took ", sprintf("%.1f", queryDuration), "s")
278 if (!is.null(res$meta$timeExceeded)) {
279 warning(
280 "The query \u201c", query, "\u201d was cut short by the KorAP server ",
281 "(timeExceeded); the reported results are incomplete.",
282 call. = FALSE
283 )
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200284 }
Marc Kupietz365660e2025-06-25 15:09:55 +0200285
286 # Calculate and display ETA information on the same line if verbose and we have more than one query
287 if (verbose && total_queries > 1) {
288 eta_info <- calculate_eta(current_query, total_queries, start_time)
289 if (eta_info != "") {
290 elapsed_time <- as.numeric(difftime(Sys.time(), start_time, units = "secs"))
291 avg_time_per_query <- elapsed_time / current_query
292
293 # Add ETA info to the same line - remove the leading ". " for cleaner formatting
294 clean_eta_info <- sub("^\\. ", ". ", eta_info)
295 log_info(verbose, clean_eta_info)
296 }
297 }
298
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200299 log_info(verbose, "\n")
300 }
301
302 result <- data.frame(
303 query = query,
304 totalResults = totalResults,
305 vc = vc,
Marc Kupietz10eff992026-09-14 08:31:41 +0200306 queryDuration = queryDuration,
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200307 webUIRequestUrl = webUIRequestUrl,
308 stringsAsFactors = FALSE
309 )
Marc Kupietzf632fe32026-09-08 07:58:46 +0200310 if (!is.null(label)) {
311 result <- tibble::add_column(result, label = label, .after = "vc")
312 }
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200313
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200314 return(result)
315 })
316
317 results %>% bind_rows()
Marc Kupietzd8851222025-05-01 10:57:19 +0200318 } else {
Marc Kupietz2078bde2023-08-27 16:46:15 +0200319 contentFields <- c("snippet", "tokens")
Marc Kupietza96537f2019-11-09 23:07:44 +0100320 if (metadataOnly) {
321 fields <- fields[!fields %in% contentFields]
322 }
Marc Kupietz80dc6432025-02-07 16:57:40 +0100323 if (!"textSigle" %in% fields) {
324 fields <- c(fields, "textSigle")
325 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100326 request <-
Marc Kupietzd8851222025-05-01 10:57:19 +0200327 paste0(
328 "?q=",
329 url_encode(enc2utf8(query)),
330 ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""),
331 ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""),
332 ifelse(!metadataOnly, "&show-tokens=true", ""),
333 "&ql=", ql
334 )
Marc Kupietza96537f2019-11-09 23:07:44 +0100335 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
336 requestUrl <- paste0(
337 kco@apiUrl,
Marc Kupietzd8851222025-05-01 10:57:19 +0200338 "search",
Marc Kupietza96537f2019-11-09 23:07:44 +0100339 request,
Marc Kupietzd8851222025-05-01 10:57:19 +0200340 "&fields=",
Marc Kupietza96537f2019-11-09 23:07:44 +0100341 paste(fields, collapse = ","),
Marc Kupietzd8851222025-05-01 10:57:19 +0200342 if (metadataOnly) "&access-rewrite-disabled=true" else ""
Marc Kupietza96537f2019-11-09 23:07:44 +0100343 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200344 log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"",
345 sep =
346 ""
347 )
Marc Kupietz10eff992026-09-14 08:31:41 +0200348 queryStart <- Sys.time()
Marc Kupietzd8851222025-05-01 10:57:19 +0200349 res <- apiCall(kco, paste0(requestUrl, "&count=0"))
Marc Kupietz10eff992026-09-14 08:31:41 +0200350 queryDuration <- as.numeric(difftime(Sys.time(), queryStart, units = "secs"))
Marc Kupietza4675722022-02-23 23:55:15 +0100351 if (is.null(res)) {
Marc Kupietza4675722022-02-23 23:55:15 +0100352 message("API call failed.")
Marc Kupietz10eff992026-09-14 08:31:41 +0200353 warning("The request for query \u201c", query, "\u201d failed; the reported results are unreliable.", call. = FALSE)
Marc Kupietza4675722022-02-23 23:55:15 +0100354 totalResults <- 0
355 } else {
Marc Kupietzd8851222025-05-01 10:57:19 +0200356 totalResults <- as.integer(res$meta$totalResults)
Marc Kupietza47d1502023-04-18 15:26:47 +0200357 log_info(verbose, ": ", totalResults, " hits")
Marc Kupietzd8851222025-05-01 10:57:19 +0200358 if (!is.null(res$meta$cached)) {
Marc Kupietz10eff992026-09-14 08:31:41 +0200359 log_info(verbose, " [cached]")
Marc Kupietzd8851222025-05-01 10:57:19 +0200360 }
Marc Kupietz10eff992026-09-14 08:31:41 +0200361 log_info(verbose, ", took ", sprintf("%.1f", queryDuration), "s")
362 if (!is.null(res$meta$timeExceeded)) {
363 warning(
364 "The query \u201c", query, "\u201d was cut short by the KorAP server ",
365 "(timeExceeded); the reported results are incomplete.",
366 call. = FALSE
367 )
368 }
369 log_info(verbose, "\n")
Marc Kupietza4675722022-02-23 23:55:15 +0100370 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200371 if (as.df) {
Marc Kupietza96537f2019-11-09 23:07:44 +0100372 data.frame(
373 query = query,
Marc Kupietza4675722022-02-23 23:55:15 +0100374 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100375 vc = vc,
Marc Kupietz10eff992026-09-14 08:31:41 +0200376 queryDuration = queryDuration,
Marc Kupietza96537f2019-11-09 23:07:44 +0100377 webUIRequestUrl = webUIRequestUrl,
378 stringsAsFactors = FALSE
379 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200380 } else {
Marc Kupietza96537f2019-11-09 23:07:44 +0100381 KorAPQuery(
382 korapConnection = kco,
383 nextStartIndex = 0,
384 fields = fields,
385 requestUrl = requestUrl,
386 request = request,
Marc Kupietza4675722022-02-23 23:55:15 +0100387 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100388 vc = vc,
389 apiResponse = res,
390 webUIRequestUrl = webUIRequestUrl,
Marc Kupietza4675722022-02-23 23:55:15 +0100391 hasMoreMatches = (totalResults > 0),
Marc Kupietza96537f2019-11-09 23:07:44 +0100392 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200393 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100394 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200395 }
396)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200397
Marc Kupietz05a60792024-12-07 16:23:31 +0100398#' @importFrom purrr map
399repair_data_strcuture <- function(x) {
Marc Kupietzd8851222025-05-01 10:57:19 +0200400 if (is.list(x)) {
401 as.character(purrr::map(x, ~ if (length(.x) > 1) {
Marc Kupietz05a60792024-12-07 16:23:31 +0100402 paste(.x, collapse = " ")
403 } else {
404 .x
405 }))
Marc Kupietzd8851222025-05-01 10:57:19 +0200406 } else {
Marc Kupietz05a60792024-12-07 16:23:31 +0100407 ifelse(is.na(x), "", x)
Marc Kupietzd8851222025-05-01 10:57:19 +0200408 }
Marc Kupietz05a60792024-12-07 16:23:31 +0100409}
410
Marc Kupietz62da2b52019-09-12 17:43:34 +0200411#' Fetch the next bunch of results of a KorAP query.
Marc Kupietze95108e2019-09-18 13:23:58 +0200412#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200413#' **`fetchNext`** fetches the next bunch of results of a KorAP query.
Marc Kupietz3f575282019-10-04 14:46:04 +0200414#'
Marc Kupietza8c40f42025-06-24 15:49:52 +0200415#' @family corpus search functions
416#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200417#' @param kqo object obtained from [corpusQuery()]
Marc Kupietz62da2b52019-09-12 17:43:34 +0200418#' @param offset start offset for query results to fetch
419#' @param maxFetch maximum number of query results to fetch
Marc Kupietz25aebc32019-09-16 18:40:50 +0200420#' @param verbose print progress information if true
Marc Kupietz67edcb52021-09-20 21:54:24 +0200421#' @param randomizePageOrder fetch result pages in pseudo random order if true. Use [set.seed()] to set seed for reproducible results.
422#' @return The `kqo` input object with updated slots `collectedMatches`, `apiResponse`, `nextStartIndex`, `hasMoreMatches`
Marc Kupietz62da2b52019-09-12 17:43:34 +0200423#'
Marc Kupietz05b22772020-02-18 21:58:42 +0100424#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200425#' \dontrun{
426#'
Marc Kupietzd3526422025-06-25 09:16:15 +0200427#' q <- KorAPConnection() |>
428#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200429#' fetchNext()
Marc Kupietz05b22772020-02-18 21:58:42 +0100430#' q@collectedMatches
Marc Kupietz657d8e72020-02-25 18:31:50 +0100431#' }
Marc Kupietz05b22772020-02-18 21:58:42 +0100432#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200433#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200434#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz62da2b52019-09-12 17:43:34 +0200435#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200436#' @aliases fetchNext
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200437#' @importFrom dplyr rowwise mutate bind_rows select summarise n select
Marc Kupietzf4881122024-12-17 14:55:39 +0100438#' @importFrom tibble enframe add_column
439#' @importFrom stringr word
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200440#' @importFrom tidyr unnest unchop pivot_wider
441#' @importFrom purrr map
Marc Kupietz632cbd42019-09-06 16:04:51 +0200442#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200443setMethod("fetchNext", "KorAPQuery", function(kqo,
444 offset = kqo@nextStartIndex,
445 maxFetch = maxResultsPerPage,
446 verbose = kqo@korapConnection@verbose,
447 randomizePageOrder = FALSE) {
Marc Kupietza7a8f1b2024-12-18 15:56:19 +0100448 # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
Marc Kupietzd8851222025-05-01 10:57:19 +0200449 results <- key <- name <- tmp_positions <- 0
Marc Kupietza7a8f1b2024-12-18 15:56:19 +0100450
Marc Kupietze95108e2019-09-18 13:23:58 +0200451 if (kqo@totalResults == 0 || offset >= kqo@totalResults) {
452 return(kqo)
Marc Kupietz62da2b52019-09-12 17:43:34 +0200453 }
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200454 use_korap_api <- Sys.getenv("USE_KORAP_API", unset = NA)
Marc Kupietz623d7122025-05-25 12:46:12 +0200455 # Calculate the initial page number (not used directly - keeping for reference)
Marc Kupietze95108e2019-09-18 13:23:58 +0200456 collectedMatches <- kqo@collectedMatches
Marc Kupietz62da2b52019-09-12 17:43:34 +0200457
Marc Kupietz24799fd2025-06-25 14:15:36 +0200458 # Track start time for ETA calculation
459 start_time <- Sys.time()
460
Marc Kupietz623d7122025-05-25 12:46:12 +0200461 # For randomized page order, generate a list of randomized page indices
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200462 if (randomizePageOrder) {
Marc Kupietz623d7122025-05-25 12:46:12 +0200463 # Calculate how many pages we need to fetch based on maxFetch
464 total_pages_to_fetch <- if (!is.na(maxFetch)) {
465 # Either limited by maxFetch or total results, whichever is smaller
466 min(ceiling(maxFetch / maxResultsPerPage), ceiling(kqo@totalResults / maxResultsPerPage))
467 } else {
468 # All pages
469 ceiling(kqo@totalResults / maxResultsPerPage)
470 }
471
472 # Generate randomized page indices (0-based for API)
473 pages <- sample.int(ceiling(kqo@totalResults / maxResultsPerPage), total_pages_to_fetch) - 1
474 page_index <- 1 # Index to track which page in the randomized list we're on
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200475 }
476
Marc Kupietzd8851222025-05-01 10:57:19 +0200477 if (is.null(collectedMatches)) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200478 collectedMatches <- data.frame()
479 }
Marc Kupietz623d7122025-05-25 12:46:12 +0200480
481 # Initialize the page counter properly based on nextStartIndex and any previously fetched results
482 # We add 1 to make it 1-based for display purposes since users expect page numbers to start from 1
483 # For first call, this will be 1, for subsequent calls, it will reflect our actual position
484 current_page_number <- ceiling(offset / maxResultsPerPage) + 1
485
486 # For sequential fetches, keep track of which global page we're on
487 # This is important for correctly showing page numbers in subsequent fetchNext calls
488 page_count_start <- current_page_number
489
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200490 repeat {
Marc Kupietz623d7122025-05-25 12:46:12 +0200491 # Determine which page to fetch next
492 if (randomizePageOrder) {
493 # In randomized mode, get the page from our randomized list using the page_index
494 # Make sure we don't exceed the array bounds
495 if (page_index > length(pages)) {
496 break # No more pages to fetch in randomized mode
497 }
498 current_offset_page <- pages[page_index]
499 # For display purposes in randomized mode, show which page out of the total we're fetching
500 display_page_number <- page_index
501 } else {
502 # In sequential mode, use the current_page_number to calculate the offset
503 current_offset_page <- (current_page_number - 1)
504 display_page_number <- current_page_number
505 }
506
507 # Calculate the actual offset in tokens
508 currentOffset <- current_offset_page * maxResultsPerPage
509
Marc Kupietzef0e9392025-06-18 12:21:49 +0200510 # Build the query with the appropriate count and offset using httr2
511 count_param <- min(if (!is.na(maxFetch)) maxFetch - results else maxResultsPerPage, maxResultsPerPage)
Marc Kupietzecc86702025-06-24 12:12:51 +0200512
Marc Kupietzef0e9392025-06-18 12:21:49 +0200513 # Parse existing URL to preserve all query parameters
514 parsed_url <- httr2::url_parse(kqo@requestUrl)
515 existing_query <- parsed_url$query
Marc Kupietzecc86702025-06-24 12:12:51 +0200516
Marc Kupietzef0e9392025-06-18 12:21:49 +0200517 # Add/update count and offset parameters
518 existing_query$count <- count_param
519 existing_query$offset <- currentOffset
Marc Kupietzecc86702025-06-24 12:12:51 +0200520
Marc Kupietzef0e9392025-06-18 12:21:49 +0200521 # Rebuild the URL with all parameters
522 query <- httr2::url_modify(kqo@requestUrl, query = existing_query)
Marc Kupietz68170952021-06-30 09:37:21 +0200523 res <- apiCall(kqo@korapConnection, query)
524 if (length(res$matches) == 0) {
525 break
526 }
527
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200528 if ("fields" %in% colnames(res$matches) && (is.na(use_korap_api) || as.numeric(use_korap_api) >= 1.0)) {
Marc Kupietz16ccf112025-01-26 13:25:27 +0100529 log_info(verbose, "Using fields API: ")
Marc Kupietz05a60792024-12-07 16:23:31 +0100530 currentMatches <- res$matches$fields %>%
531 purrr::map(~ mutate(.x, value = repair_data_strcuture(value))) %>%
532 tibble::enframe() %>%
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200533 tidyr::unnest(cols = value) %>%
534 tidyr::pivot_wider(names_from = key, id_cols = name, names_repair = "unique") %>%
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200535 dplyr::select(-name)
Marc Kupietzd8851222025-05-01 10:57:19 +0200536 if ("snippet" %in% colnames(res$matches)) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200537 currentMatches$snippet <- res$matches$snippet
538 }
Marc Kupietz3cd2c6c2025-01-08 20:35:39 +0100539 if ("tokens" %in% colnames(res$matches)) {
540 currentMatches$tokens <- res$matches$tokens
541 }
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200542 } else {
543 currentMatches <- res$matches
544 }
545
Marc Kupietze95108e2019-09-18 13:23:58 +0200546 for (field in kqo@fields) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200547 if (!field %in% colnames(currentMatches)) {
548 currentMatches[, field] <- NA
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200549 }
550 }
Marc Kupietzf4881122024-12-17 14:55:39 +0100551 currentMatches <- currentMatches %>%
552 select(kqo@fields) %>%
553 mutate(
Marc Kupietzff712a92025-07-18 09:07:23 +0200554 matchID = res$matches$matchID,
Marc Kupietz0447da02025-01-08 20:51:09 +0100555 tmp_positions = gsub(".*-p(\\d+)-(\\d+).*", "\\1 \\2", res$matches$matchID),
Marc Kupietzf4881122024-12-17 14:55:39 +0100556 matchStart = as.integer(stringr::word(tmp_positions, 1)),
557 matchEnd = as.integer(stringr::word(tmp_positions, 2)) - 1
558 ) %>%
559 select(-tmp_positions)
560
Marc Kupietz62da2b52019-09-12 17:43:34 +0200561 if (!is.list(collectedMatches)) {
562 collectedMatches <- currentMatches
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200563 } else {
Marc Kupietz2078bde2023-08-27 16:46:15 +0200564 collectedMatches <- bind_rows(collectedMatches, currentMatches)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200565 }
Marc Kupietzae9b6172025-05-02 15:50:01 +0200566
Marc Kupietz623d7122025-05-25 12:46:12 +0200567 # Get the actual items per page from the API response
568 # We now consistently use maxResultsPerPage instead
Marc Kupietzacbaab02025-05-01 10:56:35 +0200569
Marc Kupietz623d7122025-05-25 12:46:12 +0200570 # Calculate total pages consistently using fixed maxResultsPerPage
571 # This ensures consistent page counting across the function
572 total_pages <- ceiling(kqo@totalResults / maxResultsPerPage)
573
Marc Kupietz24799fd2025-06-25 14:15:36 +0200574 # Calculate ETA using the centralized function from logging.R
575 current_page <- if (randomizePageOrder) page_index else display_page_number
576 total_pages_to_fetch <- if (!is.na(maxFetch)) {
577 # Account for offset - we can only fetch from the remaining results after offset
578 remaining_results_after_offset <- max(0, kqo@totalResults - offset)
579 min(ceiling(maxFetch / maxResultsPerPage), ceiling(remaining_results_after_offset / maxResultsPerPage))
580 } else {
581 total_pages
582 }
Marc Kupietz365660e2025-06-25 15:09:55 +0200583
Marc Kupietz24799fd2025-06-25 14:15:36 +0200584 eta_info <- calculate_eta(current_page, total_pages_to_fetch, start_time)
Marc Kupietz365660e2025-06-25 15:09:55 +0200585
Marc Kupietz24799fd2025-06-25 14:15:36 +0200586 # Extract timing information for display
Marc Kupietzae9b6172025-05-02 15:50:01 +0200587 time_per_page <- NA
Marc Kupietzae9b6172025-05-02 15:50:01 +0200588 if (!is.null(res$meta$benchmark) && is.character(res$meta$benchmark)) {
Marc Kupietzae9b6172025-05-02 15:50:01 +0200589 time_per_page <- suppressWarnings(as.numeric(sub("s", "", res$meta$benchmark)))
Marc Kupietzacbaab02025-05-01 10:56:35 +0200590 }
591
Marc Kupietz623d7122025-05-25 12:46:12 +0200592 # Create the page display string with proper formatting
Marc Kupietzacbaab02025-05-01 10:56:35 +0200593
Marc Kupietz623d7122025-05-25 12:46:12 +0200594 # For global page tracking, calculate the absolute page number
595 actual_display_number <- if (randomizePageOrder) {
596 current_offset_page + 1 # In randomized mode, this is the actual page (0-based + 1)
597 } else {
598 # In sequential mode, the absolute page number is the actual offset page + 1 (to make it 1-based)
599 current_offset_page + 1
600 }
601
602 # For subsequent calls to fetchNext, we need to calculate the correct page numbers
603 # based on the current batch being fetched
604
605 # For each call to fetchNext, we want to show 1/2, 2/2 (not 3/4, 4/4)
606 # Simply count from 1 within the current batch
607
608 # The relative page number is simply the current position in this batch
609 if (randomizePageOrder) {
610 relative_page_number <- page_index # In randomized mode, we start from 1 in each batch
611 } else {
612 relative_page_number <- display_page_number - (page_count_start - 1)
613 }
614
615 # How many pages will we fetch in this batch?
Marc Kupietz021663d2025-06-18 17:49:22 +0200616 # If maxFetch is specified, calculate the total pages for this fetch operation
Marc Kupietz623d7122025-05-25 12:46:12 +0200617 pages_in_this_batch <- if (!is.na(maxFetch)) {
Marc Kupietz021663d2025-06-18 17:49:22 +0200618 # Account for offset - we can only fetch from the remaining results after offset
619 remaining_results_after_offset <- max(0, kqo@totalResults - offset)
620 min(ceiling(maxFetch / maxResultsPerPage), ceiling(remaining_results_after_offset / maxResultsPerPage))
Marc Kupietz623d7122025-05-25 12:46:12 +0200621 } else {
622 # Otherwise fetch all remaining pages
623 total_pages - page_count_start + 1
624 }
625
626 # The total pages to be shown in this batch
627 batch_total_pages <- pages_in_this_batch
628
629 page_display <- paste0(
630 "Retrieved page ",
631 sprintf(paste0("%", nchar(batch_total_pages), "d"), relative_page_number),
632 "/",
633 sprintf("%d", batch_total_pages)
634 )
635
636 # If randomized, also show which actual page we fetched
637 if (randomizePageOrder) {
638 # Determine the maximum width needed for page numbers (based on total pages)
639 # This ensures consistent alignment
640 max_page_width <- nchar(as.character(total_pages))
641 # Add the actual page number that was fetched (0-based + 1 for display) with proper padding
Marc Kupietz7638ca42025-05-25 13:18:16 +0200642 page_display <- paste0(
643 page_display,
644 sprintf(" (actual page %*d)", max_page_width, current_offset_page + 1)
645 )
Marc Kupietz623d7122025-05-25 12:46:12 +0200646 }
647 # Always show the absolute page number and total pages (for clarity)
648 else {
649 # Show the absolute page number (out of total possible pages)
650 page_display <- paste0(page_display, sprintf(
651 " (page %d of %d total)",
652 actual_display_number, total_pages
653 ))
654 }
655
656 # Add caching or timing information
657 if (!is.null(res$meta$cached)) {
658 page_display <- paste0(page_display, " [cached]")
659 } else {
660 page_display <- paste0(
661 page_display,
662 " in ",
663 if (!is.na(time_per_page)) sprintf("%4.1f", time_per_page) else "?",
Marc Kupietz24799fd2025-06-25 14:15:36 +0200664 "s",
665 eta_info
Marc Kupietz623d7122025-05-25 12:46:12 +0200666 )
667 }
668
669 log_info(verbose, paste0(page_display, "\n"))
670
671 # Increment the appropriate counter based on mode
672 if (randomizePageOrder) {
673 page_index <- page_index + 1
674 } else {
675 current_page_number <- current_page_number + 1
676 }
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200677 results <- results + res$meta$itemsPerPage
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200678 if (nrow(collectedMatches) >= kqo@totalResults || (!is.na(maxFetch) && results >= maxFetch)) {
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200679 break
680 }
681 }
Marc Kupietz68170952021-06-30 09:37:21 +0200682 nextStartIndex <- min(res$meta$startIndex + res$meta$itemsPerPage, kqo@totalResults)
Marc Kupietzd8851222025-05-01 10:57:19 +0200683 KorAPQuery(
684 nextStartIndex = nextStartIndex,
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200685 korapConnection = kqo@korapConnection,
Marc Kupietze95108e2019-09-18 13:23:58 +0200686 fields = kqo@fields,
687 requestUrl = kqo@requestUrl,
688 request = kqo@request,
Marc Kupietz68170952021-06-30 09:37:21 +0200689 totalResults = kqo@totalResults,
Marc Kupietze95108e2019-09-18 13:23:58 +0200690 vc = kqo@vc,
691 webUIRequestUrl = kqo@webUIRequestUrl,
Marc Kupietz68170952021-06-30 09:37:21 +0200692 hasMoreMatches = (kqo@totalResults > nextStartIndex),
Marc Kupietze95108e2019-09-18 13:23:58 +0200693 apiResponse = res,
Marc Kupietzd8851222025-05-01 10:57:19 +0200694 collectedMatches = collectedMatches
695 )
Marc Kupietze95108e2019-09-18 13:23:58 +0200696})
Marc Kupietz62da2b52019-09-12 17:43:34 +0200697
698#' Fetch all results of a KorAP query.
Marc Kupietz62da2b52019-09-12 17:43:34 +0200699#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200700#' **`fetchAll`** fetches all results of a KorAP query.
Marc Kupietza6e4ee62021-03-05 09:00:15 +0100701#'
Marc Kupietza8c40f42025-06-24 15:49:52 +0200702#' @family corpus search functions
Marc Kupietzdc880ac2025-06-24 20:34:43 +0200703#' @param kqo object obtained from [corpusQuery()]
704#' @param verbose print progress information if true
705#' @param ... further arguments passed to [fetchNext()]
706#' @return The updated `kqo` object with all results in `@collectedMatches`
Marc Kupietza8c40f42025-06-24 15:49:52 +0200707#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200708#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200709#' \dontrun{
Marc Kupietzecc86702025-06-24 12:12:51 +0200710#' # Fetch all metadata of every query hit for "Ameisenplage" and show a summary
711#' q <- KorAPConnection() |>
712#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200713#' fetchAll()
Marc Kupietze95108e2019-09-18 13:23:58 +0200714#' q@collectedMatches
Marc Kupietzecc86702025-06-24 12:12:51 +0200715#'
716#' # Fetch also all KWICs
717#' q <- KorAPConnection() |> auth() |>
718#' corpusQuery("Ameisenplage", metadataOnly = FALSE) |>
719#' fetchAll()
720#' q@collectedMatches
721#'
722#' # Retrieve title and text sigle metadata of all texts published on 1958-03-12
723#' q <- KorAPConnection() |>
724#' corpusQuery("<base/s=t>", # this matches each text once
725#' vc = "pubDate in 1958-03-12",
726#' fields = c("textSigle", "title"),
727#' ) |>
728#' fetchAll()
729#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100730#' }
Marc Kupietz62da2b52019-09-12 17:43:34 +0200731#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200732#' @aliases fetchAll
Marc Kupietz62da2b52019-09-12 17:43:34 +0200733#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200734setMethod("fetchAll", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
735 return(fetchNext(kqo, offset = 0, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200736})
737
738#' Fetches the remaining results of a KorAP query.
739#'
Marc Kupietzdc880ac2025-06-24 20:34:43 +0200740#' @param kqo object obtained from [corpusQuery()]
741#' @param verbose print progress information if true
742#' @param ... further arguments passed to [fetchNext()]
743#' @return The updated `kqo` object with remaining results in `@collectedMatches`
744#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200745#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200746#' \dontrun{
747#'
Marc Kupietzd3526422025-06-25 09:16:15 +0200748#' q <- KorAPConnection() |>
749#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200750#' fetchRest()
Marc Kupietze95108e2019-09-18 13:23:58 +0200751#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100752#' }
Marc Kupietze95108e2019-09-18 13:23:58 +0200753#'
754#' @aliases fetchRest
Marc Kupietze95108e2019-09-18 13:23:58 +0200755#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200756setMethod("fetchRest", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
757 return(fetchNext(kqo, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200758})
759
Marc Kupietzbdedd022025-10-09 14:14:15 +0200760# Helper to collapse multiple annotation values while preserving order
761collapse_features <- function(values) {
762 if (length(values) == 0) {
763 return(NA_character_)
764 }
765 unique_values <- values[!duplicated(values)]
766 paste(unique_values, collapse = "|")
767}
768
769# Extract token-level annotations from a DOM node
770collect_token_annotations <- function(parent_node) {
771 if (inherits(parent_node, "xml_missing")) {
772 return(list(
773 node = list(),
774 token = character(0),
775 lemma = character(0),
776 pos = character(0),
777 morph = character(0)
778 ))
779 }
780
781 leaf_nodes <- xml2::xml_find_all(parent_node, ".//span[not(.//span)]")
782
783 if (length(leaf_nodes) == 0) {
784 return(list(
785 node = list(),
786 token = character(0),
787 lemma = character(0),
788 pos = character(0),
789 morph = character(0)
790 ))
791 }
792
793 tokens <- character(0)
794 lemmas <- character(0)
795 pos_tags <- character(0)
796 morph_tags <- character(0)
797 kept_nodes <- list()
798
799 for (idx in seq_along(leaf_nodes)) {
800 leaf <- leaf_nodes[[idx]]
801 token_text <- trimws(xml2::xml_text(leaf))
802 if (identical(token_text, "")) {
803 next
804 }
805
806 kept_nodes[[length(kept_nodes) + 1]] <- leaf
807 tokens <- c(tokens, token_text)
808
809 ancestors <- xml2::xml_find_all(leaf, "ancestor-or-self::span")
810 titles <- xml2::xml_attr(ancestors, "title")
811 titles <- titles[!is.na(titles)]
812
813 feature_pieces <- if (length(titles) > 0) unlist(strsplit(titles, "[[:space:]]+")) else character(0)
814
815 lemma_values <- sub('.*?/l:(.*)$', '\\1', feature_pieces[grepl('/l:', feature_pieces)], perl = TRUE)
816 pos_values <- sub('.*?/p:(.*)$', '\\1', feature_pieces[grepl('/p:', feature_pieces)], perl = TRUE)
817 morph_values <- sub('.*?/m:(.*)$', '\\1', feature_pieces[grepl('/m:', feature_pieces)], perl = TRUE)
818
819 lemmas <- c(lemmas, collapse_features(lemma_values))
820 pos_tags <- c(pos_tags, collapse_features(pos_values))
821 morph_tags <- c(morph_tags, collapse_features(morph_values))
822 }
823
824 list(
825 node = kept_nodes,
826 token = tokens,
827 lemma = lemmas,
828 pos = pos_tags,
829 morph = morph_tags
830 )
831}
832
Marc Kupietza29f3d42025-07-18 10:14:43 +0200833#'
834#' Parse XML annotations into linguistic layers
835#'
836#' Internal helper function to extract linguistic annotations (lemma, POS, morphology)
837#' from XML annotation snippets returned by the KorAP API.
838#'
839#' @param xml_snippet XML string containing annotation data
840#' @return Named list with vectors for 'token', 'lemma', 'pos', and 'morph'
841#' @keywords internal
842parse_xml_annotations <- function(xml_snippet) {
843 if (is.null(xml_snippet) || is.na(xml_snippet) || xml_snippet == "") {
844 return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0)))
845 }
846
Marc Kupietzbdedd022025-10-09 14:14:15 +0200847 doc <- tryCatch(xml2::read_html(paste0("<root>", xml_snippet, "</root>")), error = function(e) NULL)
848 if (is.null(doc)) {
849 return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0)))
Marc Kupietzcd452182025-10-09 13:28:41 +0200850 }
851
Marc Kupietzbdedd022025-10-09 14:14:15 +0200852 match_node <- xml2::xml_find_first(doc, ".//span[contains(@class, 'match')]")
853 if (inherits(match_node, "xml_missing")) {
854 match_node <- xml2::xml_find_first(doc, ".//span")
855 if (inherits(match_node, "xml_missing")) {
856 return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0)))
Marc Kupietza29f3d42025-07-18 10:14:43 +0200857 }
858 }
859
Marc Kupietzbdedd022025-10-09 14:14:15 +0200860 token_info <- collect_token_annotations(match_node)
Marc Kupietza29f3d42025-07-18 10:14:43 +0200861
Marc Kupietzbdedd022025-10-09 14:14:15 +0200862 list(
863 token = token_info$token,
864 lemma = token_info$lemma,
865 pos = token_info$pos,
866 morph = token_info$morph
867 )
Marc Kupietza29f3d42025-07-18 10:14:43 +0200868}
869
870#'
871#' Parse XML annotations into linguistic layers with left/match/right structure
872#'
873#' Internal helper function to extract linguistic annotations (lemma, POS, morphology)
874#' from XML annotation snippets returned by the KorAP API, split into left context,
875#' match, and right context sections like the tokens field.
876#'
877#' @param xml_snippet XML string containing annotation data
878#' @return Named list with nested structure containing left/match/right for 'atokens', 'lemma', 'pos', and 'morph'
879#' @keywords internal
880parse_xml_annotations_structured <- function(xml_snippet) {
881 if (is.null(xml_snippet) || is.na(xml_snippet) || xml_snippet == "") {
882 empty_result <- list(left = character(0), match = character(0), right = character(0))
883 return(list(
884 atokens = empty_result,
885 lemma = empty_result,
886 pos = empty_result,
887 morph = empty_result
888 ))
889 }
890
Marc Kupietzbdedd022025-10-09 14:14:15 +0200891 doc <- tryCatch(xml2::read_html(paste0("<root>", xml_snippet, "</root>")), error = function(e) NULL)
892 if (is.null(doc)) {
893 empty_result <- list(left = character(0), match = character(0), right = character(0))
Marc Kupietza29f3d42025-07-18 10:14:43 +0200894 return(list(
Marc Kupietzbdedd022025-10-09 14:14:15 +0200895 atokens = empty_result,
896 lemma = empty_result,
897 pos = empty_result,
898 morph = empty_result
Marc Kupietza29f3d42025-07-18 10:14:43 +0200899 ))
900 }
901
Marc Kupietzbdedd022025-10-09 14:14:15 +0200902 match_node <- xml2::xml_find_first(doc, ".//span[contains(@class, 'match')]")
903 if (inherits(match_node, "xml_missing")) {
904 empty_result <- list(left = character(0), match = character(0), right = character(0))
905 return(list(
906 atokens = empty_result,
907 lemma = empty_result,
908 pos = empty_result,
909 morph = empty_result
910 ))
Marc Kupietza29f3d42025-07-18 10:14:43 +0200911 }
Marc Kupietzc643a122025-07-18 18:18:36 +0200912
Marc Kupietzbdedd022025-10-09 14:14:15 +0200913 token_info <- collect_token_annotations(match_node)
914 tokens <- token_info$token
915 lemmas <- token_info$lemma
916 pos_tags <- token_info$pos
917 morph_tags <- token_info$morph
918 nodes <- token_info$node
Marc Kupietzc643a122025-07-18 18:18:36 +0200919
Marc Kupietzbdedd022025-10-09 14:14:15 +0200920 if (length(tokens) == 0) {
921 empty_result <- list(left = character(0), match = character(0), right = character(0))
922 return(list(
923 atokens = empty_result,
924 lemma = empty_result,
925 pos = empty_result,
926 morph = empty_result
927 ))
928 }
Marc Kupietzc643a122025-07-18 18:18:36 +0200929
Marc Kupietzbdedd022025-10-09 14:14:15 +0200930 mark_flags <- vapply(nodes, function(n) {
931 !inherits(xml2::xml_find_first(n, "ancestor::mark"), "xml_missing")
932 }, logical(1))
Marc Kupietzc643a122025-07-18 18:18:36 +0200933
Marc Kupietzbdedd022025-10-09 14:14:15 +0200934 if (any(mark_flags)) {
935 first_idx <- which(mark_flags)[1]
936 last_idx <- tail(which(mark_flags), 1)
Marc Kupietza29f3d42025-07-18 10:14:43 +0200937 } else {
Marc Kupietzbdedd022025-10-09 14:14:15 +0200938 first_idx <- 1
939 last_idx <- length(tokens)
Marc Kupietza29f3d42025-07-18 10:14:43 +0200940 }
941
Marc Kupietzbdedd022025-10-09 14:14:15 +0200942 sections <- rep("match", length(tokens))
943 if (first_idx > 1) {
944 sections[seq_len(first_idx - 1)] <- "left"
945 }
946 if (last_idx < length(tokens)) {
947 sections[seq(from = last_idx + 1, to = length(tokens))] <- "right"
948 }
Marc Kupietza29f3d42025-07-18 10:14:43 +0200949
Marc Kupietzbdedd022025-10-09 14:14:15 +0200950 subset_by_section <- function(values, section) {
951 idx <- sections == section
952 if (!any(idx)) {
953 return(character(0))
954 }
955 values[idx]
956 }
957
958 atokens <- list(
959 left = subset_by_section(tokens, "left"),
960 match = subset_by_section(tokens, "match"),
961 right = subset_by_section(tokens, "right")
962 )
963
964 lemma <- list(
965 left = subset_by_section(lemmas, "left"),
966 match = subset_by_section(lemmas, "match"),
967 right = subset_by_section(lemmas, "right")
968 )
969
970 pos <- list(
971 left = subset_by_section(pos_tags, "left"),
972 match = subset_by_section(pos_tags, "match"),
973 right = subset_by_section(pos_tags, "right")
974 )
975
976 morph <- list(
977 left = subset_by_section(morph_tags, "left"),
978 match = subset_by_section(morph_tags, "match"),
979 right = subset_by_section(morph_tags, "right")
980 )
981
982 list(
983 atokens = atokens,
984 lemma = lemma,
985 pos = pos,
986 morph = morph
987 )
Marc Kupietza29f3d42025-07-18 10:14:43 +0200988}
989
Marc Kupietze52b2952025-07-17 16:53:02 +0200990#' Fetch annotations for all collected matches
991#'
Marc Kupietz89f796e2025-07-19 09:05:06 +0200992#' `r lifecycle::badge("experimental")`
993#'
994#' **`fetchAnnotations`** fetches annotations (only token annotations, for now)
995#' for all matches in the `@collectedMatches` slot
Marc Kupietzc643a122025-07-18 18:18:36 +0200996#' of a KorAPQuery object and adds annotation columns directly to the `@collectedMatches`
Marc Kupietz89f796e2025-07-19 09:05:06 +0200997#' data frame. The method uses the `matchID` from collected matches.
Marc Kupietza29f3d42025-07-18 10:14:43 +0200998#'
999#' **Important**: For copyright-restricted corpora, users must be authorized via [auth()]
1000#' and the initial corpus query must have `metadataOnly = FALSE` to ensure snippets are
1001#' available for annotation parsing.
1002#'
1003#' The method parses XML snippet annotations and adds linguistic columns to the data frame:
1004#' - `pos`: data frame with `left`, `match`, `right` columns, each containing list vectors of part-of-speech tags
1005#' - `lemma`: data frame with `left`, `match`, `right` columns, each containing list vectors of lemmas
1006#' - `morph`: data frame with `left`, `match`, `right` columns, each containing list vectors of morphological tags
1007#' - `atokens`: data frame with `left`, `match`, `right` columns, each containing list vectors of token text (from annotations)
1008#' - `annotation_snippet`: original XML snippet from the annotation API
Marc Kupietze52b2952025-07-17 16:53:02 +02001009#'
1010#' @family corpus search functions
Marc Kupietz89f796e2025-07-19 09:05:06 +02001011#' @concept Annotations
Marc Kupietze52b2952025-07-17 16:53:02 +02001012#'
Marc Kupietza29f3d42025-07-18 10:14:43 +02001013#' @param kqo object obtained from [corpusQuery()] with collected matches. Note: the original corpus query should have `metadataOnly = FALSE` for annotation parsing to work.
Marc Kupietze52b2952025-07-17 16:53:02 +02001014#' @param foundry string specifying the foundry to use for annotations (default: "tt" for Tree-Tagger)
Marc Kupietz93787d52025-09-03 13:33:25 +02001015#' @param overwrite logical; if TRUE, re-fetch and replace any existing
1016#' annotation columns. If FALSE (default), only add missing annotation layers
1017#' and preserve already fetched ones (e.g., keep POS/lemma from a previous
1018#' foundry while adding morph from another).
Marc Kupietze52b2952025-07-17 16:53:02 +02001019#' @param verbose print progress information if true
Marc Kupietz0af75932025-09-09 18:14:16 +02001020#' @return The updated `kqo` object with annotation columns
Marc Kupietz89f796e2025-07-19 09:05:06 +02001021#' like `pos`, `lemma`, `morph` (and `atokens` and `annotation_snippet`)
1022#' in the `@collectedMatches` slot. Each column is a data frame
1023#' with `left`, `match`, and `right` columns containing list vectors of annotations
1024#' for the left context, matched tokens, and right context, respectively.
1025#' The original XML snippet for each match is also stored in `annotation_snippet`.
Marc Kupietze52b2952025-07-17 16:53:02 +02001026#'
1027#' @examples
1028#' \dontrun{
1029#'
1030#' # Fetch annotations for matches using Tree-Tagger foundry
Marc Kupietza29f3d42025-07-18 10:14:43 +02001031#' # Note: Authorization required for copyright-restricted corpora
Marc Kupietze52b2952025-07-17 16:53:02 +02001032#' q <- KorAPConnection() |>
Marc Kupietza29f3d42025-07-18 10:14:43 +02001033#' auth() |>
1034#' corpusQuery("Ameisenplage", metadataOnly = FALSE) |>
Marc Kupietze52b2952025-07-17 16:53:02 +02001035#' fetchNext(maxFetch = 10) |>
1036#' fetchAnnotations()
Marc Kupietze52b2952025-07-17 16:53:02 +02001037#'
Marc Kupietza29f3d42025-07-18 10:14:43 +02001038#' # Access linguistic annotations for match i:
Marc Kupietz6aa5a0d2025-09-08 17:51:47 +02001039#' pos_tags <- q@collectedMatches$pos
1040#' # Data frame with left/match/right columns for POS tags
1041#' lemmas <- q@collectedMatches$lemma
1042#' # Data frame with left/match/right columns for lemmas
1043#' morphology <- q@collectedMatches$morph
1044#' # Data frame with left/match/right columns for morphological tags
1045#' atokens <- q@collectedMatches$atokens
1046#' # Data frame with left/match/right columns for annotation token text
Marc Kupietz0af75932025-09-09 18:14:16 +02001047#' # Original XML snippet for match i
1048#' raw_snippet <- q@collectedMatches$annotation_snippet[[i]]
Marc Kupietzc643a122025-07-18 18:18:36 +02001049#'
Marc Kupietza29f3d42025-07-18 10:14:43 +02001050#' # Access specific components:
Marc Kupietz0af75932025-09-09 18:14:16 +02001051#' # POS tags for the matched tokens in match i
1052#' match_pos <- q@collectedMatches$pos$match[[i]]
1053#' # Lemmas for the left context in match i
1054#' left_lemmas <- q@collectedMatches$lemma$left[[i]]
1055#' # Token text for the right context in match i
1056#' right_tokens <- q@collectedMatches$atokens$right[[i]]
Marc Kupietza29f3d42025-07-18 10:14:43 +02001057#'
Marc Kupietz89f796e2025-07-19 09:05:06 +02001058#' # Use a different foundry (e.g., MarMoT)
Marc Kupietze52b2952025-07-17 16:53:02 +02001059#' q <- KorAPConnection() |>
Marc Kupietza29f3d42025-07-18 10:14:43 +02001060#' auth() |>
1061#' corpusQuery("Ameisenplage", metadataOnly = FALSE) |>
Marc Kupietze52b2952025-07-17 16:53:02 +02001062#' fetchNext(maxFetch = 10) |>
Marc Kupietz89f796e2025-07-19 09:05:06 +02001063#' fetchAnnotations(foundry = "marmot")
1064#' q@collectedMatches$pos$left[1] # POS tags for the left context of the first match
Marc Kupietze52b2952025-07-17 16:53:02 +02001065#' }
Marc Kupietze52b2952025-07-17 16:53:02 +02001066#' @export
Marc Kupietz0af75932025-09-09 18:14:16 +02001067setMethod("fetchAnnotations", "KorAPQuery", function(kqo,
1068 foundry = "tt",
1069 overwrite = FALSE,
1070 verbose = kqo@korapConnection@verbose) {
1071 if (is.null(kqo@collectedMatches) ||
1072 nrow(kqo@collectedMatches) == 0) {
1073 warning("No collected matches found. Please run fetchNext() or fetchAll() first.")
1074 return(kqo)
1075 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001076
Marc Kupietze52b2952025-07-17 16:53:02 +02001077 df <- kqo@collectedMatches
1078 kco <- kqo@korapConnection
Marc Kupietza29f3d42025-07-18 10:14:43 +02001079
Marc Kupietza29f3d42025-07-18 10:14:43 +02001080 # Initialize annotation columns as data frames (like tokens field)
1081 # Create the structure more explicitly to avoid assignment issues
1082 nrows <- nrow(df)
Marc Kupietzc643a122025-07-18 18:18:36 +02001083
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001084 # Pre-compute the empty character vector list to avoid repeated computation
1085 empty_char_list <- I(replicate(nrows, character(0), simplify = FALSE))
Marc Kupietz0af75932025-09-09 18:14:16 +02001086
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001087 # Helper function to create annotation data frame structure
1088 create_annotation_df <- function(empty_list) {
1089 data.frame(
1090 left = empty_list,
1091 match = empty_list,
1092 right = empty_list,
1093 stringsAsFactors = FALSE
1094 )
1095 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001096
Marc Kupietz93787d52025-09-03 13:33:25 +02001097 # Track which annotation columns already existed to decide overwrite behavior
1098 existing_types <- list(
1099 pos = "pos" %in% colnames(df),
1100 lemma = "lemma" %in% colnames(df),
1101 morph = "morph" %in% colnames(df),
1102 atokens = "atokens" %in% colnames(df),
1103 annotation_snippet = "annotation_snippet" %in% colnames(df)
1104 )
1105
1106 # Initialize annotation columns using the helper function
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001107 annotation_types <- c("pos", "lemma", "morph", "atokens")
1108 for (type in annotation_types) {
Marc Kupietz93787d52025-09-03 13:33:25 +02001109 if (overwrite || !existing_types[[type]]) {
1110 df[[type]] <- create_annotation_df(empty_char_list)
1111 }
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001112 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001113
Marc Kupietz93787d52025-09-03 13:33:25 +02001114 if (overwrite || !existing_types$annotation_snippet) {
feldmuellera02f1932025-09-15 16:38:06 +02001115 df$annotation_snippet <- rep(NA_character_, nrows) # Fixed line
Marc Kupietz93787d52025-09-03 13:33:25 +02001116 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001117
Marc Kupietze8c0fef2025-07-18 19:59:04 +02001118 # Initialize timing for ETA calculation
1119 start_time <- Sys.time()
1120 if (verbose) {
1121 log_info(verbose, paste("Starting to fetch annotations for", nrows, "matches\n"))
1122 }
1123
Marc Kupietz93787d52025-09-03 13:33:25 +02001124 # Helper to decide if existing annotation row is effectively empty
1125 is_empty_annotation_row <- function(ann_df, row_index) {
1126 if (is.null(ann_df) || nrow(ann_df) < row_index) return(TRUE)
1127 left_val <- ann_df$left[[row_index]]
1128 match_val <- ann_df$match[[row_index]]
1129 right_val <- ann_df$right[[row_index]]
1130 all(
1131 (is.null(left_val) || (length(left_val) == 0) || all(is.na(left_val))),
1132 (is.null(match_val) || (length(match_val) == 0) || all(is.na(match_val))),
1133 (is.null(right_val) || (length(right_val) == 0) || all(is.na(right_val)))
1134 )
1135 }
1136
Marc Kupietze52b2952025-07-17 16:53:02 +02001137 for (i in seq_len(nrow(df))) {
Marc Kupietze8c0fef2025-07-18 19:59:04 +02001138 # ETA logging
1139 if (verbose && i > 1) {
1140 eta_info <- calculate_eta(i, nrows, start_time)
1141 log_info(verbose, paste("Fetching annotations for match", i, "of", nrows, eta_info, "\n"))
1142 }
Marc Kupietzff712a92025-07-18 09:07:23 +02001143 # Use matchID if available, otherwise fall back to constructing from matchStart/matchEnd
1144 if ("matchID" %in% colnames(df) && !is.na(df$matchID[i])) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001145 # matchID format: "match-match-A00/JUN/39609-p202-203" or encrypted format like
1146 # "match-DNB10/CSL/80400-p2343-2344x_MinDOhu_P6dd2MMZJyyus_7MairdKnr1LxY07Cya-Ow"
1147 # Extract document path and position, handling both regular and encrypted formats
Marc Kupietzc643a122025-07-18 18:18:36 +02001148
Marc Kupietza29f3d42025-07-18 10:14:43 +02001149 # More flexible regex to extract the document path with position and encryption
1150 # Look for pattern: match-(...)-p(\d+)-(\d+)(.*) where (.*) is the encrypted part
1151 # We need to capture the entire path including the encrypted suffix
1152 match_result <- regexpr("match-(.+?-p\\d+-\\d+.*)", df$matchID[i], perl = TRUE)
Marc Kupietzc643a122025-07-18 18:18:36 +02001153
Marc Kupietza29f3d42025-07-18 10:14:43 +02001154 if (match_result > 0) {
1155 # Extract the complete path including encryption (everything after "match-")
1156 doc_path_with_pos_and_encryption <- gsub("^match-(.+)$", "\\1", df$matchID[i], perl = TRUE)
1157 # Convert the dash before position to slash, but keep everything after the position
1158 match_path <- gsub("-p(\\d+-\\d+.*)", "/p\\1", doc_path_with_pos_and_encryption)
Marc Kupietz25121302025-07-19 08:45:43 +02001159 # Use httr2 to construct URL safely
1160 base_url <- paste0(kco@apiUrl, "corpus/", match_path)
1161 req <- httr2::url_modify(base_url, query = list(foundry = foundry))
Marc Kupietza29f3d42025-07-18 10:14:43 +02001162 } else {
Marc Kupietz25121302025-07-19 08:45:43 +02001163 # If regex fails, fall back to the old method with httr2
1164 # Format numbers to avoid scientific notation
1165 match_start <- format(df$matchStart[i], scientific = FALSE)
1166 match_end <- format(df$matchEnd[i], scientific = FALSE)
1167 base_url <- paste0(kco@apiUrl, "corpus/", df$textSigle[i], "/", "p", match_start, "-", match_end)
1168 req <- httr2::url_modify(base_url, query = list(foundry = foundry))
Marc Kupietzff712a92025-07-18 09:07:23 +02001169 }
1170 } else {
Marc Kupietz25121302025-07-19 08:45:43 +02001171 # Fallback to the old method with httr2
1172 # Format numbers to avoid scientific notation
1173 match_start <- format(df$matchStart[i], scientific = FALSE)
1174 match_end <- format(df$matchEnd[i], scientific = FALSE)
1175 base_url <- paste0(kco@apiUrl, "corpus/", df$textSigle[i], "/", "p", match_start, "-", match_end)
1176 req <- httr2::url_modify(base_url, query = list(foundry = foundry))
Marc Kupietzff712a92025-07-18 09:07:23 +02001177 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001178
Marc Kupietze52b2952025-07-17 16:53:02 +02001179 tryCatch({
1180 res <- apiCall(kco, req)
Marc Kupietzc643a122025-07-18 18:18:36 +02001181
Marc Kupietze52b2952025-07-17 16:53:02 +02001182 if (!is.null(res)) {
Marc Kupietz93787d52025-09-03 13:33:25 +02001183 # Store the raw annotation snippet (respect overwrite flag)
1184 if (overwrite || !existing_types$annotation_snippet || is.null(df$annotation_snippet[[i]]) || is.na(df$annotation_snippet[[i]])) {
1185 df$annotation_snippet[[i]] <- if (is.list(res) && "snippet" %in% names(res)) res$snippet else NA
1186 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001187
1188 # Parse XML annotations if snippet is available
1189 if (is.list(res) && "snippet" %in% names(res)) {
1190 parsed_annotations <- parse_xml_annotations_structured(res$snippet)
1191
1192 # Store the parsed linguistic data in data frame format (like tokens)
1193 # Use individual assignment to avoid data frame mismatch errors
1194 tryCatch({
1195 # Assign POS annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001196 if (overwrite || !existing_types$pos || is_empty_annotation_row(df$pos, i)) {
1197 df$pos$left[i] <- list(parsed_annotations$pos$left)
1198 df$pos$match[i] <- list(parsed_annotations$pos$match)
1199 df$pos$right[i] <- list(parsed_annotations$pos$right)
1200 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001201
Marc Kupietza29f3d42025-07-18 10:14:43 +02001202 # Assign lemma annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001203 if (overwrite || !existing_types$lemma || is_empty_annotation_row(df$lemma, i)) {
1204 df$lemma$left[i] <- list(parsed_annotations$lemma$left)
1205 df$lemma$match[i] <- list(parsed_annotations$lemma$match)
1206 df$lemma$right[i] <- list(parsed_annotations$lemma$right)
1207 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001208
Marc Kupietza29f3d42025-07-18 10:14:43 +02001209 # Assign morphology annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001210 if (overwrite || !existing_types$morph || is_empty_annotation_row(df$morph, i)) {
1211 df$morph$left[i] <- list(parsed_annotations$morph$left)
1212 df$morph$match[i] <- list(parsed_annotations$morph$match)
1213 df$morph$right[i] <- list(parsed_annotations$morph$right)
1214 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001215
Marc Kupietza29f3d42025-07-18 10:14:43 +02001216 # Assign token annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001217 if (overwrite || !existing_types$atokens || is_empty_annotation_row(df$atokens, i)) {
1218 df$atokens$left[i] <- list(parsed_annotations$atokens$left)
1219 df$atokens$match[i] <- list(parsed_annotations$atokens$match)
1220 df$atokens$right[i] <- list(parsed_annotations$atokens$right)
1221 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001222 }, error = function(assign_error) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001223 # Set empty character vectors on assignment error using list assignment
Marc Kupietz93787d52025-09-03 13:33:25 +02001224 if (overwrite || !existing_types$pos) {
1225 df$pos$left[i] <<- list(character(0))
1226 df$pos$match[i] <<- list(character(0))
1227 df$pos$right[i] <<- list(character(0))
1228 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001229
Marc Kupietz93787d52025-09-03 13:33:25 +02001230 if (overwrite || !existing_types$lemma) {
1231 df$lemma$left[i] <<- list(character(0))
1232 df$lemma$match[i] <<- list(character(0))
1233 df$lemma$right[i] <<- list(character(0))
1234 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001235
Marc Kupietz93787d52025-09-03 13:33:25 +02001236 if (overwrite || !existing_types$morph) {
1237 df$morph$left[i] <<- list(character(0))
1238 df$morph$match[i] <<- list(character(0))
1239 df$morph$right[i] <<- list(character(0))
1240 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001241
Marc Kupietz93787d52025-09-03 13:33:25 +02001242 if (overwrite || !existing_types$atokens) {
1243 df$atokens$left[i] <<- list(character(0))
1244 df$atokens$match[i] <<- list(character(0))
1245 df$atokens$right[i] <<- list(character(0))
1246 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001247 })
Marc Kupietza29f3d42025-07-18 10:14:43 +02001248 } else {
1249 # No snippet available, store empty vectors
Marc Kupietz93787d52025-09-03 13:33:25 +02001250 if (overwrite || !existing_types$pos) {
1251 df$pos$left[i] <- list(character(0))
1252 df$pos$match[i] <- list(character(0))
1253 df$pos$right[i] <- list(character(0))
1254 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001255
Marc Kupietz93787d52025-09-03 13:33:25 +02001256 if (overwrite || !existing_types$lemma) {
1257 df$lemma$left[i] <- list(character(0))
1258 df$lemma$match[i] <- list(character(0))
1259 df$lemma$right[i] <- list(character(0))
1260 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001261
Marc Kupietz93787d52025-09-03 13:33:25 +02001262 if (overwrite || !existing_types$morph) {
1263 df$morph$left[i] <- list(character(0))
1264 df$morph$match[i] <- list(character(0))
1265 df$morph$right[i] <- list(character(0))
1266 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001267
Marc Kupietz93787d52025-09-03 13:33:25 +02001268 if (overwrite || !existing_types$atokens) {
1269 df$atokens$left[i] <- list(character(0))
1270 df$atokens$match[i] <- list(character(0))
1271 df$atokens$right[i] <- list(character(0))
1272 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001273 }
Marc Kupietze52b2952025-07-17 16:53:02 +02001274 } else {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001275 # Store NAs for failed requests
Marc Kupietz93787d52025-09-03 13:33:25 +02001276 if (overwrite || !existing_types$pos) {
1277 df$pos$left[i] <- list(NA)
1278 df$pos$match[i] <- list(NA)
1279 df$pos$right[i] <- list(NA)
1280 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001281
Marc Kupietz93787d52025-09-03 13:33:25 +02001282 if (overwrite || !existing_types$lemma) {
1283 df$lemma$left[i] <- list(NA)
1284 df$lemma$match[i] <- list(NA)
1285 df$lemma$right[i] <- list(NA)
1286 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001287
Marc Kupietz93787d52025-09-03 13:33:25 +02001288 if (overwrite || !existing_types$morph) {
1289 df$morph$left[i] <- list(NA)
1290 df$morph$match[i] <- list(NA)
1291 df$morph$right[i] <- list(NA)
1292 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001293
Marc Kupietz93787d52025-09-03 13:33:25 +02001294 if (overwrite || !existing_types$atokens) {
1295 df$atokens$left[i] <- list(NA)
1296 df$atokens$match[i] <- list(NA)
1297 df$atokens$right[i] <- list(NA)
1298 }
1299 if (overwrite || !existing_types$annotation_snippet) {
1300 df$annotation_snippet[[i]] <- NA
1301 }
Marc Kupietze52b2952025-07-17 16:53:02 +02001302 }
1303 }, error = function(e) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001304 # Store NAs for failed requests
Marc Kupietz93787d52025-09-03 13:33:25 +02001305 if (overwrite || !existing_types$pos) {
1306 df$pos$left[i] <- list(NA)
1307 df$pos$match[i] <- list(NA)
1308 df$pos$right[i] <- list(NA)
1309 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001310
Marc Kupietz93787d52025-09-03 13:33:25 +02001311 if (overwrite || !existing_types$lemma) {
1312 df$lemma$left[i] <- list(NA)
1313 df$lemma$match[i] <- list(NA)
1314 df$lemma$right[i] <- list(NA)
1315 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001316
Marc Kupietz93787d52025-09-03 13:33:25 +02001317 if (overwrite || !existing_types$morph) {
1318 df$morph$left[i] <- list(NA)
1319 df$morph$match[i] <- list(NA)
1320 df$morph$right[i] <- list(NA)
1321 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001322
Marc Kupietz93787d52025-09-03 13:33:25 +02001323 if (overwrite || !existing_types$atokens) {
1324 df$atokens$left[i] <- list(NA)
1325 df$atokens$match[i] <- list(NA)
1326 df$atokens$right[i] <- list(NA)
1327 }
1328 if (overwrite || !existing_types$annotation_snippet) {
1329 df$annotation_snippet[[i]] <- NA
1330 }
Marc Kupietze52b2952025-07-17 16:53:02 +02001331 })
1332 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001333
Marc Kupietza29f3d42025-07-18 10:14:43 +02001334 # Validate data frame structure before assignment
1335 if (nrow(df) != nrow(kqo@collectedMatches)) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001336 }
1337
1338 # Update the collectedMatches with annotation data
1339 tryCatch({
1340 kqo@collectedMatches <- df
1341 }, error = function(assign_error) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001342 # Try a safer approach: add columns individually
1343 tryCatch({
1344 kqo@collectedMatches$pos <- df$pos
Marc Kupietzc643a122025-07-18 18:18:36 +02001345 kqo@collectedMatches$lemma <- df$lemma
Marc Kupietza29f3d42025-07-18 10:14:43 +02001346 kqo@collectedMatches$morph <- df$morph
1347 kqo@collectedMatches$atokens <- df$atokens
1348 kqo@collectedMatches$annotation_snippet <- df$annotation_snippet
1349 }, error = function(col_error) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001350 warning("Failed to add annotation data to collectedMatches")
1351 })
1352 })
1353
Marc Kupietze8c0fef2025-07-18 19:59:04 +02001354 if (verbose) {
1355 elapsed_time <- Sys.time() - start_time
1356 log_info(verbose, paste("Finished fetching annotations for", nrows, "matches in", format_duration(as.numeric(elapsed_time, units = "secs")), "\n"))
1357 }
1358
Marc Kupietze52b2952025-07-17 16:53:02 +02001359 return(kqo)
1360})
1361
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001362#' Query frequencies of search expressions in virtual corpora
Marc Kupietz3f575282019-10-04 14:46:04 +02001363#'
Marc Kupietz67edcb52021-09-20 21:54:24 +02001364#' **`frequencyQuery`** combines [corpusQuery()], [corpusStats()] and
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001365#' [ci()] to compute a tibble with the absolute and relative frequencies and
Marc Kupietz3f575282019-10-04 14:46:04 +02001366#' confidence intervals of one ore multiple search terms across one or multiple
1367#' virtual corpora.
1368#'
Marc Kupietza8c40f42025-06-24 15:49:52 +02001369#' @family frequency analysis
Marc Kupietz3f575282019-10-04 14:46:04 +02001370#' @aliases frequencyQuery
Marc Kupietz3f575282019-10-04 14:46:04 +02001371#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +02001372#' \dontrun{
1373#'
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001374#' KorAPConnection(verbose = TRUE) |>
Marc Kupietz3f575282019-10-04 14:46:04 +02001375#' frequencyQuery(c("Mücke", "Schnake"), paste0("pubDate in ", 2000:2003))
Marc Kupietz05b22772020-02-18 21:58:42 +01001376#' }
Marc Kupietz3f575282019-10-04 14:46:04 +02001377#'
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001378# @inheritParams corpusQuery
Marc Kupietz617266d2025-02-27 10:43:07 +01001379#' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()`
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001380#' @param query corpus query string(s.) (can be a vector). The query language depends on the `ql` parameter. Either `query` must be provided or `KorAPUrl`.
1381#' @param vc virtual corpus definition(s) (can be a vector)
Marc Kupietz67edcb52021-09-20 21:54:24 +02001382#' @param conf.level confidence level of the returned confidence interval (passed through [ci()] to [prop.test()]).
1383#' @param as.alternatives LOGICAL that specifies if the query terms should be treated as alternatives. If `as.alternatives` is TRUE, the sum over all query hits, instead of the respective vc token sizes is used as total for the calculation of relative frequencies.
Marc Kupietza3a8cd92026-09-08 07:59:04 +02001384#' @param cacheAs path to an RDS file to keep the result in. If the file exists and records the same call, it is read back instead of contacting the server; otherwise the query is run and its result stored there. Unlike the connection's `cache`, this file belongs to the caller, which is what keeps an analysis reproducible once the corpus has grown or the scores have changed. Defaults to \code{NULL} (no file).
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001385#' @param ... further arguments passed to or from other methods (see [corpusQuery()]), most notably `expand`, a logical that decides if `query` and `vc` parameters are expanded to all of their combinations. It defaults to `TRUE`, if `query` and `vc` have different lengths, and to `FALSE` otherwise.
Marc Kupietz3f575282019-10-04 14:46:04 +02001386#' @export
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001387#'
1388#' @return A tibble, with each row containing the following result columns for query and vc combinations:
1389#' - **query**: the query string used for the frequency analysis.
1390#' - **totalResults**: absolute frequency of query matches in the vc.
1391#' - **vc**: virtual corpus used for the query.
Marc Kupietz10eff992026-09-14 08:31:41 +02001392#' - **queryDuration**: client-side duration of the request in seconds.
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001393#' - **webUIRequestUrl**: URL of the corresponding web UI request with respect to query and vc.
1394#' - **total**: total number of words in vc.
1395#' - **f**: relative frequency of query matches in the vc.
1396#' - **conf.low**: lower bound of the confidence interval for the relative frequency, given `conf.level`.
1397#' - **conf.high**: upper bound of the confidence interval for the relative frequency, given `conf.level`.
1398
Marc Kupietzd8851222025-05-01 10:57:19 +02001399setMethod(
1400 "frequencyQuery", "KorAPConnection",
Marc Kupietza3a8cd92026-09-08 07:59:04 +02001401 function(kco, query, vc = "", conf.level = 0.95, as.alternatives = FALSE,
1402 cacheAs = NULL, ...) {
1403 cacheRecord <- NULL
1404 if (!is.null(cacheAs)) {
1405 cacheAs <- cacheAsFileName(cacheAs)
1406 cacheRecord <- cacheAsRecord(environment(), list(...), kco)
1407 cached <- readCacheAs(cacheAs, kco, cacheRecord, "frequency query")
1408 if (!is.null(cached)) {
1409 return(cached)
1410 }
1411 }
1412
1413 result <- (if (as.alternatives) {
Marc Kupietzd8851222025-05-01 10:57:19 +02001414 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |>
Marc Kupietzea34b812025-06-25 15:49:00 +02001415 group_by(vc) |>
Marc Kupietz71d6e052019-11-22 18:42:10 +01001416 mutate(total = sum(totalResults))
Marc Kupietzd8851222025-05-01 10:57:19 +02001417 } else {
1418 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |>
1419 mutate(total = corpusStats(kco, vc = vc, as.df = TRUE)$tokens)
Marc Kupietzea34b812025-06-25 15:49:00 +02001420 }) |>
Marc Kupietz0c29cea2019-10-09 08:44:36 +02001421 ci(conf.level = conf.level)
Marc Kupietza3a8cd92026-09-08 07:59:04 +02001422
1423 if (!is.null(cacheAs)) {
1424 writeCacheAs(cacheAs, kco, cacheRecord, "frequency query", result)
1425 }
1426 result
Marc Kupietzd8851222025-05-01 10:57:19 +02001427 }
1428)
Marc Kupietz3f575282019-10-04 14:46:04 +02001429
Marc Kupietz38a9d682024-12-06 16:17:09 +01001430#' buildWebUIRequestUrlFromString
1431#'
1432#' @rdname KorAPQuery-class
1433#' @importFrom urltools url_encode
1434#' @export
1435buildWebUIRequestUrlFromString <- function(KorAPUrl,
Marc Kupietzd8851222025-05-01 10:57:19 +02001436 query,
1437 vc = "",
1438 ql = "poliqarp") {
Marc Kupietz38a9d682024-12-06 16:17:09 +01001439 if ("KorAPConnection" %in% class(KorAPUrl)) {
1440 KorAPUrl <- KorAPUrl@KorAPUrl
1441 }
1442
1443 request <-
1444 paste0(
Marc Kupietzd8851222025-05-01 10:57:19 +02001445 "?q=",
Marc Kupietz38a9d682024-12-06 16:17:09 +01001446 urltools::url_encode(enc2utf8(as.character(query))),
Marc Kupietzd8851222025-05-01 10:57:19 +02001447 ifelse(vc != "",
1448 paste0("&cq=", urltools::url_encode(enc2utf8(vc))),
1449 ""
1450 ),
1451 "&ql=",
Marc Kupietz38a9d682024-12-06 16:17:09 +01001452 ql
1453 )
1454 paste0(KorAPUrl, request)
1455}
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001456
1457#' buildWebUIRequestUrl
1458#'
1459#' @rdname KorAPQuery-class
Marc Kupietzf9129592025-01-26 19:17:54 +01001460#' @importFrom httr2 url_parse
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001461#' @export
1462buildWebUIRequestUrl <- function(kco,
Marc Kupietzd8851222025-05-01 10:57:19 +02001463 query = if (missing(KorAPUrl)) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001464 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
Marc Kupietzd8851222025-05-01 10:57:19 +02001465 } else {
1466 httr2::url_parse(KorAPUrl)$query$q
1467 },
Marc Kupietzf9129592025-01-26 19:17:54 +01001468 vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq,
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001469 KorAPUrl,
Marc Kupietzf9129592025-01-26 19:17:54 +01001470 ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql) {
Marc Kupietz38a9d682024-12-06 16:17:09 +01001471 buildWebUIRequestUrlFromString(kco@KorAPUrl, query, vc, ql)
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001472}
1473
Marc Kupietzd8851222025-05-01 10:57:19 +02001474#' format()
Marc Kupietze95108e2019-09-18 13:23:58 +02001475#' @rdname KorAPQuery-class
1476#' @param x KorAPQuery object
1477#' @param ... further arguments passed to or from other methods
Marc Kupietzb73ca0f2025-01-28 20:45:01 +01001478#' @importFrom urltools param_get url_decode
Marc Kupietze95108e2019-09-18 13:23:58 +02001479#' @export
1480format.KorAPQuery <- function(x, ...) {
1481 cat("<KorAPQuery>\n")
1482 q <- x
Marc Kupietzd8851222025-05-01 10:57:19 +02001483 param <- urltools::param_get(q@request) |> lapply(urltools::url_decode)
Marc Kupietzb73ca0f2025-01-28 20:45:01 +01001484 cat(" Query: ", param$q, "\n")
1485 if (!is.null(param$cq) && param$cq != "") {
1486 cat(" Virtual corpus: ", param$cq, "\n")
1487 }
1488 if (!is.null(q@collectedMatches)) {
1489 cat("==============================================================================================================", "\n")
1490 print(summary(q@collectedMatches))
1491 cat("==============================================================================================================", "\n")
1492 }
1493 cat(" Total results: ", q@totalResults, "\n")
1494 cat(" Fetched results: ", q@nextStartIndex, "\n")
Marc Kupietza29f3d42025-07-18 10:14:43 +02001495 if (!is.null(q@collectedMatches) && "pos" %in% colnames(q@collectedMatches)) {
1496 successful_annotations <- sum(!is.na(q@collectedMatches$annotation_snippet))
1497 parsed_annotations <- sum(!is.na(q@collectedMatches$pos))
1498 cat(" Annotations: ", successful_annotations, " of ", nrow(q@collectedMatches), " matches")
1499 if (parsed_annotations > 0) {
1500 cat(" (", parsed_annotations, " with parsed linguistic data)")
1501 }
1502 cat("\n")
Marc Kupietze52b2952025-07-17 16:53:02 +02001503 }
Marc Kupietz62da2b52019-09-12 17:43:34 +02001504}
1505
Marc Kupietze95108e2019-09-18 13:23:58 +02001506#' show()
Marc Kupietz62da2b52019-09-12 17:43:34 +02001507#'
Marc Kupietze95108e2019-09-18 13:23:58 +02001508#' @rdname KorAPQuery-class
1509#' @param object KorAPQuery object
Marc Kupietz62da2b52019-09-12 17:43:34 +02001510#' @export
Marc Kupietze95108e2019-09-18 13:23:58 +02001511setMethod("show", "KorAPQuery", function(object) {
1512 format(object)
Marc Kupietzc643a122025-07-18 18:18:36 +02001513 invisible(object)
Marc Kupietze95108e2019-09-18 13:23:58 +02001514})