blob: abd17340c549a5fba3ceb2d5d87fa7c13e5f1a50 [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",
Marc Kupietz8ad07462026-09-14 11:58:36 +020048 "availability", "textClass", "dmozDomain", "wikiDomain",
49 "snippet", "tokens"
Marc Kupietzd8851222025-05-01 10:57:19 +020050 ),
Marc Kupietza29f3d42025-07-18 10:14:43 +020051 requestUrl = "", webUIRequestUrl = "", apiResponse = NULL, hasMoreMatches = FALSE, collectedMatches = NULL) {
Marc Kupietzd8851222025-05-01 10:57:19 +020052 .Object <- callNextMethod()
53 .Object@korapConnection <- korapConnection
54 .Object@request <- request
55 .Object@vc <- vc
56 .Object@totalResults <- totalResults
57 .Object@nextStartIndex <- nextStartIndex
58 .Object@fields <- fields
59 .Object@requestUrl <- requestUrl
60 .Object@webUIRequestUrl <- webUIRequestUrl
61 .Object@apiResponse <- apiResponse
62 .Object@hasMoreMatches <- hasMoreMatches
63 .Object@collectedMatches <- collectedMatches
64 .Object
65 }
66)
Marc Kupietz632cbd42019-09-06 16:04:51 +020067
Marc Kupietzd8851222025-05-01 10:57:19 +020068setGeneric("corpusQuery", function(kco, ...) standardGeneric("corpusQuery"))
69setGeneric("fetchAll", function(kqo, ...) standardGeneric("fetchAll"))
70setGeneric("fetchNext", function(kqo, ...) standardGeneric("fetchNext"))
71setGeneric("fetchRest", function(kqo, ...) standardGeneric("fetchRest"))
Marc Kupietz0af75932025-09-09 18:14:16 +020072setGeneric(
73 "fetchAnnotations",
74 function(kqo,
75 foundry = "tt",
76 overwrite = FALSE,
77 verbose = kqo@korapConnection@verbose) standardGeneric("fetchAnnotations")
78)
Marc Kupietzd8851222025-05-01 10:57:19 +020079setGeneric("frequencyQuery", function(kco, ...) standardGeneric("frequencyQuery"))
Marc Kupietze95108e2019-09-18 13:23:58 +020080
81maxResultsPerPage <- 50
Marc Kupietz62da2b52019-09-12 17:43:34 +020082
Marc Kupietz4de53ec2019-10-04 09:12:00 +020083## quiets concerns of R CMD check re: the .'s that appear in pipelines
Marc Kupietzef1ef4a2025-02-19 12:12:40 +010084utils::globalVariables(c("."))
Marc Kupietz632cbd42019-09-06 16:04:51 +020085
Marc Kupietza8c40f42025-06-24 15:49:52 +020086#' Search corpus for query terms
Marc Kupietzdbd431a2021-08-29 12:17:45 +020087#'
Marc Kupietz67edcb52021-09-20 21:54:24 +020088#' **`corpusQuery`** performs a corpus query via a connection to a KorAP-API-server
Marc Kupietze95108e2019-09-18 13:23:58 +020089#'
Marc Kupietza8c40f42025-06-24 15:49:52 +020090#' @family corpus search functions
Marc Kupietzdbd431a2021-08-29 12:17:45 +020091#' @aliases corpusQuery
92#'
93#' @importFrom urltools url_encode
94#' @importFrom purrr pmap
Marc Kupietzea34b812025-06-25 15:49:00 +020095#' @importFrom dplyr bind_rows group_by
Marc Kupietzdbd431a2021-08-29 12:17:45 +020096#'
Marc Kupietz617266d2025-02-27 10:43:07 +010097#' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()`
Marc Kupietz67edcb52021-09-20 21:54:24 +020098#' @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 +020099#' @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 +0200100#' @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 +0200101#' @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.
102#' If you want your corpus queries to return not only metadata, but also KWICS, you need to authorize
103#' your RKorAPClient application as explained in the
104#' [authorization section](https://github.com/KorAP/RKorAPClient#authorization)
105#' of the RKorAPClient Readme on GitHub and set the `metadataOnly` parameter to
106#' `FALSE`.
Marc Kupietz67edcb52021-09-20 21:54:24 +0200107#' @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 +0200108#' @param fields character vector specifying which metadata fields to retrieve for each match.
109#' Available fields depend on the corpus. For DeReKo (German Reference Corpus), possible fields include:
110#' \describe{
111#' \item{**Text identification**:}{`textSigle`, `docSigle`, `corpusSigle` - hierarchical text identifiers}
112#' \item{**Publication info**:}{`author`, `editor`, `title`, `docTitle`, `corpusTitle` - authorship and titles}
113#' \item{**Temporal data**:}{`pubDate`, `creationDate` - when text was published/created}
114#' \item{**Publication details**:}{`pubPlace`, `publisher`, `reference` - where/how published}
Marc Kupietz8ad07462026-09-14 11:58:36 +0200115#' \item{**Text classification**:}{`textClass`, `dmozDomain`, `wikiDomain`, `textType`, `textTypeArt`, `textDomain`, `textColumn` - topic domain, genre, text type and column}
Marc Kupietz1623fe82025-06-24 16:31:46 +0200116#' \item{**Adminstrative and technical info**:}{`corpusEditor`, `availability`, `language`, `foundries` - access rights and annotations}
117#' \item{**Content data**:}{`snippet`, `tokens`, `tokenSource`, `externalLink` - actual text content, tokenization, and link to source text}
118#' \item{**System data**:}{`indexCreationDate`, `indexLastModified` - corpus indexing info}
119#' }
120#' Use `c("textSigle", "pubDate", "author")` to retrieve multiple fields.
121#' 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 +0100122#' @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 +0200123#' @param verbose print some info
Marc Kupietz4de53ec2019-10-04 09:12:00 +0200124#' @param as.df return result as data frame instead of as S4 object?
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200125#' @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 +0200126#' @param context string that specifies the size of the left and the right context returned in `snippet`
127#' (provided that `metadataOnly` is set to `false` and that the necessary access right are met).
128#' 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).
129#' If the parameter is not set, the default context size secification of the KorAP server instance will be used.
130#' Note that you cannot overrule the maximum context size set in the KorAP server instance,
131#' as this is typically legally motivated.
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200132#' @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 +0200133#' A corresponding URL to be used within a web browser is contained in `@webUIRequestUrl`
134#' 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 +0200135#'
136#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200137#' \dontrun{
138#'
Marc Kupietz1623fe82025-06-24 16:31:46 +0200139#' # Fetch basic metadata for "Ameisenplage"
Marc Kupietzd3526422025-06-25 09:16:15 +0200140#' KorAPConnection() |>
141#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200142#' fetchAll()
Marc Kupietz1623fe82025-06-24 16:31:46 +0200143#'
144#' # Fetch specific metadata fields for bibliographic analysis
Marc Kupietzd3526422025-06-25 09:16:15 +0200145#' query <- KorAPConnection() |>
Marc Kupietz1623fe82025-06-24 16:31:46 +0200146#' corpusQuery("Ameisenplage",
147#' fields = c("textSigle", "author", "title", "pubDate", "pubPlace", "textType"))
148#' results <- fetchAll(query)
149#' results@collectedMatches
Marc Kupietz657d8e72020-02-25 18:31:50 +0100150#' }
Marc Kupietz3c531f62019-09-13 12:17:24 +0200151#'
Marc Kupietz6ae76052021-09-21 10:34:00 +0200152#' \dontrun{
153#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200154#' # Use the copy of a KorAP-web-frontend URL for an API query of "Ameise" in a virtual corpus
155#' # and show the number of query hits (but don't fetch them).
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200156#'
Marc Kupietzd3526422025-06-25 09:16:15 +0200157#' KorAPConnection(verbose = TRUE) |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200158#' corpusQuery(
159#' KorAPUrl =
160#' "https://korap.ids-mannheim.de/?q=Ameise&cq=pubDate+since+2017&ql=poliqarp"
161#' )
Marc Kupietz6ae76052021-09-21 10:34:00 +0200162#' }
163#'
164#' \dontrun{
Marc Kupietz3c531f62019-09-13 12:17:24 +0200165#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200166#' # Plot the time/frequency curve of "Ameisenplage"
Marc Kupietzd3526422025-06-25 09:16:15 +0200167#' KorAPConnection(verbose = TRUE) |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200168#' {
169#' . ->> kco
Marc Kupietzd3526422025-06-25 09:16:15 +0200170#' } |>
171#' corpusQuery("Ameisenplage") |>
172#' fetchAll() |>
173#' slot("collectedMatches") |>
174#' mutate(year = lubridate::year(pubDate)) |>
175#' dplyr::select(year) |>
176#' group_by(year) |>
177#' summarise(Count = dplyr::n()) |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200178#' mutate(Freq = mapply(function(f, y) {
179#' f / corpusStats(kco, paste("pubDate in", y))@tokens
Marc Kupietzd3526422025-06-25 09:16:15 +0200180#' }, Count, year)) |>
181#' dplyr::select(-Count) |>
182#' complete(year = min(year):max(year), fill = list(Freq = 0)) |>
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200183#' plot(type = "l")
Marc Kupietz05b22772020-02-18 21:58:42 +0100184#' }
Marc Kupietz67edcb52021-09-20 21:54:24 +0200185#' @seealso [KorAPConnection()], [fetchNext()], [fetchRest()], [fetchAll()], [corpusStats()]
Marc Kupietz632cbd42019-09-06 16:04:51 +0200186#'
187#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200188#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz632cbd42019-09-06 16:04:51 +0200189#'
190#' @export
Marc Kupietzd8851222025-05-01 10:57:19 +0200191setMethod(
192 "corpusQuery", "KorAPConnection",
193 function(kco,
194 query = if (missing(KorAPUrl)) {
195 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
196 } else {
197 httr2::url_parse(KorAPUrl)$query$q
198 },
199 vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq,
200 KorAPUrl,
201 metadataOnly = TRUE,
202 ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql,
203 fields = c(
204 "corpusSigle",
205 "textSigle",
206 "pubDate",
207 "pubPlace",
208 "availability",
209 "textClass",
Marc Kupietz8ad07462026-09-14 11:58:36 +0200210 "dmozDomain",
211 "wikiDomain",
Marc Kupietzd8851222025-05-01 10:57:19 +0200212 "snippet",
213 "tokens"
214 ),
215 accessRewriteFatal = TRUE,
216 verbose = kco@verbose,
217 expand = length(vc) != length(query),
218 as.df = FALSE,
219 context = NULL) {
220 if (length(query) > 1 || length(vc) > 1) {
Marc Kupietzf632fe32026-09-08 07:58:46 +0200221 # expand_grid() and tibble() drop the names of vc, so the labels the
222 # caller gave their virtual corpora are carried along as a column
223 vcLabel <- vcLabels(vc)
Marc Kupietzd8851222025-05-01 10:57:19 +0200224 grid <- if (expand) expand_grid(query = query, vc = vc) else tibble(query = query, vc = vc)
Marc Kupietzf632fe32026-09-08 07:58:46 +0200225 if (!is.null(vcLabel)) {
226 grid$label <- if (expand) rep(vcLabel, times = length(query)) else vcLabel
227 }
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200228
229 # Initialize timing variables for ETA calculation
230 total_queries <- nrow(grid)
231 current_query <- 0
232 start_time <- Sys.time()
233
Marc Kupietzf632fe32026-09-08 07:58:46 +0200234 results <- purrr::pmap(grid, function(query, vc, label = NULL, ...) {
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200235 current_query <<- current_query + 1
236
237 # Execute the single query directly (avoiding recursive call)
238 contentFields <- c("snippet", "tokens")
239 query_fields <- fields
240 if (metadataOnly) {
241 query_fields <- query_fields[!query_fields %in% contentFields]
242 }
243 if (!"textSigle" %in% query_fields) {
244 query_fields <- c(query_fields, "textSigle")
245 }
246 request <-
247 paste0(
248 "?q=",
249 url_encode(enc2utf8(query)),
250 ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""),
251 ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""),
252 ifelse(!metadataOnly, "&show-tokens=true", ""),
253 "&ql=", ql
254 )
255 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
256 requestUrl <- paste0(
257 kco@apiUrl,
258 "search",
259 request,
260 "&fields=",
261 paste(query_fields, collapse = ","),
262 if (metadataOnly) "&access-rewrite-disabled=true" else ""
263 )
264
265 # Show individual query progress
266 log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"", sep = "")
Marc Kupietz10eff992026-09-14 08:31:41 +0200267 queryStart <- Sys.time()
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200268 res <- apiCall(kco, paste0(requestUrl, "&count=0"))
Marc Kupietz10eff992026-09-14 08:31:41 +0200269 queryDuration <- as.numeric(difftime(Sys.time(), queryStart, units = "secs"))
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200270 if (is.null(res)) {
Marc Kupietz10eff992026-09-14 08:31:41 +0200271 log_info(verbose, ": API call failed after ", sprintf("%.1f", queryDuration), "s\n")
272 warning("The request for query \u201c", query, "\u201d failed; the reported results are unreliable.", call. = FALSE)
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200273 totalResults <- 0
274 } else {
275 totalResults <- as.integer(res$meta$totalResults)
276 log_info(verbose, ": ", totalResults, " hits")
277 if (!is.null(res$meta$cached)) {
278 log_info(verbose, " [cached]")
Marc Kupietz10eff992026-09-14 08:31:41 +0200279 }
280 log_info(verbose, ", took ", sprintf("%.1f", queryDuration), "s")
281 if (!is.null(res$meta$timeExceeded)) {
282 warning(
283 "The query \u201c", query, "\u201d was cut short by the KorAP server ",
284 "(timeExceeded); the reported results are incomplete.",
285 call. = FALSE
286 )
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200287 }
Marc Kupietz365660e2025-06-25 15:09:55 +0200288
289 # Calculate and display ETA information on the same line if verbose and we have more than one query
290 if (verbose && total_queries > 1) {
291 eta_info <- calculate_eta(current_query, total_queries, start_time)
292 if (eta_info != "") {
293 elapsed_time <- as.numeric(difftime(Sys.time(), start_time, units = "secs"))
294 avg_time_per_query <- elapsed_time / current_query
295
296 # Add ETA info to the same line - remove the leading ". " for cleaner formatting
297 clean_eta_info <- sub("^\\. ", ". ", eta_info)
298 log_info(verbose, clean_eta_info)
299 }
300 }
301
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200302 log_info(verbose, "\n")
303 }
304
305 result <- data.frame(
306 query = query,
307 totalResults = totalResults,
308 vc = vc,
Marc Kupietz10eff992026-09-14 08:31:41 +0200309 queryDuration = queryDuration,
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200310 webUIRequestUrl = webUIRequestUrl,
311 stringsAsFactors = FALSE
312 )
Marc Kupietzf632fe32026-09-08 07:58:46 +0200313 if (!is.null(label)) {
314 result <- tibble::add_column(result, label = label, .after = "vc")
315 }
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200316
Marc Kupietz6ef61a82025-05-29 16:07:03 +0200317 return(result)
318 })
319
320 results %>% bind_rows()
Marc Kupietzd8851222025-05-01 10:57:19 +0200321 } else {
Marc Kupietz2078bde2023-08-27 16:46:15 +0200322 contentFields <- c("snippet", "tokens")
Marc Kupietza96537f2019-11-09 23:07:44 +0100323 if (metadataOnly) {
324 fields <- fields[!fields %in% contentFields]
325 }
Marc Kupietz80dc6432025-02-07 16:57:40 +0100326 if (!"textSigle" %in% fields) {
327 fields <- c(fields, "textSigle")
328 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100329 request <-
Marc Kupietzd8851222025-05-01 10:57:19 +0200330 paste0(
331 "?q=",
332 url_encode(enc2utf8(query)),
333 ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""),
334 ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""),
335 ifelse(!metadataOnly, "&show-tokens=true", ""),
336 "&ql=", ql
337 )
Marc Kupietza96537f2019-11-09 23:07:44 +0100338 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
339 requestUrl <- paste0(
340 kco@apiUrl,
Marc Kupietzd8851222025-05-01 10:57:19 +0200341 "search",
Marc Kupietza96537f2019-11-09 23:07:44 +0100342 request,
Marc Kupietzd8851222025-05-01 10:57:19 +0200343 "&fields=",
Marc Kupietza96537f2019-11-09 23:07:44 +0100344 paste(fields, collapse = ","),
Marc Kupietzd8851222025-05-01 10:57:19 +0200345 if (metadataOnly) "&access-rewrite-disabled=true" else ""
Marc Kupietza96537f2019-11-09 23:07:44 +0100346 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200347 log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"",
348 sep =
349 ""
350 )
Marc Kupietz10eff992026-09-14 08:31:41 +0200351 queryStart <- Sys.time()
Marc Kupietzd8851222025-05-01 10:57:19 +0200352 res <- apiCall(kco, paste0(requestUrl, "&count=0"))
Marc Kupietz10eff992026-09-14 08:31:41 +0200353 queryDuration <- as.numeric(difftime(Sys.time(), queryStart, units = "secs"))
Marc Kupietza4675722022-02-23 23:55:15 +0100354 if (is.null(res)) {
Marc Kupietza4675722022-02-23 23:55:15 +0100355 message("API call failed.")
Marc Kupietz10eff992026-09-14 08:31:41 +0200356 warning("The request for query \u201c", query, "\u201d failed; the reported results are unreliable.", call. = FALSE)
Marc Kupietza4675722022-02-23 23:55:15 +0100357 totalResults <- 0
358 } else {
Marc Kupietzd8851222025-05-01 10:57:19 +0200359 totalResults <- as.integer(res$meta$totalResults)
Marc Kupietza47d1502023-04-18 15:26:47 +0200360 log_info(verbose, ": ", totalResults, " hits")
Marc Kupietzd8851222025-05-01 10:57:19 +0200361 if (!is.null(res$meta$cached)) {
Marc Kupietz10eff992026-09-14 08:31:41 +0200362 log_info(verbose, " [cached]")
Marc Kupietzd8851222025-05-01 10:57:19 +0200363 }
Marc Kupietz10eff992026-09-14 08:31:41 +0200364 log_info(verbose, ", took ", sprintf("%.1f", queryDuration), "s")
365 if (!is.null(res$meta$timeExceeded)) {
366 warning(
367 "The query \u201c", query, "\u201d was cut short by the KorAP server ",
368 "(timeExceeded); the reported results are incomplete.",
369 call. = FALSE
370 )
371 }
372 log_info(verbose, "\n")
Marc Kupietza4675722022-02-23 23:55:15 +0100373 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200374 if (as.df) {
Marc Kupietza96537f2019-11-09 23:07:44 +0100375 data.frame(
376 query = query,
Marc Kupietza4675722022-02-23 23:55:15 +0100377 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100378 vc = vc,
Marc Kupietz10eff992026-09-14 08:31:41 +0200379 queryDuration = queryDuration,
Marc Kupietza96537f2019-11-09 23:07:44 +0100380 webUIRequestUrl = webUIRequestUrl,
381 stringsAsFactors = FALSE
382 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200383 } else {
Marc Kupietza96537f2019-11-09 23:07:44 +0100384 KorAPQuery(
385 korapConnection = kco,
386 nextStartIndex = 0,
387 fields = fields,
388 requestUrl = requestUrl,
389 request = request,
Marc Kupietza4675722022-02-23 23:55:15 +0100390 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100391 vc = vc,
392 apiResponse = res,
393 webUIRequestUrl = webUIRequestUrl,
Marc Kupietza4675722022-02-23 23:55:15 +0100394 hasMoreMatches = (totalResults > 0),
Marc Kupietza96537f2019-11-09 23:07:44 +0100395 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200396 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100397 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200398 }
399)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200400
Marc Kupietz05a60792024-12-07 16:23:31 +0100401#' @importFrom purrr map
402repair_data_strcuture <- function(x) {
Marc Kupietzd8851222025-05-01 10:57:19 +0200403 if (is.list(x)) {
404 as.character(purrr::map(x, ~ if (length(.x) > 1) {
Marc Kupietz05a60792024-12-07 16:23:31 +0100405 paste(.x, collapse = " ")
406 } else {
407 .x
408 }))
Marc Kupietzd8851222025-05-01 10:57:19 +0200409 } else {
Marc Kupietz05a60792024-12-07 16:23:31 +0100410 ifelse(is.na(x), "", x)
Marc Kupietzd8851222025-05-01 10:57:19 +0200411 }
Marc Kupietz05a60792024-12-07 16:23:31 +0100412}
413
Marc Kupietz62da2b52019-09-12 17:43:34 +0200414#' Fetch the next bunch of results of a KorAP query.
Marc Kupietze95108e2019-09-18 13:23:58 +0200415#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200416#' **`fetchNext`** fetches the next bunch of results of a KorAP query.
Marc Kupietz3f575282019-10-04 14:46:04 +0200417#'
Marc Kupietza8c40f42025-06-24 15:49:52 +0200418#' @family corpus search functions
419#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200420#' @param kqo object obtained from [corpusQuery()]
Marc Kupietz62da2b52019-09-12 17:43:34 +0200421#' @param offset start offset for query results to fetch
422#' @param maxFetch maximum number of query results to fetch
Marc Kupietz25aebc32019-09-16 18:40:50 +0200423#' @param verbose print progress information if true
Marc Kupietz67edcb52021-09-20 21:54:24 +0200424#' @param randomizePageOrder fetch result pages in pseudo random order if true. Use [set.seed()] to set seed for reproducible results.
425#' @return The `kqo` input object with updated slots `collectedMatches`, `apiResponse`, `nextStartIndex`, `hasMoreMatches`
Marc Kupietz62da2b52019-09-12 17:43:34 +0200426#'
Marc Kupietz05b22772020-02-18 21:58:42 +0100427#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200428#' \dontrun{
429#'
Marc Kupietzd3526422025-06-25 09:16:15 +0200430#' q <- KorAPConnection() |>
431#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200432#' fetchNext()
Marc Kupietz05b22772020-02-18 21:58:42 +0100433#' q@collectedMatches
Marc Kupietz657d8e72020-02-25 18:31:50 +0100434#' }
Marc Kupietz05b22772020-02-18 21:58:42 +0100435#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200436#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200437#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz62da2b52019-09-12 17:43:34 +0200438#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200439#' @aliases fetchNext
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200440#' @importFrom dplyr rowwise mutate bind_rows select summarise n select
Marc Kupietzf4881122024-12-17 14:55:39 +0100441#' @importFrom tibble enframe add_column
442#' @importFrom stringr word
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200443#' @importFrom tidyr unnest unchop pivot_wider
444#' @importFrom purrr map
Marc Kupietz632cbd42019-09-06 16:04:51 +0200445#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200446setMethod("fetchNext", "KorAPQuery", function(kqo,
447 offset = kqo@nextStartIndex,
448 maxFetch = maxResultsPerPage,
449 verbose = kqo@korapConnection@verbose,
450 randomizePageOrder = FALSE) {
Marc Kupietza7a8f1b2024-12-18 15:56:19 +0100451 # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
Marc Kupietzd8851222025-05-01 10:57:19 +0200452 results <- key <- name <- tmp_positions <- 0
Marc Kupietza7a8f1b2024-12-18 15:56:19 +0100453
Marc Kupietze95108e2019-09-18 13:23:58 +0200454 if (kqo@totalResults == 0 || offset >= kqo@totalResults) {
455 return(kqo)
Marc Kupietz62da2b52019-09-12 17:43:34 +0200456 }
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200457 use_korap_api <- Sys.getenv("USE_KORAP_API", unset = NA)
Marc Kupietz623d7122025-05-25 12:46:12 +0200458 # Calculate the initial page number (not used directly - keeping for reference)
Marc Kupietze95108e2019-09-18 13:23:58 +0200459 collectedMatches <- kqo@collectedMatches
Marc Kupietz62da2b52019-09-12 17:43:34 +0200460
Marc Kupietz24799fd2025-06-25 14:15:36 +0200461 # Track start time for ETA calculation
462 start_time <- Sys.time()
463
Marc Kupietz623d7122025-05-25 12:46:12 +0200464 # For randomized page order, generate a list of randomized page indices
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200465 if (randomizePageOrder) {
Marc Kupietz623d7122025-05-25 12:46:12 +0200466 # Calculate how many pages we need to fetch based on maxFetch
467 total_pages_to_fetch <- if (!is.na(maxFetch)) {
468 # Either limited by maxFetch or total results, whichever is smaller
469 min(ceiling(maxFetch / maxResultsPerPage), ceiling(kqo@totalResults / maxResultsPerPage))
470 } else {
471 # All pages
472 ceiling(kqo@totalResults / maxResultsPerPage)
473 }
474
475 # Generate randomized page indices (0-based for API)
476 pages <- sample.int(ceiling(kqo@totalResults / maxResultsPerPage), total_pages_to_fetch) - 1
477 page_index <- 1 # Index to track which page in the randomized list we're on
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200478 }
479
Marc Kupietzd8851222025-05-01 10:57:19 +0200480 if (is.null(collectedMatches)) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200481 collectedMatches <- data.frame()
482 }
Marc Kupietz623d7122025-05-25 12:46:12 +0200483
484 # Initialize the page counter properly based on nextStartIndex and any previously fetched results
485 # We add 1 to make it 1-based for display purposes since users expect page numbers to start from 1
486 # For first call, this will be 1, for subsequent calls, it will reflect our actual position
487 current_page_number <- ceiling(offset / maxResultsPerPage) + 1
488
489 # For sequential fetches, keep track of which global page we're on
490 # This is important for correctly showing page numbers in subsequent fetchNext calls
491 page_count_start <- current_page_number
492
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200493 repeat {
Marc Kupietz623d7122025-05-25 12:46:12 +0200494 # Determine which page to fetch next
495 if (randomizePageOrder) {
496 # In randomized mode, get the page from our randomized list using the page_index
497 # Make sure we don't exceed the array bounds
498 if (page_index > length(pages)) {
499 break # No more pages to fetch in randomized mode
500 }
501 current_offset_page <- pages[page_index]
502 # For display purposes in randomized mode, show which page out of the total we're fetching
503 display_page_number <- page_index
504 } else {
505 # In sequential mode, use the current_page_number to calculate the offset
506 current_offset_page <- (current_page_number - 1)
507 display_page_number <- current_page_number
508 }
509
510 # Calculate the actual offset in tokens
511 currentOffset <- current_offset_page * maxResultsPerPage
512
Marc Kupietzef0e9392025-06-18 12:21:49 +0200513 # Build the query with the appropriate count and offset using httr2
514 count_param <- min(if (!is.na(maxFetch)) maxFetch - results else maxResultsPerPage, maxResultsPerPage)
Marc Kupietzecc86702025-06-24 12:12:51 +0200515
Marc Kupietzef0e9392025-06-18 12:21:49 +0200516 # Parse existing URL to preserve all query parameters
517 parsed_url <- httr2::url_parse(kqo@requestUrl)
518 existing_query <- parsed_url$query
Marc Kupietzecc86702025-06-24 12:12:51 +0200519
Marc Kupietzef0e9392025-06-18 12:21:49 +0200520 # Add/update count and offset parameters
521 existing_query$count <- count_param
522 existing_query$offset <- currentOffset
Marc Kupietzecc86702025-06-24 12:12:51 +0200523
Marc Kupietzef0e9392025-06-18 12:21:49 +0200524 # Rebuild the URL with all parameters
525 query <- httr2::url_modify(kqo@requestUrl, query = existing_query)
Marc Kupietz68170952021-06-30 09:37:21 +0200526 res <- apiCall(kqo@korapConnection, query)
527 if (length(res$matches) == 0) {
528 break
529 }
530
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200531 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 +0100532 log_info(verbose, "Using fields API: ")
Marc Kupietz05a60792024-12-07 16:23:31 +0100533 currentMatches <- res$matches$fields %>%
534 purrr::map(~ mutate(.x, value = repair_data_strcuture(value))) %>%
535 tibble::enframe() %>%
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200536 tidyr::unnest(cols = value) %>%
537 tidyr::pivot_wider(names_from = key, id_cols = name, names_repair = "unique") %>%
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200538 dplyr::select(-name)
Marc Kupietzd8851222025-05-01 10:57:19 +0200539 if ("snippet" %in% colnames(res$matches)) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200540 currentMatches$snippet <- res$matches$snippet
541 }
Marc Kupietz3cd2c6c2025-01-08 20:35:39 +0100542 if ("tokens" %in% colnames(res$matches)) {
543 currentMatches$tokens <- res$matches$tokens
544 }
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200545 } else {
546 currentMatches <- res$matches
547 }
548
Marc Kupietze95108e2019-09-18 13:23:58 +0200549 for (field in kqo@fields) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200550 if (!field %in% colnames(currentMatches)) {
551 currentMatches[, field] <- NA
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200552 }
553 }
Marc Kupietzf4881122024-12-17 14:55:39 +0100554 currentMatches <- currentMatches %>%
555 select(kqo@fields) %>%
556 mutate(
Marc Kupietzff712a92025-07-18 09:07:23 +0200557 matchID = res$matches$matchID,
Marc Kupietz0447da02025-01-08 20:51:09 +0100558 tmp_positions = gsub(".*-p(\\d+)-(\\d+).*", "\\1 \\2", res$matches$matchID),
Marc Kupietzf4881122024-12-17 14:55:39 +0100559 matchStart = as.integer(stringr::word(tmp_positions, 1)),
560 matchEnd = as.integer(stringr::word(tmp_positions, 2)) - 1
561 ) %>%
562 select(-tmp_positions)
563
Marc Kupietz62da2b52019-09-12 17:43:34 +0200564 if (!is.list(collectedMatches)) {
565 collectedMatches <- currentMatches
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200566 } else {
Marc Kupietz2078bde2023-08-27 16:46:15 +0200567 collectedMatches <- bind_rows(collectedMatches, currentMatches)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200568 }
Marc Kupietzae9b6172025-05-02 15:50:01 +0200569
Marc Kupietz623d7122025-05-25 12:46:12 +0200570 # Get the actual items per page from the API response
571 # We now consistently use maxResultsPerPage instead
Marc Kupietzacbaab02025-05-01 10:56:35 +0200572
Marc Kupietz623d7122025-05-25 12:46:12 +0200573 # Calculate total pages consistently using fixed maxResultsPerPage
574 # This ensures consistent page counting across the function
575 total_pages <- ceiling(kqo@totalResults / maxResultsPerPage)
576
Marc Kupietz24799fd2025-06-25 14:15:36 +0200577 # Calculate ETA using the centralized function from logging.R
578 current_page <- if (randomizePageOrder) page_index else display_page_number
579 total_pages_to_fetch <- if (!is.na(maxFetch)) {
580 # Account for offset - we can only fetch from the remaining results after offset
581 remaining_results_after_offset <- max(0, kqo@totalResults - offset)
582 min(ceiling(maxFetch / maxResultsPerPage), ceiling(remaining_results_after_offset / maxResultsPerPage))
583 } else {
584 total_pages
585 }
Marc Kupietz365660e2025-06-25 15:09:55 +0200586
Marc Kupietz24799fd2025-06-25 14:15:36 +0200587 eta_info <- calculate_eta(current_page, total_pages_to_fetch, start_time)
Marc Kupietz365660e2025-06-25 15:09:55 +0200588
Marc Kupietz24799fd2025-06-25 14:15:36 +0200589 # Extract timing information for display
Marc Kupietzae9b6172025-05-02 15:50:01 +0200590 time_per_page <- NA
Marc Kupietzae9b6172025-05-02 15:50:01 +0200591 if (!is.null(res$meta$benchmark) && is.character(res$meta$benchmark)) {
Marc Kupietzae9b6172025-05-02 15:50:01 +0200592 time_per_page <- suppressWarnings(as.numeric(sub("s", "", res$meta$benchmark)))
Marc Kupietzacbaab02025-05-01 10:56:35 +0200593 }
594
Marc Kupietz623d7122025-05-25 12:46:12 +0200595 # Create the page display string with proper formatting
Marc Kupietzacbaab02025-05-01 10:56:35 +0200596
Marc Kupietz623d7122025-05-25 12:46:12 +0200597 # For global page tracking, calculate the absolute page number
598 actual_display_number <- if (randomizePageOrder) {
599 current_offset_page + 1 # In randomized mode, this is the actual page (0-based + 1)
600 } else {
601 # In sequential mode, the absolute page number is the actual offset page + 1 (to make it 1-based)
602 current_offset_page + 1
603 }
604
605 # For subsequent calls to fetchNext, we need to calculate the correct page numbers
606 # based on the current batch being fetched
607
608 # For each call to fetchNext, we want to show 1/2, 2/2 (not 3/4, 4/4)
609 # Simply count from 1 within the current batch
610
611 # The relative page number is simply the current position in this batch
612 if (randomizePageOrder) {
613 relative_page_number <- page_index # In randomized mode, we start from 1 in each batch
614 } else {
615 relative_page_number <- display_page_number - (page_count_start - 1)
616 }
617
618 # How many pages will we fetch in this batch?
Marc Kupietz021663d2025-06-18 17:49:22 +0200619 # If maxFetch is specified, calculate the total pages for this fetch operation
Marc Kupietz623d7122025-05-25 12:46:12 +0200620 pages_in_this_batch <- if (!is.na(maxFetch)) {
Marc Kupietz021663d2025-06-18 17:49:22 +0200621 # Account for offset - we can only fetch from the remaining results after offset
622 remaining_results_after_offset <- max(0, kqo@totalResults - offset)
623 min(ceiling(maxFetch / maxResultsPerPage), ceiling(remaining_results_after_offset / maxResultsPerPage))
Marc Kupietz623d7122025-05-25 12:46:12 +0200624 } else {
625 # Otherwise fetch all remaining pages
626 total_pages - page_count_start + 1
627 }
628
629 # The total pages to be shown in this batch
630 batch_total_pages <- pages_in_this_batch
631
632 page_display <- paste0(
633 "Retrieved page ",
634 sprintf(paste0("%", nchar(batch_total_pages), "d"), relative_page_number),
635 "/",
636 sprintf("%d", batch_total_pages)
637 )
638
639 # If randomized, also show which actual page we fetched
640 if (randomizePageOrder) {
641 # Determine the maximum width needed for page numbers (based on total pages)
642 # This ensures consistent alignment
643 max_page_width <- nchar(as.character(total_pages))
644 # Add the actual page number that was fetched (0-based + 1 for display) with proper padding
Marc Kupietz7638ca42025-05-25 13:18:16 +0200645 page_display <- paste0(
646 page_display,
647 sprintf(" (actual page %*d)", max_page_width, current_offset_page + 1)
648 )
Marc Kupietz623d7122025-05-25 12:46:12 +0200649 }
650 # Always show the absolute page number and total pages (for clarity)
651 else {
652 # Show the absolute page number (out of total possible pages)
653 page_display <- paste0(page_display, sprintf(
654 " (page %d of %d total)",
655 actual_display_number, total_pages
656 ))
657 }
658
659 # Add caching or timing information
660 if (!is.null(res$meta$cached)) {
661 page_display <- paste0(page_display, " [cached]")
662 } else {
663 page_display <- paste0(
664 page_display,
665 " in ",
666 if (!is.na(time_per_page)) sprintf("%4.1f", time_per_page) else "?",
Marc Kupietz24799fd2025-06-25 14:15:36 +0200667 "s",
668 eta_info
Marc Kupietz623d7122025-05-25 12:46:12 +0200669 )
670 }
671
672 log_info(verbose, paste0(page_display, "\n"))
673
674 # Increment the appropriate counter based on mode
675 if (randomizePageOrder) {
676 page_index <- page_index + 1
677 } else {
678 current_page_number <- current_page_number + 1
679 }
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200680 results <- results + res$meta$itemsPerPage
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200681 if (nrow(collectedMatches) >= kqo@totalResults || (!is.na(maxFetch) && results >= maxFetch)) {
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200682 break
683 }
684 }
Marc Kupietz68170952021-06-30 09:37:21 +0200685 nextStartIndex <- min(res$meta$startIndex + res$meta$itemsPerPage, kqo@totalResults)
Marc Kupietzd8851222025-05-01 10:57:19 +0200686 KorAPQuery(
687 nextStartIndex = nextStartIndex,
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200688 korapConnection = kqo@korapConnection,
Marc Kupietze95108e2019-09-18 13:23:58 +0200689 fields = kqo@fields,
690 requestUrl = kqo@requestUrl,
691 request = kqo@request,
Marc Kupietz68170952021-06-30 09:37:21 +0200692 totalResults = kqo@totalResults,
Marc Kupietze95108e2019-09-18 13:23:58 +0200693 vc = kqo@vc,
694 webUIRequestUrl = kqo@webUIRequestUrl,
Marc Kupietz68170952021-06-30 09:37:21 +0200695 hasMoreMatches = (kqo@totalResults > nextStartIndex),
Marc Kupietze95108e2019-09-18 13:23:58 +0200696 apiResponse = res,
Marc Kupietzd8851222025-05-01 10:57:19 +0200697 collectedMatches = collectedMatches
698 )
Marc Kupietze95108e2019-09-18 13:23:58 +0200699})
Marc Kupietz62da2b52019-09-12 17:43:34 +0200700
701#' Fetch all results of a KorAP query.
Marc Kupietz62da2b52019-09-12 17:43:34 +0200702#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200703#' **`fetchAll`** fetches all results of a KorAP query.
Marc Kupietza6e4ee62021-03-05 09:00:15 +0100704#'
Marc Kupietza8c40f42025-06-24 15:49:52 +0200705#' @family corpus search functions
Marc Kupietzdc880ac2025-06-24 20:34:43 +0200706#' @param kqo object obtained from [corpusQuery()]
707#' @param verbose print progress information if true
708#' @param ... further arguments passed to [fetchNext()]
709#' @return The updated `kqo` object with all results in `@collectedMatches`
Marc Kupietza8c40f42025-06-24 15:49:52 +0200710#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200711#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200712#' \dontrun{
Marc Kupietzecc86702025-06-24 12:12:51 +0200713#' # Fetch all metadata of every query hit for "Ameisenplage" and show a summary
714#' q <- KorAPConnection() |>
715#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200716#' fetchAll()
Marc Kupietze95108e2019-09-18 13:23:58 +0200717#' q@collectedMatches
Marc Kupietzecc86702025-06-24 12:12:51 +0200718#'
719#' # Fetch also all KWICs
720#' q <- KorAPConnection() |> auth() |>
721#' corpusQuery("Ameisenplage", metadataOnly = FALSE) |>
722#' fetchAll()
723#' q@collectedMatches
724#'
725#' # Retrieve title and text sigle metadata of all texts published on 1958-03-12
726#' q <- KorAPConnection() |>
727#' corpusQuery("<base/s=t>", # this matches each text once
728#' vc = "pubDate in 1958-03-12",
729#' fields = c("textSigle", "title"),
730#' ) |>
731#' fetchAll()
732#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100733#' }
Marc Kupietz62da2b52019-09-12 17:43:34 +0200734#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200735#' @aliases fetchAll
Marc Kupietz62da2b52019-09-12 17:43:34 +0200736#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200737setMethod("fetchAll", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
738 return(fetchNext(kqo, offset = 0, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200739})
740
741#' Fetches the remaining results of a KorAP query.
742#'
Marc Kupietzdc880ac2025-06-24 20:34:43 +0200743#' @param kqo object obtained from [corpusQuery()]
744#' @param verbose print progress information if true
745#' @param ... further arguments passed to [fetchNext()]
746#' @return The updated `kqo` object with remaining results in `@collectedMatches`
747#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200748#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200749#' \dontrun{
750#'
Marc Kupietzd3526422025-06-25 09:16:15 +0200751#' q <- KorAPConnection() |>
752#' corpusQuery("Ameisenplage") |>
Marc Kupietzd8851222025-05-01 10:57:19 +0200753#' fetchRest()
Marc Kupietze95108e2019-09-18 13:23:58 +0200754#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100755#' }
Marc Kupietze95108e2019-09-18 13:23:58 +0200756#'
757#' @aliases fetchRest
Marc Kupietze95108e2019-09-18 13:23:58 +0200758#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200759setMethod("fetchRest", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
760 return(fetchNext(kqo, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200761})
762
Marc Kupietzbdedd022025-10-09 14:14:15 +0200763# Helper to collapse multiple annotation values while preserving order
764collapse_features <- function(values) {
765 if (length(values) == 0) {
766 return(NA_character_)
767 }
768 unique_values <- values[!duplicated(values)]
769 paste(unique_values, collapse = "|")
770}
771
772# Extract token-level annotations from a DOM node
773collect_token_annotations <- function(parent_node) {
774 if (inherits(parent_node, "xml_missing")) {
775 return(list(
776 node = list(),
777 token = character(0),
778 lemma = character(0),
779 pos = character(0),
780 morph = character(0)
781 ))
782 }
783
784 leaf_nodes <- xml2::xml_find_all(parent_node, ".//span[not(.//span)]")
785
786 if (length(leaf_nodes) == 0) {
787 return(list(
788 node = list(),
789 token = character(0),
790 lemma = character(0),
791 pos = character(0),
792 morph = character(0)
793 ))
794 }
795
796 tokens <- character(0)
797 lemmas <- character(0)
798 pos_tags <- character(0)
799 morph_tags <- character(0)
800 kept_nodes <- list()
801
802 for (idx in seq_along(leaf_nodes)) {
803 leaf <- leaf_nodes[[idx]]
804 token_text <- trimws(xml2::xml_text(leaf))
805 if (identical(token_text, "")) {
806 next
807 }
808
809 kept_nodes[[length(kept_nodes) + 1]] <- leaf
810 tokens <- c(tokens, token_text)
811
812 ancestors <- xml2::xml_find_all(leaf, "ancestor-or-self::span")
813 titles <- xml2::xml_attr(ancestors, "title")
814 titles <- titles[!is.na(titles)]
815
816 feature_pieces <- if (length(titles) > 0) unlist(strsplit(titles, "[[:space:]]+")) else character(0)
817
818 lemma_values <- sub('.*?/l:(.*)$', '\\1', feature_pieces[grepl('/l:', feature_pieces)], perl = TRUE)
819 pos_values <- sub('.*?/p:(.*)$', '\\1', feature_pieces[grepl('/p:', feature_pieces)], perl = TRUE)
820 morph_values <- sub('.*?/m:(.*)$', '\\1', feature_pieces[grepl('/m:', feature_pieces)], perl = TRUE)
821
822 lemmas <- c(lemmas, collapse_features(lemma_values))
823 pos_tags <- c(pos_tags, collapse_features(pos_values))
824 morph_tags <- c(morph_tags, collapse_features(morph_values))
825 }
826
827 list(
828 node = kept_nodes,
829 token = tokens,
830 lemma = lemmas,
831 pos = pos_tags,
832 morph = morph_tags
833 )
834}
835
Marc Kupietza29f3d42025-07-18 10:14:43 +0200836#'
837#' Parse XML annotations into linguistic layers
838#'
839#' Internal helper function to extract linguistic annotations (lemma, POS, morphology)
840#' from XML annotation snippets returned by the KorAP API.
841#'
842#' @param xml_snippet XML string containing annotation data
843#' @return Named list with vectors for 'token', 'lemma', 'pos', and 'morph'
844#' @keywords internal
845parse_xml_annotations <- function(xml_snippet) {
846 if (is.null(xml_snippet) || is.na(xml_snippet) || xml_snippet == "") {
847 return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0)))
848 }
849
Marc Kupietzbdedd022025-10-09 14:14:15 +0200850 doc <- tryCatch(xml2::read_html(paste0("<root>", xml_snippet, "</root>")), error = function(e) NULL)
851 if (is.null(doc)) {
852 return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0)))
Marc Kupietzcd452182025-10-09 13:28:41 +0200853 }
854
Marc Kupietzbdedd022025-10-09 14:14:15 +0200855 match_node <- xml2::xml_find_first(doc, ".//span[contains(@class, 'match')]")
856 if (inherits(match_node, "xml_missing")) {
857 match_node <- xml2::xml_find_first(doc, ".//span")
858 if (inherits(match_node, "xml_missing")) {
859 return(list(token = character(0), lemma = character(0), pos = character(0), morph = character(0)))
Marc Kupietza29f3d42025-07-18 10:14:43 +0200860 }
861 }
862
Marc Kupietzbdedd022025-10-09 14:14:15 +0200863 token_info <- collect_token_annotations(match_node)
Marc Kupietza29f3d42025-07-18 10:14:43 +0200864
Marc Kupietzbdedd022025-10-09 14:14:15 +0200865 list(
866 token = token_info$token,
867 lemma = token_info$lemma,
868 pos = token_info$pos,
869 morph = token_info$morph
870 )
Marc Kupietza29f3d42025-07-18 10:14:43 +0200871}
872
873#'
874#' Parse XML annotations into linguistic layers with left/match/right structure
875#'
876#' Internal helper function to extract linguistic annotations (lemma, POS, morphology)
877#' from XML annotation snippets returned by the KorAP API, split into left context,
878#' match, and right context sections like the tokens field.
879#'
880#' @param xml_snippet XML string containing annotation data
881#' @return Named list with nested structure containing left/match/right for 'atokens', 'lemma', 'pos', and 'morph'
882#' @keywords internal
883parse_xml_annotations_structured <- function(xml_snippet) {
884 if (is.null(xml_snippet) || is.na(xml_snippet) || xml_snippet == "") {
885 empty_result <- list(left = character(0), match = character(0), right = character(0))
886 return(list(
887 atokens = empty_result,
888 lemma = empty_result,
889 pos = empty_result,
890 morph = empty_result
891 ))
892 }
893
Marc Kupietzbdedd022025-10-09 14:14:15 +0200894 doc <- tryCatch(xml2::read_html(paste0("<root>", xml_snippet, "</root>")), error = function(e) NULL)
895 if (is.null(doc)) {
896 empty_result <- list(left = character(0), match = character(0), right = character(0))
Marc Kupietza29f3d42025-07-18 10:14:43 +0200897 return(list(
Marc Kupietzbdedd022025-10-09 14:14:15 +0200898 atokens = empty_result,
899 lemma = empty_result,
900 pos = empty_result,
901 morph = empty_result
Marc Kupietza29f3d42025-07-18 10:14:43 +0200902 ))
903 }
904
Marc Kupietzbdedd022025-10-09 14:14:15 +0200905 match_node <- xml2::xml_find_first(doc, ".//span[contains(@class, 'match')]")
906 if (inherits(match_node, "xml_missing")) {
907 empty_result <- list(left = character(0), match = character(0), right = character(0))
908 return(list(
909 atokens = empty_result,
910 lemma = empty_result,
911 pos = empty_result,
912 morph = empty_result
913 ))
Marc Kupietza29f3d42025-07-18 10:14:43 +0200914 }
Marc Kupietzc643a122025-07-18 18:18:36 +0200915
Marc Kupietzbdedd022025-10-09 14:14:15 +0200916 token_info <- collect_token_annotations(match_node)
917 tokens <- token_info$token
918 lemmas <- token_info$lemma
919 pos_tags <- token_info$pos
920 morph_tags <- token_info$morph
921 nodes <- token_info$node
Marc Kupietzc643a122025-07-18 18:18:36 +0200922
Marc Kupietzbdedd022025-10-09 14:14:15 +0200923 if (length(tokens) == 0) {
924 empty_result <- list(left = character(0), match = character(0), right = character(0))
925 return(list(
926 atokens = empty_result,
927 lemma = empty_result,
928 pos = empty_result,
929 morph = empty_result
930 ))
931 }
Marc Kupietzc643a122025-07-18 18:18:36 +0200932
Marc Kupietzbdedd022025-10-09 14:14:15 +0200933 mark_flags <- vapply(nodes, function(n) {
934 !inherits(xml2::xml_find_first(n, "ancestor::mark"), "xml_missing")
935 }, logical(1))
Marc Kupietzc643a122025-07-18 18:18:36 +0200936
Marc Kupietzbdedd022025-10-09 14:14:15 +0200937 if (any(mark_flags)) {
938 first_idx <- which(mark_flags)[1]
939 last_idx <- tail(which(mark_flags), 1)
Marc Kupietza29f3d42025-07-18 10:14:43 +0200940 } else {
Marc Kupietzbdedd022025-10-09 14:14:15 +0200941 first_idx <- 1
942 last_idx <- length(tokens)
Marc Kupietza29f3d42025-07-18 10:14:43 +0200943 }
944
Marc Kupietzbdedd022025-10-09 14:14:15 +0200945 sections <- rep("match", length(tokens))
946 if (first_idx > 1) {
947 sections[seq_len(first_idx - 1)] <- "left"
948 }
949 if (last_idx < length(tokens)) {
950 sections[seq(from = last_idx + 1, to = length(tokens))] <- "right"
951 }
Marc Kupietza29f3d42025-07-18 10:14:43 +0200952
Marc Kupietzbdedd022025-10-09 14:14:15 +0200953 subset_by_section <- function(values, section) {
954 idx <- sections == section
955 if (!any(idx)) {
956 return(character(0))
957 }
958 values[idx]
959 }
960
961 atokens <- list(
962 left = subset_by_section(tokens, "left"),
963 match = subset_by_section(tokens, "match"),
964 right = subset_by_section(tokens, "right")
965 )
966
967 lemma <- list(
968 left = subset_by_section(lemmas, "left"),
969 match = subset_by_section(lemmas, "match"),
970 right = subset_by_section(lemmas, "right")
971 )
972
973 pos <- list(
974 left = subset_by_section(pos_tags, "left"),
975 match = subset_by_section(pos_tags, "match"),
976 right = subset_by_section(pos_tags, "right")
977 )
978
979 morph <- list(
980 left = subset_by_section(morph_tags, "left"),
981 match = subset_by_section(morph_tags, "match"),
982 right = subset_by_section(morph_tags, "right")
983 )
984
985 list(
986 atokens = atokens,
987 lemma = lemma,
988 pos = pos,
989 morph = morph
990 )
Marc Kupietza29f3d42025-07-18 10:14:43 +0200991}
992
Marc Kupietze52b2952025-07-17 16:53:02 +0200993#' Fetch annotations for all collected matches
994#'
Marc Kupietz89f796e2025-07-19 09:05:06 +0200995#' `r lifecycle::badge("experimental")`
996#'
997#' **`fetchAnnotations`** fetches annotations (only token annotations, for now)
998#' for all matches in the `@collectedMatches` slot
Marc Kupietzc643a122025-07-18 18:18:36 +0200999#' of a KorAPQuery object and adds annotation columns directly to the `@collectedMatches`
Marc Kupietz89f796e2025-07-19 09:05:06 +02001000#' data frame. The method uses the `matchID` from collected matches.
Marc Kupietza29f3d42025-07-18 10:14:43 +02001001#'
1002#' **Important**: For copyright-restricted corpora, users must be authorized via [auth()]
1003#' and the initial corpus query must have `metadataOnly = FALSE` to ensure snippets are
1004#' available for annotation parsing.
1005#'
1006#' The method parses XML snippet annotations and adds linguistic columns to the data frame:
1007#' - `pos`: data frame with `left`, `match`, `right` columns, each containing list vectors of part-of-speech tags
1008#' - `lemma`: data frame with `left`, `match`, `right` columns, each containing list vectors of lemmas
1009#' - `morph`: data frame with `left`, `match`, `right` columns, each containing list vectors of morphological tags
1010#' - `atokens`: data frame with `left`, `match`, `right` columns, each containing list vectors of token text (from annotations)
1011#' - `annotation_snippet`: original XML snippet from the annotation API
Marc Kupietze52b2952025-07-17 16:53:02 +02001012#'
1013#' @family corpus search functions
Marc Kupietz89f796e2025-07-19 09:05:06 +02001014#' @concept Annotations
Marc Kupietze52b2952025-07-17 16:53:02 +02001015#'
Marc Kupietza29f3d42025-07-18 10:14:43 +02001016#' @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 +02001017#' @param foundry string specifying the foundry to use for annotations (default: "tt" for Tree-Tagger)
Marc Kupietz93787d52025-09-03 13:33:25 +02001018#' @param overwrite logical; if TRUE, re-fetch and replace any existing
1019#' annotation columns. If FALSE (default), only add missing annotation layers
1020#' and preserve already fetched ones (e.g., keep POS/lemma from a previous
1021#' foundry while adding morph from another).
Marc Kupietze52b2952025-07-17 16:53:02 +02001022#' @param verbose print progress information if true
Marc Kupietz0af75932025-09-09 18:14:16 +02001023#' @return The updated `kqo` object with annotation columns
Marc Kupietz89f796e2025-07-19 09:05:06 +02001024#' like `pos`, `lemma`, `morph` (and `atokens` and `annotation_snippet`)
1025#' in the `@collectedMatches` slot. Each column is a data frame
1026#' with `left`, `match`, and `right` columns containing list vectors of annotations
1027#' for the left context, matched tokens, and right context, respectively.
1028#' The original XML snippet for each match is also stored in `annotation_snippet`.
Marc Kupietze52b2952025-07-17 16:53:02 +02001029#'
1030#' @examples
1031#' \dontrun{
1032#'
1033#' # Fetch annotations for matches using Tree-Tagger foundry
Marc Kupietza29f3d42025-07-18 10:14:43 +02001034#' # Note: Authorization required for copyright-restricted corpora
Marc Kupietze52b2952025-07-17 16:53:02 +02001035#' q <- KorAPConnection() |>
Marc Kupietza29f3d42025-07-18 10:14:43 +02001036#' auth() |>
1037#' corpusQuery("Ameisenplage", metadataOnly = FALSE) |>
Marc Kupietze52b2952025-07-17 16:53:02 +02001038#' fetchNext(maxFetch = 10) |>
1039#' fetchAnnotations()
Marc Kupietze52b2952025-07-17 16:53:02 +02001040#'
Marc Kupietza29f3d42025-07-18 10:14:43 +02001041#' # Access linguistic annotations for match i:
Marc Kupietz6aa5a0d2025-09-08 17:51:47 +02001042#' pos_tags <- q@collectedMatches$pos
1043#' # Data frame with left/match/right columns for POS tags
1044#' lemmas <- q@collectedMatches$lemma
1045#' # Data frame with left/match/right columns for lemmas
1046#' morphology <- q@collectedMatches$morph
1047#' # Data frame with left/match/right columns for morphological tags
1048#' atokens <- q@collectedMatches$atokens
1049#' # Data frame with left/match/right columns for annotation token text
Marc Kupietz0af75932025-09-09 18:14:16 +02001050#' # Original XML snippet for match i
1051#' raw_snippet <- q@collectedMatches$annotation_snippet[[i]]
Marc Kupietzc643a122025-07-18 18:18:36 +02001052#'
Marc Kupietza29f3d42025-07-18 10:14:43 +02001053#' # Access specific components:
Marc Kupietz0af75932025-09-09 18:14:16 +02001054#' # POS tags for the matched tokens in match i
1055#' match_pos <- q@collectedMatches$pos$match[[i]]
1056#' # Lemmas for the left context in match i
1057#' left_lemmas <- q@collectedMatches$lemma$left[[i]]
1058#' # Token text for the right context in match i
1059#' right_tokens <- q@collectedMatches$atokens$right[[i]]
Marc Kupietza29f3d42025-07-18 10:14:43 +02001060#'
Marc Kupietz89f796e2025-07-19 09:05:06 +02001061#' # Use a different foundry (e.g., MarMoT)
Marc Kupietze52b2952025-07-17 16:53:02 +02001062#' q <- KorAPConnection() |>
Marc Kupietza29f3d42025-07-18 10:14:43 +02001063#' auth() |>
1064#' corpusQuery("Ameisenplage", metadataOnly = FALSE) |>
Marc Kupietze52b2952025-07-17 16:53:02 +02001065#' fetchNext(maxFetch = 10) |>
Marc Kupietz89f796e2025-07-19 09:05:06 +02001066#' fetchAnnotations(foundry = "marmot")
1067#' q@collectedMatches$pos$left[1] # POS tags for the left context of the first match
Marc Kupietze52b2952025-07-17 16:53:02 +02001068#' }
Marc Kupietze52b2952025-07-17 16:53:02 +02001069#' @export
Marc Kupietz0af75932025-09-09 18:14:16 +02001070setMethod("fetchAnnotations", "KorAPQuery", function(kqo,
1071 foundry = "tt",
1072 overwrite = FALSE,
1073 verbose = kqo@korapConnection@verbose) {
1074 if (is.null(kqo@collectedMatches) ||
1075 nrow(kqo@collectedMatches) == 0) {
1076 warning("No collected matches found. Please run fetchNext() or fetchAll() first.")
1077 return(kqo)
1078 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001079
Marc Kupietze52b2952025-07-17 16:53:02 +02001080 df <- kqo@collectedMatches
1081 kco <- kqo@korapConnection
Marc Kupietza29f3d42025-07-18 10:14:43 +02001082
Marc Kupietza29f3d42025-07-18 10:14:43 +02001083 # Initialize annotation columns as data frames (like tokens field)
1084 # Create the structure more explicitly to avoid assignment issues
1085 nrows <- nrow(df)
Marc Kupietzc643a122025-07-18 18:18:36 +02001086
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001087 # Pre-compute the empty character vector list to avoid repeated computation
1088 empty_char_list <- I(replicate(nrows, character(0), simplify = FALSE))
Marc Kupietz0af75932025-09-09 18:14:16 +02001089
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001090 # Helper function to create annotation data frame structure
1091 create_annotation_df <- function(empty_list) {
1092 data.frame(
1093 left = empty_list,
1094 match = empty_list,
1095 right = empty_list,
1096 stringsAsFactors = FALSE
1097 )
1098 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001099
Marc Kupietz93787d52025-09-03 13:33:25 +02001100 # Track which annotation columns already existed to decide overwrite behavior
1101 existing_types <- list(
1102 pos = "pos" %in% colnames(df),
1103 lemma = "lemma" %in% colnames(df),
1104 morph = "morph" %in% colnames(df),
1105 atokens = "atokens" %in% colnames(df),
1106 annotation_snippet = "annotation_snippet" %in% colnames(df)
1107 )
1108
1109 # Initialize annotation columns using the helper function
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001110 annotation_types <- c("pos", "lemma", "morph", "atokens")
1111 for (type in annotation_types) {
Marc Kupietz93787d52025-09-03 13:33:25 +02001112 if (overwrite || !existing_types[[type]]) {
1113 df[[type]] <- create_annotation_df(empty_char_list)
1114 }
Marc Kupietz03d2b1a2025-07-19 09:14:45 +02001115 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001116
Marc Kupietz93787d52025-09-03 13:33:25 +02001117 if (overwrite || !existing_types$annotation_snippet) {
feldmuellera02f1932025-09-15 16:38:06 +02001118 df$annotation_snippet <- rep(NA_character_, nrows) # Fixed line
Marc Kupietz93787d52025-09-03 13:33:25 +02001119 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001120
Marc Kupietze8c0fef2025-07-18 19:59:04 +02001121 # Initialize timing for ETA calculation
1122 start_time <- Sys.time()
1123 if (verbose) {
1124 log_info(verbose, paste("Starting to fetch annotations for", nrows, "matches\n"))
1125 }
1126
Marc Kupietz93787d52025-09-03 13:33:25 +02001127 # Helper to decide if existing annotation row is effectively empty
1128 is_empty_annotation_row <- function(ann_df, row_index) {
1129 if (is.null(ann_df) || nrow(ann_df) < row_index) return(TRUE)
1130 left_val <- ann_df$left[[row_index]]
1131 match_val <- ann_df$match[[row_index]]
1132 right_val <- ann_df$right[[row_index]]
1133 all(
1134 (is.null(left_val) || (length(left_val) == 0) || all(is.na(left_val))),
1135 (is.null(match_val) || (length(match_val) == 0) || all(is.na(match_val))),
1136 (is.null(right_val) || (length(right_val) == 0) || all(is.na(right_val)))
1137 )
1138 }
1139
Marc Kupietze52b2952025-07-17 16:53:02 +02001140 for (i in seq_len(nrow(df))) {
Marc Kupietze8c0fef2025-07-18 19:59:04 +02001141 # ETA logging
1142 if (verbose && i > 1) {
1143 eta_info <- calculate_eta(i, nrows, start_time)
1144 log_info(verbose, paste("Fetching annotations for match", i, "of", nrows, eta_info, "\n"))
1145 }
Marc Kupietzff712a92025-07-18 09:07:23 +02001146 # Use matchID if available, otherwise fall back to constructing from matchStart/matchEnd
1147 if ("matchID" %in% colnames(df) && !is.na(df$matchID[i])) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001148 # matchID format: "match-match-A00/JUN/39609-p202-203" or encrypted format like
1149 # "match-DNB10/CSL/80400-p2343-2344x_MinDOhu_P6dd2MMZJyyus_7MairdKnr1LxY07Cya-Ow"
1150 # Extract document path and position, handling both regular and encrypted formats
Marc Kupietzc643a122025-07-18 18:18:36 +02001151
Marc Kupietza29f3d42025-07-18 10:14:43 +02001152 # More flexible regex to extract the document path with position and encryption
1153 # Look for pattern: match-(...)-p(\d+)-(\d+)(.*) where (.*) is the encrypted part
1154 # We need to capture the entire path including the encrypted suffix
1155 match_result <- regexpr("match-(.+?-p\\d+-\\d+.*)", df$matchID[i], perl = TRUE)
Marc Kupietzc643a122025-07-18 18:18:36 +02001156
Marc Kupietza29f3d42025-07-18 10:14:43 +02001157 if (match_result > 0) {
1158 # Extract the complete path including encryption (everything after "match-")
1159 doc_path_with_pos_and_encryption <- gsub("^match-(.+)$", "\\1", df$matchID[i], perl = TRUE)
1160 # Convert the dash before position to slash, but keep everything after the position
1161 match_path <- gsub("-p(\\d+-\\d+.*)", "/p\\1", doc_path_with_pos_and_encryption)
Marc Kupietz25121302025-07-19 08:45:43 +02001162 # Use httr2 to construct URL safely
1163 base_url <- paste0(kco@apiUrl, "corpus/", match_path)
1164 req <- httr2::url_modify(base_url, query = list(foundry = foundry))
Marc Kupietza29f3d42025-07-18 10:14:43 +02001165 } else {
Marc Kupietz25121302025-07-19 08:45:43 +02001166 # If regex fails, fall back to the old method with httr2
1167 # Format numbers to avoid scientific notation
1168 match_start <- format(df$matchStart[i], scientific = FALSE)
1169 match_end <- format(df$matchEnd[i], scientific = FALSE)
1170 base_url <- paste0(kco@apiUrl, "corpus/", df$textSigle[i], "/", "p", match_start, "-", match_end)
1171 req <- httr2::url_modify(base_url, query = list(foundry = foundry))
Marc Kupietzff712a92025-07-18 09:07:23 +02001172 }
1173 } else {
Marc Kupietz25121302025-07-19 08:45:43 +02001174 # Fallback to the old method with httr2
1175 # Format numbers to avoid scientific notation
1176 match_start <- format(df$matchStart[i], scientific = FALSE)
1177 match_end <- format(df$matchEnd[i], scientific = FALSE)
1178 base_url <- paste0(kco@apiUrl, "corpus/", df$textSigle[i], "/", "p", match_start, "-", match_end)
1179 req <- httr2::url_modify(base_url, query = list(foundry = foundry))
Marc Kupietzff712a92025-07-18 09:07:23 +02001180 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001181
Marc Kupietze52b2952025-07-17 16:53:02 +02001182 tryCatch({
1183 res <- apiCall(kco, req)
Marc Kupietzc643a122025-07-18 18:18:36 +02001184
Marc Kupietze52b2952025-07-17 16:53:02 +02001185 if (!is.null(res)) {
Marc Kupietz93787d52025-09-03 13:33:25 +02001186 # Store the raw annotation snippet (respect overwrite flag)
1187 if (overwrite || !existing_types$annotation_snippet || is.null(df$annotation_snippet[[i]]) || is.na(df$annotation_snippet[[i]])) {
1188 df$annotation_snippet[[i]] <- if (is.list(res) && "snippet" %in% names(res)) res$snippet else NA
1189 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001190
1191 # Parse XML annotations if snippet is available
1192 if (is.list(res) && "snippet" %in% names(res)) {
1193 parsed_annotations <- parse_xml_annotations_structured(res$snippet)
1194
1195 # Store the parsed linguistic data in data frame format (like tokens)
1196 # Use individual assignment to avoid data frame mismatch errors
1197 tryCatch({
1198 # Assign POS annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001199 if (overwrite || !existing_types$pos || is_empty_annotation_row(df$pos, i)) {
1200 df$pos$left[i] <- list(parsed_annotations$pos$left)
1201 df$pos$match[i] <- list(parsed_annotations$pos$match)
1202 df$pos$right[i] <- list(parsed_annotations$pos$right)
1203 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001204
Marc Kupietza29f3d42025-07-18 10:14:43 +02001205 # Assign lemma annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001206 if (overwrite || !existing_types$lemma || is_empty_annotation_row(df$lemma, i)) {
1207 df$lemma$left[i] <- list(parsed_annotations$lemma$left)
1208 df$lemma$match[i] <- list(parsed_annotations$lemma$match)
1209 df$lemma$right[i] <- list(parsed_annotations$lemma$right)
1210 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001211
Marc Kupietza29f3d42025-07-18 10:14:43 +02001212 # Assign morphology annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001213 if (overwrite || !existing_types$morph || is_empty_annotation_row(df$morph, i)) {
1214 df$morph$left[i] <- list(parsed_annotations$morph$left)
1215 df$morph$match[i] <- list(parsed_annotations$morph$match)
1216 df$morph$right[i] <- list(parsed_annotations$morph$right)
1217 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001218
Marc Kupietza29f3d42025-07-18 10:14:43 +02001219 # Assign token annotations
Marc Kupietz93787d52025-09-03 13:33:25 +02001220 if (overwrite || !existing_types$atokens || is_empty_annotation_row(df$atokens, i)) {
1221 df$atokens$left[i] <- list(parsed_annotations$atokens$left)
1222 df$atokens$match[i] <- list(parsed_annotations$atokens$match)
1223 df$atokens$right[i] <- list(parsed_annotations$atokens$right)
1224 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001225 }, error = function(assign_error) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001226 # Set empty character vectors on assignment error using list assignment
Marc Kupietz93787d52025-09-03 13:33:25 +02001227 if (overwrite || !existing_types$pos) {
1228 df$pos$left[i] <<- list(character(0))
1229 df$pos$match[i] <<- list(character(0))
1230 df$pos$right[i] <<- list(character(0))
1231 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001232
Marc Kupietz93787d52025-09-03 13:33:25 +02001233 if (overwrite || !existing_types$lemma) {
1234 df$lemma$left[i] <<- list(character(0))
1235 df$lemma$match[i] <<- list(character(0))
1236 df$lemma$right[i] <<- list(character(0))
1237 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001238
Marc Kupietz93787d52025-09-03 13:33:25 +02001239 if (overwrite || !existing_types$morph) {
1240 df$morph$left[i] <<- list(character(0))
1241 df$morph$match[i] <<- list(character(0))
1242 df$morph$right[i] <<- list(character(0))
1243 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001244
Marc Kupietz93787d52025-09-03 13:33:25 +02001245 if (overwrite || !existing_types$atokens) {
1246 df$atokens$left[i] <<- list(character(0))
1247 df$atokens$match[i] <<- list(character(0))
1248 df$atokens$right[i] <<- list(character(0))
1249 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001250 })
Marc Kupietza29f3d42025-07-18 10:14:43 +02001251 } else {
1252 # No snippet available, store empty vectors
Marc Kupietz93787d52025-09-03 13:33:25 +02001253 if (overwrite || !existing_types$pos) {
1254 df$pos$left[i] <- list(character(0))
1255 df$pos$match[i] <- list(character(0))
1256 df$pos$right[i] <- list(character(0))
1257 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001258
Marc Kupietz93787d52025-09-03 13:33:25 +02001259 if (overwrite || !existing_types$lemma) {
1260 df$lemma$left[i] <- list(character(0))
1261 df$lemma$match[i] <- list(character(0))
1262 df$lemma$right[i] <- list(character(0))
1263 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001264
Marc Kupietz93787d52025-09-03 13:33:25 +02001265 if (overwrite || !existing_types$morph) {
1266 df$morph$left[i] <- list(character(0))
1267 df$morph$match[i] <- list(character(0))
1268 df$morph$right[i] <- list(character(0))
1269 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001270
Marc Kupietz93787d52025-09-03 13:33:25 +02001271 if (overwrite || !existing_types$atokens) {
1272 df$atokens$left[i] <- list(character(0))
1273 df$atokens$match[i] <- list(character(0))
1274 df$atokens$right[i] <- list(character(0))
1275 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001276 }
Marc Kupietze52b2952025-07-17 16:53:02 +02001277 } else {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001278 # Store NAs for failed requests
Marc Kupietz93787d52025-09-03 13:33:25 +02001279 if (overwrite || !existing_types$pos) {
1280 df$pos$left[i] <- list(NA)
1281 df$pos$match[i] <- list(NA)
1282 df$pos$right[i] <- list(NA)
1283 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001284
Marc Kupietz93787d52025-09-03 13:33:25 +02001285 if (overwrite || !existing_types$lemma) {
1286 df$lemma$left[i] <- list(NA)
1287 df$lemma$match[i] <- list(NA)
1288 df$lemma$right[i] <- list(NA)
1289 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001290
Marc Kupietz93787d52025-09-03 13:33:25 +02001291 if (overwrite || !existing_types$morph) {
1292 df$morph$left[i] <- list(NA)
1293 df$morph$match[i] <- list(NA)
1294 df$morph$right[i] <- list(NA)
1295 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001296
Marc Kupietz93787d52025-09-03 13:33:25 +02001297 if (overwrite || !existing_types$atokens) {
1298 df$atokens$left[i] <- list(NA)
1299 df$atokens$match[i] <- list(NA)
1300 df$atokens$right[i] <- list(NA)
1301 }
1302 if (overwrite || !existing_types$annotation_snippet) {
1303 df$annotation_snippet[[i]] <- NA
1304 }
Marc Kupietze52b2952025-07-17 16:53:02 +02001305 }
1306 }, error = function(e) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001307 # Store NAs for failed requests
Marc Kupietz93787d52025-09-03 13:33:25 +02001308 if (overwrite || !existing_types$pos) {
1309 df$pos$left[i] <- list(NA)
1310 df$pos$match[i] <- list(NA)
1311 df$pos$right[i] <- list(NA)
1312 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001313
Marc Kupietz93787d52025-09-03 13:33:25 +02001314 if (overwrite || !existing_types$lemma) {
1315 df$lemma$left[i] <- list(NA)
1316 df$lemma$match[i] <- list(NA)
1317 df$lemma$right[i] <- list(NA)
1318 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001319
Marc Kupietz93787d52025-09-03 13:33:25 +02001320 if (overwrite || !existing_types$morph) {
1321 df$morph$left[i] <- list(NA)
1322 df$morph$match[i] <- list(NA)
1323 df$morph$right[i] <- list(NA)
1324 }
Marc Kupietzc643a122025-07-18 18:18:36 +02001325
Marc Kupietz93787d52025-09-03 13:33:25 +02001326 if (overwrite || !existing_types$atokens) {
1327 df$atokens$left[i] <- list(NA)
1328 df$atokens$match[i] <- list(NA)
1329 df$atokens$right[i] <- list(NA)
1330 }
1331 if (overwrite || !existing_types$annotation_snippet) {
1332 df$annotation_snippet[[i]] <- NA
1333 }
Marc Kupietze52b2952025-07-17 16:53:02 +02001334 })
1335 }
Marc Kupietza29f3d42025-07-18 10:14:43 +02001336
Marc Kupietza29f3d42025-07-18 10:14:43 +02001337 # Validate data frame structure before assignment
1338 if (nrow(df) != nrow(kqo@collectedMatches)) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001339 }
1340
1341 # Update the collectedMatches with annotation data
1342 tryCatch({
1343 kqo@collectedMatches <- df
1344 }, error = function(assign_error) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001345 # Try a safer approach: add columns individually
1346 tryCatch({
1347 kqo@collectedMatches$pos <- df$pos
Marc Kupietzc643a122025-07-18 18:18:36 +02001348 kqo@collectedMatches$lemma <- df$lemma
Marc Kupietza29f3d42025-07-18 10:14:43 +02001349 kqo@collectedMatches$morph <- df$morph
1350 kqo@collectedMatches$atokens <- df$atokens
1351 kqo@collectedMatches$annotation_snippet <- df$annotation_snippet
1352 }, error = function(col_error) {
Marc Kupietza29f3d42025-07-18 10:14:43 +02001353 warning("Failed to add annotation data to collectedMatches")
1354 })
1355 })
1356
Marc Kupietze8c0fef2025-07-18 19:59:04 +02001357 if (verbose) {
1358 elapsed_time <- Sys.time() - start_time
1359 log_info(verbose, paste("Finished fetching annotations for", nrows, "matches in", format_duration(as.numeric(elapsed_time, units = "secs")), "\n"))
1360 }
1361
Marc Kupietze52b2952025-07-17 16:53:02 +02001362 return(kqo)
1363})
1364
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001365#' Query frequencies of search expressions in virtual corpora
Marc Kupietz3f575282019-10-04 14:46:04 +02001366#'
Marc Kupietz67edcb52021-09-20 21:54:24 +02001367#' **`frequencyQuery`** combines [corpusQuery()], [corpusStats()] and
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001368#' [ci()] to compute a tibble with the absolute and relative frequencies and
Marc Kupietz3f575282019-10-04 14:46:04 +02001369#' confidence intervals of one ore multiple search terms across one or multiple
1370#' virtual corpora.
1371#'
Marc Kupietza8c40f42025-06-24 15:49:52 +02001372#' @family frequency analysis
Marc Kupietz3f575282019-10-04 14:46:04 +02001373#' @aliases frequencyQuery
Marc Kupietz3f575282019-10-04 14:46:04 +02001374#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +02001375#' \dontrun{
1376#'
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001377#' KorAPConnection(verbose = TRUE) |>
Marc Kupietz3f575282019-10-04 14:46:04 +02001378#' frequencyQuery(c("Mücke", "Schnake"), paste0("pubDate in ", 2000:2003))
Marc Kupietz05b22772020-02-18 21:58:42 +01001379#' }
Marc Kupietz3f575282019-10-04 14:46:04 +02001380#'
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001381# @inheritParams corpusQuery
Marc Kupietz617266d2025-02-27 10:43:07 +01001382#' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()`
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001383#' @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`.
1384#' @param vc virtual corpus definition(s) (can be a vector)
Marc Kupietz67edcb52021-09-20 21:54:24 +02001385#' @param conf.level confidence level of the returned confidence interval (passed through [ci()] to [prop.test()]).
1386#' @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 +02001387#' @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 +02001388#' @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 +02001389#' @export
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001390#'
1391#' @return A tibble, with each row containing the following result columns for query and vc combinations:
1392#' - **query**: the query string used for the frequency analysis.
1393#' - **totalResults**: absolute frequency of query matches in the vc.
1394#' - **vc**: virtual corpus used for the query.
Marc Kupietz10eff992026-09-14 08:31:41 +02001395#' - **queryDuration**: client-side duration of the request in seconds.
Marc Kupietzad8d2ed2025-04-05 15:37:38 +02001396#' - **webUIRequestUrl**: URL of the corresponding web UI request with respect to query and vc.
1397#' - **total**: total number of words in vc.
1398#' - **f**: relative frequency of query matches in the vc.
1399#' - **conf.low**: lower bound of the confidence interval for the relative frequency, given `conf.level`.
1400#' - **conf.high**: upper bound of the confidence interval for the relative frequency, given `conf.level`.
1401
Marc Kupietzd8851222025-05-01 10:57:19 +02001402setMethod(
1403 "frequencyQuery", "KorAPConnection",
Marc Kupietza3a8cd92026-09-08 07:59:04 +02001404 function(kco, query, vc = "", conf.level = 0.95, as.alternatives = FALSE,
1405 cacheAs = NULL, ...) {
1406 cacheRecord <- NULL
1407 if (!is.null(cacheAs)) {
1408 cacheAs <- cacheAsFileName(cacheAs)
1409 cacheRecord <- cacheAsRecord(environment(), list(...), kco)
1410 cached <- readCacheAs(cacheAs, kco, cacheRecord, "frequency query")
1411 if (!is.null(cached)) {
1412 return(cached)
1413 }
1414 }
1415
1416 result <- (if (as.alternatives) {
Marc Kupietzd8851222025-05-01 10:57:19 +02001417 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |>
Marc Kupietzea34b812025-06-25 15:49:00 +02001418 group_by(vc) |>
Marc Kupietz71d6e052019-11-22 18:42:10 +01001419 mutate(total = sum(totalResults))
Marc Kupietzd8851222025-05-01 10:57:19 +02001420 } else {
1421 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |>
1422 mutate(total = corpusStats(kco, vc = vc, as.df = TRUE)$tokens)
Marc Kupietzea34b812025-06-25 15:49:00 +02001423 }) |>
Marc Kupietz0c29cea2019-10-09 08:44:36 +02001424 ci(conf.level = conf.level)
Marc Kupietza3a8cd92026-09-08 07:59:04 +02001425
1426 if (!is.null(cacheAs)) {
1427 writeCacheAs(cacheAs, kco, cacheRecord, "frequency query", result)
1428 }
1429 result
Marc Kupietzd8851222025-05-01 10:57:19 +02001430 }
1431)
Marc Kupietz3f575282019-10-04 14:46:04 +02001432
Marc Kupietz38a9d682024-12-06 16:17:09 +01001433#' buildWebUIRequestUrlFromString
1434#'
1435#' @rdname KorAPQuery-class
1436#' @importFrom urltools url_encode
1437#' @export
1438buildWebUIRequestUrlFromString <- function(KorAPUrl,
Marc Kupietzd8851222025-05-01 10:57:19 +02001439 query,
1440 vc = "",
1441 ql = "poliqarp") {
Marc Kupietz38a9d682024-12-06 16:17:09 +01001442 if ("KorAPConnection" %in% class(KorAPUrl)) {
1443 KorAPUrl <- KorAPUrl@KorAPUrl
1444 }
1445
1446 request <-
1447 paste0(
Marc Kupietzd8851222025-05-01 10:57:19 +02001448 "?q=",
Marc Kupietz38a9d682024-12-06 16:17:09 +01001449 urltools::url_encode(enc2utf8(as.character(query))),
Marc Kupietzd8851222025-05-01 10:57:19 +02001450 ifelse(vc != "",
1451 paste0("&cq=", urltools::url_encode(enc2utf8(vc))),
1452 ""
1453 ),
1454 "&ql=",
Marc Kupietz38a9d682024-12-06 16:17:09 +01001455 ql
1456 )
1457 paste0(KorAPUrl, request)
1458}
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001459
1460#' buildWebUIRequestUrl
1461#'
1462#' @rdname KorAPQuery-class
Marc Kupietzf9129592025-01-26 19:17:54 +01001463#' @importFrom httr2 url_parse
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001464#' @export
1465buildWebUIRequestUrl <- function(kco,
Marc Kupietzd8851222025-05-01 10:57:19 +02001466 query = if (missing(KorAPUrl)) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001467 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
Marc Kupietzd8851222025-05-01 10:57:19 +02001468 } else {
1469 httr2::url_parse(KorAPUrl)$query$q
1470 },
Marc Kupietzf9129592025-01-26 19:17:54 +01001471 vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq,
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001472 KorAPUrl,
Marc Kupietzf9129592025-01-26 19:17:54 +01001473 ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql) {
Marc Kupietz38a9d682024-12-06 16:17:09 +01001474 buildWebUIRequestUrlFromString(kco@KorAPUrl, query, vc, ql)
Marc Kupietzdbd431a2021-08-29 12:17:45 +02001475}
1476
Marc Kupietzd8851222025-05-01 10:57:19 +02001477#' format()
Marc Kupietze95108e2019-09-18 13:23:58 +02001478#' @rdname KorAPQuery-class
1479#' @param x KorAPQuery object
1480#' @param ... further arguments passed to or from other methods
Marc Kupietzb73ca0f2025-01-28 20:45:01 +01001481#' @importFrom urltools param_get url_decode
Marc Kupietze95108e2019-09-18 13:23:58 +02001482#' @export
1483format.KorAPQuery <- function(x, ...) {
1484 cat("<KorAPQuery>\n")
1485 q <- x
Marc Kupietzd8851222025-05-01 10:57:19 +02001486 param <- urltools::param_get(q@request) |> lapply(urltools::url_decode)
Marc Kupietzb73ca0f2025-01-28 20:45:01 +01001487 cat(" Query: ", param$q, "\n")
1488 if (!is.null(param$cq) && param$cq != "") {
1489 cat(" Virtual corpus: ", param$cq, "\n")
1490 }
1491 if (!is.null(q@collectedMatches)) {
1492 cat("==============================================================================================================", "\n")
1493 print(summary(q@collectedMatches))
1494 cat("==============================================================================================================", "\n")
1495 }
1496 cat(" Total results: ", q@totalResults, "\n")
1497 cat(" Fetched results: ", q@nextStartIndex, "\n")
Marc Kupietza29f3d42025-07-18 10:14:43 +02001498 if (!is.null(q@collectedMatches) && "pos" %in% colnames(q@collectedMatches)) {
1499 successful_annotations <- sum(!is.na(q@collectedMatches$annotation_snippet))
1500 parsed_annotations <- sum(!is.na(q@collectedMatches$pos))
1501 cat(" Annotations: ", successful_annotations, " of ", nrow(q@collectedMatches), " matches")
1502 if (parsed_annotations > 0) {
1503 cat(" (", parsed_annotations, " with parsed linguistic data)")
1504 }
1505 cat("\n")
Marc Kupietze52b2952025-07-17 16:53:02 +02001506 }
Marc Kupietz62da2b52019-09-12 17:43:34 +02001507}
1508
Marc Kupietze95108e2019-09-18 13:23:58 +02001509#' show()
Marc Kupietz62da2b52019-09-12 17:43:34 +02001510#'
Marc Kupietze95108e2019-09-18 13:23:58 +02001511#' @rdname KorAPQuery-class
1512#' @param object KorAPQuery object
Marc Kupietz62da2b52019-09-12 17:43:34 +02001513#' @export
Marc Kupietze95108e2019-09-18 13:23:58 +02001514setMethod("show", "KorAPQuery", function(object) {
1515 format(object)
Marc Kupietzc643a122025-07-18 18:18:36 +02001516 invisible(object)
Marc Kupietze95108e2019-09-18 13:23:58 +02001517})