blob: dc9294bd85d8e4557cf3bce145faead34ea93a19 [file] [log] [blame]
Marc Kupietze95108e2019-09-18 13:23:58 +02001#' Class KorAPQuery
2#'
Marc Kupietza6e4ee62021-03-05 09:00:15 +01003#' This class provides methods to perform different kinds of queries on the KorAP API server.
Marc Kupietz67edcb52021-09-20 21:54:24 +02004#' `KorAPQuery` objects, which are typically created by the [corpusQuery()] method,
Marc Kupietza6e4ee62021-03-05 09:00:15 +01005#' represent the current state of a query to a KorAP server.
Marc Kupietze95108e2019-09-18 13:23:58 +02006#'
7#' @include KorAPConnection.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",
24 "hasMoreMatches"
25))
Marc Kupietz5bbc9db2019-08-30 16:30:45 +020026
Marc Kupietze95108e2019-09-18 13:23:58 +020027#' Method initialize
28#'
29#' @rdname KorAPQuery-class
30#' @param .Object …
Marc Kupietzb8972182019-09-20 21:33:46 +020031#' @param korapConnection KorAPConnection object
Marc Kupietze95108e2019-09-18 13:23:58 +020032#' @param request query part of the request URL
33#' @param vc definition of a virtual corpus
34#' @param totalResults number of hits the query has yielded
35#' @param nextStartIndex at what index to start the next fetch of query results
36#' @param fields what data / metadata fields should be collected
37#' @param requestUrl complete URL of the API request
38#' @param webUIRequestUrl URL of a web frontend request corresponding to the API request
39#' @param apiResponse data-frame representation of the JSON response of the API request
Marc Kupietz7776dec2019-09-27 16:59:02 +020040#' @param hasMoreMatches logical that signals if more query results can be fetched
Marc Kupietze95108e2019-09-18 13:23:58 +020041#' @param collectedMatches matches already fetched from the KorAP-API-server
Marc Kupietz97a1bca2019-10-04 22:52:09 +020042#'
43#' @importFrom tibble tibble
Marc Kupietze95108e2019-09-18 13:23:58 +020044#' @export
Marc Kupietzd8851222025-05-01 10:57:19 +020045setMethod(
46 "initialize", "KorAPQuery",
47 function(.Object, korapConnection = NULL, request = NULL, vc = "", totalResults = 0, nextStartIndex = 0, fields = c(
48 "corpusSigle", "textSigle", "pubDate", "pubPlace",
49 "availability", "textClass", "snippet", "tokens"
50 ),
51 requestUrl = "", webUIRequestUrl = "", apiResponse = NULL, hasMoreMatches = FALSE, collectedMatches = NULL) {
52 .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"))
72setGeneric("frequencyQuery", function(kco, ...) standardGeneric("frequencyQuery"))
Marc Kupietze95108e2019-09-18 13:23:58 +020073
74maxResultsPerPage <- 50
Marc Kupietz62da2b52019-09-12 17:43:34 +020075
Marc Kupietz4de53ec2019-10-04 09:12:00 +020076## quiets concerns of R CMD check re: the .'s that appear in pipelines
Marc Kupietzef1ef4a2025-02-19 12:12:40 +010077utils::globalVariables(c("."))
Marc Kupietz632cbd42019-09-06 16:04:51 +020078
Marc Kupietzdbd431a2021-08-29 12:17:45 +020079#' Corpus query
80#'
Marc Kupietz67edcb52021-09-20 21:54:24 +020081#' **`corpusQuery`** performs a corpus query via a connection to a KorAP-API-server
Marc Kupietze95108e2019-09-18 13:23:58 +020082#'
Marc Kupietzdbd431a2021-08-29 12:17:45 +020083#' @rdname KorAPQuery-class
84#' @aliases corpusQuery
85#'
86#' @importFrom urltools url_encode
87#' @importFrom purrr pmap
88#' @importFrom dplyr bind_rows
89#'
Marc Kupietz617266d2025-02-27 10:43:07 +010090#' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()`
Marc Kupietz67edcb52021-09-20 21:54:24 +020091#' @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 +020092#' @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 +020093#' @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 +020094#' @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.
95#' If you want your corpus queries to return not only metadata, but also KWICS, you need to authorize
96#' your RKorAPClient application as explained in the
97#' [authorization section](https://github.com/KorAP/RKorAPClient#authorization)
98#' of the RKorAPClient Readme on GitHub and set the `metadataOnly` parameter to
99#' `FALSE`.
Marc Kupietz67edcb52021-09-20 21:54:24 +0200100#' @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.
Akron5e135462019-09-27 16:31:38 +0200101#' @param fields (meta)data fields that will be fetched for every match.
Marc Kupietz43a6ade2020-02-18 17:01:44 +0100102#' @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 +0200103#' @param verbose print some info
Marc Kupietz4de53ec2019-10-04 09:12:00 +0200104#' @param as.df return result as data frame instead of as S4 object?
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200105#' @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 +0200106#' @param context string that specifies the size of the left and the right context returned in `snippet`
107#' (provided that `metadataOnly` is set to `false` and that the necessary access right are met).
108#' 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).
109#' If the parameter is not set, the default context size secification of the KorAP server instance will be used.
110#' Note that you cannot overrule the maximum context size set in the KorAP server instance,
111#' as this is typically legally motivated.
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200112#' @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 +0200113#' A corresponding URL to be used within a web browser is contained in `@webUIRequestUrl`
114#' 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 +0200115#'
116#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200117#' \dontrun{
118#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200119#' # Fetch metadata of every query hit for "Ameisenplage" and show a summary
Marc Kupietzd8851222025-05-01 10:57:19 +0200120#' KorAPConnection() %>%
121#' corpusQuery("Ameisenplage") %>%
122#' fetchAll()
Marc Kupietz657d8e72020-02-25 18:31:50 +0100123#' }
Marc Kupietz3c531f62019-09-13 12:17:24 +0200124#'
Marc Kupietz6ae76052021-09-21 10:34:00 +0200125#' \dontrun{
126#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200127#' # Use the copy of a KorAP-web-frontend URL for an API query of "Ameise" in a virtual corpus
128#' # and show the number of query hits (but don't fetch them).
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200129#'
Marc Kupietz617266d2025-02-27 10:43:07 +0100130#' KorAPConnection(verbose = TRUE) %>%
Marc Kupietzd8851222025-05-01 10:57:19 +0200131#' corpusQuery(
132#' KorAPUrl =
133#' "https://korap.ids-mannheim.de/?q=Ameise&cq=pubDate+since+2017&ql=poliqarp"
134#' )
Marc Kupietz6ae76052021-09-21 10:34:00 +0200135#' }
136#'
137#' \dontrun{
Marc Kupietz3c531f62019-09-13 12:17:24 +0200138#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200139#' # Plot the time/frequency curve of "Ameisenplage"
Marc Kupietzd8851222025-05-01 10:57:19 +0200140#' KorAPConnection(verbose = TRUE) %>%
141#' {
142#' . ->> kco
143#' } %>%
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200144#' corpusQuery("Ameisenplage") %>%
145#' fetchAll() %>%
146#' slot("collectedMatches") %>%
147#' mutate(year = lubridate::year(pubDate)) %>%
Marc Kupietz19e2ebd2019-10-07 11:45:30 +0200148#' dplyr::select(year) %>%
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200149#' group_by(year) %>%
Marc Kupietzcb3c59e2020-06-02 10:10:43 +0200150#' summarise(Count = dplyr::n()) %>%
Marc Kupietzd8851222025-05-01 10:57:19 +0200151#' mutate(Freq = mapply(function(f, y) {
152#' f / corpusStats(kco, paste("pubDate in", y))@tokens
153#' }, Count, year)) %>%
Marc Kupietz19e2ebd2019-10-07 11:45:30 +0200154#' dplyr::select(-Count) %>%
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200155#' complete(year = min(year):max(year), fill = list(Freq = 0)) %>%
156#' plot(type = "l")
Marc Kupietz05b22772020-02-18 21:58:42 +0100157#' }
Marc Kupietz67edcb52021-09-20 21:54:24 +0200158#' @seealso [KorAPConnection()], [fetchNext()], [fetchRest()], [fetchAll()], [corpusStats()]
Marc Kupietz632cbd42019-09-06 16:04:51 +0200159#'
160#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200161#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz632cbd42019-09-06 16:04:51 +0200162#'
163#' @export
Marc Kupietzd8851222025-05-01 10:57:19 +0200164setMethod(
165 "corpusQuery", "KorAPConnection",
166 function(kco,
167 query = if (missing(KorAPUrl)) {
168 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
169 } else {
170 httr2::url_parse(KorAPUrl)$query$q
171 },
172 vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq,
173 KorAPUrl,
174 metadataOnly = TRUE,
175 ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql,
176 fields = c(
177 "corpusSigle",
178 "textSigle",
179 "pubDate",
180 "pubPlace",
181 "availability",
182 "textClass",
183 "snippet",
184 "tokens"
185 ),
186 accessRewriteFatal = TRUE,
187 verbose = kco@verbose,
188 expand = length(vc) != length(query),
189 as.df = FALSE,
190 context = NULL) {
191 if (length(query) > 1 || length(vc) > 1) {
192 grid <- if (expand) expand_grid(query = query, vc = vc) else tibble(query = query, vc = vc)
193 purrr::pmap(grid, function(query, vc, ...) {
194 corpusQuery(kco, query = query, vc = vc, ql = ql, verbose = verbose, as.df = TRUE)
195 }) %>%
196 bind_rows()
197 } else {
Marc Kupietz2078bde2023-08-27 16:46:15 +0200198 contentFields <- c("snippet", "tokens")
Marc Kupietza96537f2019-11-09 23:07:44 +0100199 if (metadataOnly) {
200 fields <- fields[!fields %in% contentFields]
201 }
Marc Kupietz80dc6432025-02-07 16:57:40 +0100202 if (!"textSigle" %in% fields) {
203 fields <- c(fields, "textSigle")
204 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100205 request <-
Marc Kupietzd8851222025-05-01 10:57:19 +0200206 paste0(
207 "?q=",
208 url_encode(enc2utf8(query)),
209 ifelse(!metadataOnly && !is.null(context) && context != "", paste0("&context=", url_encode(enc2utf8(context))), ""),
210 ifelse(vc != "", paste0("&cq=", url_encode(enc2utf8(vc))), ""),
211 ifelse(!metadataOnly, "&show-tokens=true", ""),
212 "&ql=", ql
213 )
Marc Kupietza96537f2019-11-09 23:07:44 +0100214 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
215 requestUrl <- paste0(
216 kco@apiUrl,
Marc Kupietzd8851222025-05-01 10:57:19 +0200217 "search",
Marc Kupietza96537f2019-11-09 23:07:44 +0100218 request,
Marc Kupietzd8851222025-05-01 10:57:19 +0200219 "&fields=",
Marc Kupietza96537f2019-11-09 23:07:44 +0100220 paste(fields, collapse = ","),
Marc Kupietzd8851222025-05-01 10:57:19 +0200221 if (metadataOnly) "&access-rewrite-disabled=true" else ""
Marc Kupietza96537f2019-11-09 23:07:44 +0100222 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200223 log_info(verbose, "\rSearching \"", query, "\" in \"", vc, "\"",
224 sep =
225 ""
226 )
227 res <- apiCall(kco, paste0(requestUrl, "&count=0"))
Marc Kupietza4675722022-02-23 23:55:15 +0100228 if (is.null(res)) {
Marc Kupietza4675722022-02-23 23:55:15 +0100229 message("API call failed.")
230 totalResults <- 0
231 } else {
Marc Kupietzd8851222025-05-01 10:57:19 +0200232 totalResults <- as.integer(res$meta$totalResults)
Marc Kupietza47d1502023-04-18 15:26:47 +0200233 log_info(verbose, ": ", totalResults, " hits")
Marc Kupietzd8851222025-05-01 10:57:19 +0200234 if (!is.null(res$meta$cached)) {
Marc Kupietza47d1502023-04-18 15:26:47 +0200235 log_info(verbose, " [cached]\n")
Marc Kupietzd8851222025-05-01 10:57:19 +0200236 } else if (!is.null(res$meta$benchmark)) {
Marc Kupietz7638ca42025-05-25 13:18:16 +0200237 # Round the benchmark time to 2 decimal places for better readability
238 # If it's a string ending with 's', extract the number, round it, and re-add 's'
239 if (is.character(res$meta$benchmark) && grepl("s$", res$meta$benchmark)) {
240 time_value <- as.numeric(sub("s$", "", res$meta$benchmark))
241 formatted_time <- paste0(round(time_value, 2), "s")
242 log_info(verbose, ", took ", formatted_time, "\n", sep = "")
243 } else {
244 # Fallback if the format is different than expected
245 log_info(verbose, ", took ", res$meta$benchmark, "\n", sep = "")
246 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200247 } else {
248 log_info(verbose, "\n")
249 }
Marc Kupietza4675722022-02-23 23:55:15 +0100250 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200251 if (as.df) {
Marc Kupietza96537f2019-11-09 23:07:44 +0100252 data.frame(
253 query = query,
Marc Kupietza4675722022-02-23 23:55:15 +0100254 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100255 vc = vc,
256 webUIRequestUrl = webUIRequestUrl,
257 stringsAsFactors = FALSE
258 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200259 } else {
Marc Kupietza96537f2019-11-09 23:07:44 +0100260 KorAPQuery(
261 korapConnection = kco,
262 nextStartIndex = 0,
263 fields = fields,
264 requestUrl = requestUrl,
265 request = request,
Marc Kupietza4675722022-02-23 23:55:15 +0100266 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100267 vc = vc,
268 apiResponse = res,
269 webUIRequestUrl = webUIRequestUrl,
Marc Kupietza4675722022-02-23 23:55:15 +0100270 hasMoreMatches = (totalResults > 0),
Marc Kupietza96537f2019-11-09 23:07:44 +0100271 )
Marc Kupietzd8851222025-05-01 10:57:19 +0200272 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100273 }
Marc Kupietzd8851222025-05-01 10:57:19 +0200274 }
275)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200276
Marc Kupietz05a60792024-12-07 16:23:31 +0100277#' @importFrom purrr map
278repair_data_strcuture <- function(x) {
Marc Kupietzd8851222025-05-01 10:57:19 +0200279 if (is.list(x)) {
280 as.character(purrr::map(x, ~ if (length(.x) > 1) {
Marc Kupietz05a60792024-12-07 16:23:31 +0100281 paste(.x, collapse = " ")
282 } else {
283 .x
284 }))
Marc Kupietzd8851222025-05-01 10:57:19 +0200285 } else {
Marc Kupietz05a60792024-12-07 16:23:31 +0100286 ifelse(is.na(x), "", x)
Marc Kupietzd8851222025-05-01 10:57:19 +0200287 }
Marc Kupietz05a60792024-12-07 16:23:31 +0100288}
289
Marc Kupietz62da2b52019-09-12 17:43:34 +0200290#' Fetch the next bunch of results of a KorAP query.
Marc Kupietze95108e2019-09-18 13:23:58 +0200291#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200292#' **`fetchNext`** fetches the next bunch of results of a KorAP query.
Marc Kupietz3f575282019-10-04 14:46:04 +0200293#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200294#' @param kqo object obtained from [corpusQuery()]
Marc Kupietz62da2b52019-09-12 17:43:34 +0200295#' @param offset start offset for query results to fetch
296#' @param maxFetch maximum number of query results to fetch
Marc Kupietz25aebc32019-09-16 18:40:50 +0200297#' @param verbose print progress information if true
Marc Kupietz67edcb52021-09-20 21:54:24 +0200298#' @param randomizePageOrder fetch result pages in pseudo random order if true. Use [set.seed()] to set seed for reproducible results.
299#' @return The `kqo` input object with updated slots `collectedMatches`, `apiResponse`, `nextStartIndex`, `hasMoreMatches`
Marc Kupietz62da2b52019-09-12 17:43:34 +0200300#'
Marc Kupietz05b22772020-02-18 21:58:42 +0100301#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200302#' \dontrun{
303#'
Marc Kupietzd8851222025-05-01 10:57:19 +0200304#' q <- KorAPConnection() %>%
305#' corpusQuery("Ameisenplage") %>%
306#' fetchNext()
Marc Kupietz05b22772020-02-18 21:58:42 +0100307#' q@collectedMatches
Marc Kupietz657d8e72020-02-25 18:31:50 +0100308#' }
Marc Kupietz05b22772020-02-18 21:58:42 +0100309#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200310#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200311#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz62da2b52019-09-12 17:43:34 +0200312#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200313#' @aliases fetchNext
314#' @rdname KorAPQuery-class
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200315#' @importFrom dplyr rowwise mutate bind_rows select summarise n select
Marc Kupietzf4881122024-12-17 14:55:39 +0100316#' @importFrom tibble enframe add_column
317#' @importFrom stringr word
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200318#' @importFrom tidyr unnest unchop pivot_wider
319#' @importFrom purrr map
Marc Kupietz632cbd42019-09-06 16:04:51 +0200320#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200321setMethod("fetchNext", "KorAPQuery", function(kqo,
322 offset = kqo@nextStartIndex,
323 maxFetch = maxResultsPerPage,
324 verbose = kqo@korapConnection@verbose,
325 randomizePageOrder = FALSE) {
Marc Kupietza7a8f1b2024-12-18 15:56:19 +0100326 # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
Marc Kupietzd8851222025-05-01 10:57:19 +0200327 results <- key <- name <- tmp_positions <- 0
Marc Kupietza7a8f1b2024-12-18 15:56:19 +0100328
Marc Kupietze95108e2019-09-18 13:23:58 +0200329 if (kqo@totalResults == 0 || offset >= kqo@totalResults) {
330 return(kqo)
Marc Kupietz62da2b52019-09-12 17:43:34 +0200331 }
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200332 use_korap_api <- Sys.getenv("USE_KORAP_API", unset = NA)
Marc Kupietz623d7122025-05-25 12:46:12 +0200333 # Calculate the initial page number (not used directly - keeping for reference)
Marc Kupietze95108e2019-09-18 13:23:58 +0200334 collectedMatches <- kqo@collectedMatches
Marc Kupietz62da2b52019-09-12 17:43:34 +0200335
Marc Kupietz623d7122025-05-25 12:46:12 +0200336 # For randomized page order, generate a list of randomized page indices
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200337 if (randomizePageOrder) {
Marc Kupietz623d7122025-05-25 12:46:12 +0200338 # Calculate how many pages we need to fetch based on maxFetch
339 total_pages_to_fetch <- if (!is.na(maxFetch)) {
340 # Either limited by maxFetch or total results, whichever is smaller
341 min(ceiling(maxFetch / maxResultsPerPage), ceiling(kqo@totalResults / maxResultsPerPage))
342 } else {
343 # All pages
344 ceiling(kqo@totalResults / maxResultsPerPage)
345 }
346
347 # Generate randomized page indices (0-based for API)
348 pages <- sample.int(ceiling(kqo@totalResults / maxResultsPerPage), total_pages_to_fetch) - 1
349 page_index <- 1 # Index to track which page in the randomized list we're on
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200350 }
351
Marc Kupietzd8851222025-05-01 10:57:19 +0200352 if (is.null(collectedMatches)) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200353 collectedMatches <- data.frame()
354 }
Marc Kupietz623d7122025-05-25 12:46:12 +0200355
356 # Initialize the page counter properly based on nextStartIndex and any previously fetched results
357 # We add 1 to make it 1-based for display purposes since users expect page numbers to start from 1
358 # For first call, this will be 1, for subsequent calls, it will reflect our actual position
359 current_page_number <- ceiling(offset / maxResultsPerPage) + 1
360
361 # For sequential fetches, keep track of which global page we're on
362 # This is important for correctly showing page numbers in subsequent fetchNext calls
363 page_count_start <- current_page_number
364
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200365 repeat {
Marc Kupietz623d7122025-05-25 12:46:12 +0200366 # Determine which page to fetch next
367 if (randomizePageOrder) {
368 # In randomized mode, get the page from our randomized list using the page_index
369 # Make sure we don't exceed the array bounds
370 if (page_index > length(pages)) {
371 break # No more pages to fetch in randomized mode
372 }
373 current_offset_page <- pages[page_index]
374 # For display purposes in randomized mode, show which page out of the total we're fetching
375 display_page_number <- page_index
376 } else {
377 # In sequential mode, use the current_page_number to calculate the offset
378 current_offset_page <- (current_page_number - 1)
379 display_page_number <- current_page_number
380 }
381
382 # Calculate the actual offset in tokens
383 currentOffset <- current_offset_page * maxResultsPerPage
384
385 # Build the query with the appropriate count and offset
Marc Kupietzd8851222025-05-01 10:57:19 +0200386 query <- paste0(kqo@requestUrl, "&count=", min(if (!is.na(maxFetch)) maxFetch - results else maxResultsPerPage, maxResultsPerPage), "&offset=", currentOffset, "&cutoff=true")
Marc Kupietz68170952021-06-30 09:37:21 +0200387 res <- apiCall(kqo@korapConnection, query)
388 if (length(res$matches) == 0) {
389 break
390 }
391
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200392 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 +0100393 log_info(verbose, "Using fields API: ")
Marc Kupietz05a60792024-12-07 16:23:31 +0100394 currentMatches <- res$matches$fields %>%
395 purrr::map(~ mutate(.x, value = repair_data_strcuture(value))) %>%
396 tibble::enframe() %>%
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200397 tidyr::unnest(cols = value) %>%
398 tidyr::pivot_wider(names_from = key, id_cols = name, names_repair = "unique") %>%
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200399 dplyr::select(-name)
Marc Kupietzd8851222025-05-01 10:57:19 +0200400 if ("snippet" %in% colnames(res$matches)) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200401 currentMatches$snippet <- res$matches$snippet
402 }
Marc Kupietz3cd2c6c2025-01-08 20:35:39 +0100403 if ("tokens" %in% colnames(res$matches)) {
404 currentMatches$tokens <- res$matches$tokens
405 }
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200406 } else {
407 currentMatches <- res$matches
408 }
409
Marc Kupietze95108e2019-09-18 13:23:58 +0200410 for (field in kqo@fields) {
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200411 if (!field %in% colnames(currentMatches)) {
412 currentMatches[, field] <- NA
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200413 }
414 }
Marc Kupietzf4881122024-12-17 14:55:39 +0100415 currentMatches <- currentMatches %>%
416 select(kqo@fields) %>%
417 mutate(
Marc Kupietz0447da02025-01-08 20:51:09 +0100418 tmp_positions = gsub(".*-p(\\d+)-(\\d+).*", "\\1 \\2", res$matches$matchID),
Marc Kupietzf4881122024-12-17 14:55:39 +0100419 matchStart = as.integer(stringr::word(tmp_positions, 1)),
420 matchEnd = as.integer(stringr::word(tmp_positions, 2)) - 1
421 ) %>%
422 select(-tmp_positions)
423
Marc Kupietz62da2b52019-09-12 17:43:34 +0200424 if (!is.list(collectedMatches)) {
425 collectedMatches <- currentMatches
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200426 } else {
Marc Kupietz2078bde2023-08-27 16:46:15 +0200427 collectedMatches <- bind_rows(collectedMatches, currentMatches)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200428 }
Marc Kupietzae9b6172025-05-02 15:50:01 +0200429
Marc Kupietz623d7122025-05-25 12:46:12 +0200430 # Get the actual items per page from the API response
431 # We now consistently use maxResultsPerPage instead
Marc Kupietzacbaab02025-05-01 10:56:35 +0200432
Marc Kupietz623d7122025-05-25 12:46:12 +0200433 # Calculate total pages consistently using fixed maxResultsPerPage
434 # This ensures consistent page counting across the function
435 total_pages <- ceiling(kqo@totalResults / maxResultsPerPage)
436
437 # Calculate the total pages based on what we've already fetched plus what we'll fetch
438 # This ensures the correct denominator is displayed for subsequent fetchNext calls
439
440 # Calculate the total number of pages for the entire result set
441 # This calculation is kept for reference and for showing in parentheses
Marc Kupietz669114b2025-05-02 22:02:20 +0200442
Marc Kupietzae9b6172025-05-02 15:50:01 +0200443 # Estimate remaining time
444 time_per_page <- NA
445 eta_str <- "N/A"
446 completion_time_str <- "N/A"
Marc Kupietzacbaab02025-05-01 10:56:35 +0200447
Marc Kupietzae9b6172025-05-02 15:50:01 +0200448 if (!is.null(res$meta$benchmark) && is.character(res$meta$benchmark)) {
449 # benchmark looks like "0.123s"
450 time_per_page <- suppressWarnings(as.numeric(sub("s", "", res$meta$benchmark)))
451 if (!is.na(time_per_page)) {
Marc Kupietz623d7122025-05-25 12:46:12 +0200452 # First determine our current global position for ETA calculation
453 current_global_position <- if (randomizePageOrder) {
454 # In randomized mode, this is how many pages we've processed so far in this batch
455 page_index - 1 # -1 because we're calculating remaining
456 } else {
457 page_count_start + (current_page_number - 1) - 1 # -1 because we're calculating remaining
458 }
459
460 # Calculate remaining pages based on maxFetch if specified
461 if (!is.na(maxFetch) && maxFetch < kqo@totalResults) {
462 # We need to fetch up to maxFetch results
463 remaining_items_to_fetch <- maxFetch - nrow(collectedMatches)
464 remaining_pages <- ceiling(remaining_items_to_fetch / maxResultsPerPage)
465 } else {
466 # We need to fetch all results - account for our actual global position
467 # For randomized order, calculate remaining pages based on the randomized list or maxFetch
468 if (randomizePageOrder) {
469 if (exists("pages") && length(pages) > 0) {
470 remaining_pages <- length(pages) - page_index
471 } else if (!is.na(maxFetch)) {
472 # If pages is not available, use maxFetch to estimate remaining pages
473 remaining_pages <- ceiling(maxFetch / maxResultsPerPage) - page_index
474 } else {
475 # Fallback to a reasonable default
476 remaining_pages <- 1
477 }
478 } else {
479 # For sequential order, use the current global position
480 remaining_pages <- total_pages - current_global_position
481 }
482 }
Marc Kupietzae9b6172025-05-02 15:50:01 +0200483
484 estimated_remaining_seconds <- remaining_pages * time_per_page
485 estimated_completion_time <- Sys.time() + estimated_remaining_seconds
486
487 # Format time nicely
488 format_duration <- function(seconds) {
489 if (is.na(seconds) || seconds < 0) {
Marc Kupietz623d7122025-05-25 12:46:12 +0200490 # Instead of "N/A", return "00s" as a fallback
491 return("00s")
Marc Kupietzae9b6172025-05-02 15:50:01 +0200492 }
493 days <- floor(seconds / (24 * 3600))
494 seconds <- seconds %% (24 * 3600)
495 hours <- floor(seconds / 3600)
496 seconds <- seconds %% 3600
497 minutes <- floor(seconds / 60)
498 seconds <- floor(seconds %% 60)
499 paste0(
500 if (days > 0) paste0(days, "d ") else "",
501 if (hours > 0 || days > 0) paste0(sprintf("%02d", hours), "h ") else "",
502 if (minutes > 0 || hours > 0 || days > 0) paste0(sprintf("%02d", minutes), "m ") else "",
503 paste0(sprintf("%02d", seconds), "s")
504 )
505 }
506
507 eta_str <- format_duration(estimated_remaining_seconds)
508 completion_time_str <- format(estimated_completion_time, "%Y-%m-%d %H:%M:%S")
Marc Kupietzacbaab02025-05-01 10:56:35 +0200509 }
Marc Kupietzacbaab02025-05-01 10:56:35 +0200510 }
511
Marc Kupietz623d7122025-05-25 12:46:12 +0200512 # Create the page display string with proper formatting
Marc Kupietzacbaab02025-05-01 10:56:35 +0200513
Marc Kupietz623d7122025-05-25 12:46:12 +0200514 # For global page tracking, calculate the absolute page number
515 actual_display_number <- if (randomizePageOrder) {
516 current_offset_page + 1 # In randomized mode, this is the actual page (0-based + 1)
517 } else {
518 # In sequential mode, the absolute page number is the actual offset page + 1 (to make it 1-based)
519 current_offset_page + 1
520 }
521
522 # For subsequent calls to fetchNext, we need to calculate the correct page numbers
523 # based on the current batch being fetched
524
525 # For each call to fetchNext, we want to show 1/2, 2/2 (not 3/4, 4/4)
526 # Simply count from 1 within the current batch
527
528 # The relative page number is simply the current position in this batch
529 if (randomizePageOrder) {
530 relative_page_number <- page_index # In randomized mode, we start from 1 in each batch
531 } else {
532 relative_page_number <- display_page_number - (page_count_start - 1)
533 }
534
535 # How many pages will we fetch in this batch?
536 # If maxFetch is specified, calculate based on it
537 pages_in_this_batch <- if (!is.na(maxFetch)) {
538 ceiling(maxFetch / maxResultsPerPage)
539 } else {
540 # Otherwise fetch all remaining pages
541 total_pages - page_count_start + 1
542 }
543
544 # The total pages to be shown in this batch
545 batch_total_pages <- pages_in_this_batch
546
547 page_display <- paste0(
548 "Retrieved page ",
549 sprintf(paste0("%", nchar(batch_total_pages), "d"), relative_page_number),
550 "/",
551 sprintf("%d", batch_total_pages)
552 )
553
554 # If randomized, also show which actual page we fetched
555 if (randomizePageOrder) {
556 # Determine the maximum width needed for page numbers (based on total pages)
557 # This ensures consistent alignment
558 max_page_width <- nchar(as.character(total_pages))
559 # Add the actual page number that was fetched (0-based + 1 for display) with proper padding
Marc Kupietz7638ca42025-05-25 13:18:16 +0200560 page_display <- paste0(
561 page_display,
562 sprintf(" (actual page %*d)", max_page_width, current_offset_page + 1)
563 )
Marc Kupietz623d7122025-05-25 12:46:12 +0200564 }
565 # Always show the absolute page number and total pages (for clarity)
566 else {
567 # Show the absolute page number (out of total possible pages)
568 page_display <- paste0(page_display, sprintf(
569 " (page %d of %d total)",
570 actual_display_number, total_pages
571 ))
572 }
573
574 # Add caching or timing information
575 if (!is.null(res$meta$cached)) {
576 page_display <- paste0(page_display, " [cached]")
577 } else {
578 page_display <- paste0(
579 page_display,
580 " in ",
581 if (!is.na(time_per_page)) sprintf("%4.1f", time_per_page) else "?",
582 "s. ETA: ",
583 # Display ETA for both randomized and sequential modes
584 eta_str,
585 # Show completion time for both modes
586 paste0(" (", completion_time_str, ")")
587 )
588 }
589
590 log_info(verbose, paste0(page_display, "\n"))
591
592 # Increment the appropriate counter based on mode
593 if (randomizePageOrder) {
594 page_index <- page_index + 1
595 } else {
596 current_page_number <- current_page_number + 1
597 }
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200598 results <- results + res$meta$itemsPerPage
Marc Kupietze8bd49b2024-06-28 07:24:44 +0200599 if (nrow(collectedMatches) >= kqo@totalResults || (!is.na(maxFetch) && results >= maxFetch)) {
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200600 break
601 }
602 }
Marc Kupietz68170952021-06-30 09:37:21 +0200603 nextStartIndex <- min(res$meta$startIndex + res$meta$itemsPerPage, kqo@totalResults)
Marc Kupietzd8851222025-05-01 10:57:19 +0200604 KorAPQuery(
605 nextStartIndex = nextStartIndex,
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200606 korapConnection = kqo@korapConnection,
Marc Kupietze95108e2019-09-18 13:23:58 +0200607 fields = kqo@fields,
608 requestUrl = kqo@requestUrl,
609 request = kqo@request,
Marc Kupietz68170952021-06-30 09:37:21 +0200610 totalResults = kqo@totalResults,
Marc Kupietze95108e2019-09-18 13:23:58 +0200611 vc = kqo@vc,
612 webUIRequestUrl = kqo@webUIRequestUrl,
Marc Kupietz68170952021-06-30 09:37:21 +0200613 hasMoreMatches = (kqo@totalResults > nextStartIndex),
Marc Kupietze95108e2019-09-18 13:23:58 +0200614 apiResponse = res,
Marc Kupietzd8851222025-05-01 10:57:19 +0200615 collectedMatches = collectedMatches
616 )
Marc Kupietze95108e2019-09-18 13:23:58 +0200617})
Marc Kupietz62da2b52019-09-12 17:43:34 +0200618
619#' Fetch all results of a KorAP query.
Marc Kupietz62da2b52019-09-12 17:43:34 +0200620#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200621#' **`fetchAll`** fetches all results of a KorAP query.
Marc Kupietza6e4ee62021-03-05 09:00:15 +0100622#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200623#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200624#' \dontrun{
625#'
Marc Kupietzd8851222025-05-01 10:57:19 +0200626#' q <- KorAPConnection() %>%
627#' corpusQuery("Ameisenplage") %>%
628#' fetchAll()
Marc Kupietze95108e2019-09-18 13:23:58 +0200629#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100630#' }
Marc Kupietz62da2b52019-09-12 17:43:34 +0200631#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200632#' @aliases fetchAll
633#' @rdname KorAPQuery-class
Marc Kupietz62da2b52019-09-12 17:43:34 +0200634#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200635setMethod("fetchAll", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
636 return(fetchNext(kqo, offset = 0, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200637})
638
639#' Fetches the remaining results of a KorAP query.
640#'
641#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200642#' \dontrun{
643#'
Marc Kupietzd8851222025-05-01 10:57:19 +0200644#' q <- KorAPConnection() %>%
645#' corpusQuery("Ameisenplage") %>%
646#' fetchRest()
Marc Kupietze95108e2019-09-18 13:23:58 +0200647#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100648#' }
Marc Kupietze95108e2019-09-18 13:23:58 +0200649#'
650#' @aliases fetchRest
651#' @rdname KorAPQuery-class
652#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200653setMethod("fetchRest", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
654 return(fetchNext(kqo, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200655})
656
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200657#' Query frequencies of search expressions in virtual corpora
Marc Kupietz3f575282019-10-04 14:46:04 +0200658#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200659#' **`frequencyQuery`** combines [corpusQuery()], [corpusStats()] and
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200660#' [ci()] to compute a tibble with the absolute and relative frequencies and
Marc Kupietz3f575282019-10-04 14:46:04 +0200661#' confidence intervals of one ore multiple search terms across one or multiple
662#' virtual corpora.
663#'
664#' @aliases frequencyQuery
Marc Kupietz3f575282019-10-04 14:46:04 +0200665#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200666#' \dontrun{
667#'
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200668#' KorAPConnection(verbose = TRUE) |>
Marc Kupietz3f575282019-10-04 14:46:04 +0200669#' frequencyQuery(c("Mücke", "Schnake"), paste0("pubDate in ", 2000:2003))
Marc Kupietz05b22772020-02-18 21:58:42 +0100670#' }
Marc Kupietz3f575282019-10-04 14:46:04 +0200671#'
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200672# @inheritParams corpusQuery
Marc Kupietz617266d2025-02-27 10:43:07 +0100673#' @param kco [KorAPConnection()] object (obtained e.g. from `KorAPConnection()`
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200674#' @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`.
675#' @param vc virtual corpus definition(s) (can be a vector)
Marc Kupietz67edcb52021-09-20 21:54:24 +0200676#' @param conf.level confidence level of the returned confidence interval (passed through [ci()] to [prop.test()]).
677#' @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 Kupietzad8d2ed2025-04-05 15:37:38 +0200678#' @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 +0200679#' @export
Marc Kupietzad8d2ed2025-04-05 15:37:38 +0200680#'
681#' @return A tibble, with each row containing the following result columns for query and vc combinations:
682#' - **query**: the query string used for the frequency analysis.
683#' - **totalResults**: absolute frequency of query matches in the vc.
684#' - **vc**: virtual corpus used for the query.
685#' - **webUIRequestUrl**: URL of the corresponding web UI request with respect to query and vc.
686#' - **total**: total number of words in vc.
687#' - **f**: relative frequency of query matches in the vc.
688#' - **conf.low**: lower bound of the confidence interval for the relative frequency, given `conf.level`.
689#' - **conf.high**: upper bound of the confidence interval for the relative frequency, given `conf.level`.
690
Marc Kupietzd8851222025-05-01 10:57:19 +0200691setMethod(
692 "frequencyQuery", "KorAPConnection",
Marc Kupietz71d6e052019-11-22 18:42:10 +0100693 function(kco, query, vc = "", conf.level = 0.95, as.alternatives = FALSE, ...) {
Marc Kupietzd8851222025-05-01 10:57:19 +0200694 (if (as.alternatives) {
695 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |>
Marc Kupietz71d6e052019-11-22 18:42:10 +0100696 group_by(vc) %>%
697 mutate(total = sum(totalResults))
Marc Kupietzd8851222025-05-01 10:57:19 +0200698 } else {
699 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) |>
700 mutate(total = corpusStats(kco, vc = vc, as.df = TRUE)$tokens)
701 }) %>%
Marc Kupietz0c29cea2019-10-09 08:44:36 +0200702 ci(conf.level = conf.level)
Marc Kupietzd8851222025-05-01 10:57:19 +0200703 }
704)
Marc Kupietz3f575282019-10-04 14:46:04 +0200705
Marc Kupietz38a9d682024-12-06 16:17:09 +0100706#' buildWebUIRequestUrlFromString
707#'
708#' @rdname KorAPQuery-class
709#' @importFrom urltools url_encode
710#' @export
711buildWebUIRequestUrlFromString <- function(KorAPUrl,
Marc Kupietzd8851222025-05-01 10:57:19 +0200712 query,
713 vc = "",
714 ql = "poliqarp") {
Marc Kupietz38a9d682024-12-06 16:17:09 +0100715 if ("KorAPConnection" %in% class(KorAPUrl)) {
716 KorAPUrl <- KorAPUrl@KorAPUrl
717 }
718
719 request <-
720 paste0(
Marc Kupietzd8851222025-05-01 10:57:19 +0200721 "?q=",
Marc Kupietz38a9d682024-12-06 16:17:09 +0100722 urltools::url_encode(enc2utf8(as.character(query))),
Marc Kupietzd8851222025-05-01 10:57:19 +0200723 ifelse(vc != "",
724 paste0("&cq=", urltools::url_encode(enc2utf8(vc))),
725 ""
726 ),
727 "&ql=",
Marc Kupietz38a9d682024-12-06 16:17:09 +0100728 ql
729 )
730 paste0(KorAPUrl, request)
731}
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200732
733#' buildWebUIRequestUrl
734#'
735#' @rdname KorAPQuery-class
Marc Kupietzf9129592025-01-26 19:17:54 +0100736#' @importFrom httr2 url_parse
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200737#' @export
738buildWebUIRequestUrl <- function(kco,
Marc Kupietzd8851222025-05-01 10:57:19 +0200739 query = if (missing(KorAPUrl)) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200740 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
Marc Kupietzd8851222025-05-01 10:57:19 +0200741 } else {
742 httr2::url_parse(KorAPUrl)$query$q
743 },
Marc Kupietzf9129592025-01-26 19:17:54 +0100744 vc = if (missing(KorAPUrl)) "" else httr2::url_parse(KorAPUrl)$query$cq,
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200745 KorAPUrl,
Marc Kupietzf9129592025-01-26 19:17:54 +0100746 ql = if (missing(KorAPUrl)) "poliqarp" else httr2::url_parse(KorAPUrl)$query$ql) {
Marc Kupietz38a9d682024-12-06 16:17:09 +0100747 buildWebUIRequestUrlFromString(kco@KorAPUrl, query, vc, ql)
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200748}
749
Marc Kupietzd8851222025-05-01 10:57:19 +0200750#' format()
Marc Kupietze95108e2019-09-18 13:23:58 +0200751#' @rdname KorAPQuery-class
752#' @param x KorAPQuery object
753#' @param ... further arguments passed to or from other methods
Marc Kupietzb73ca0f2025-01-28 20:45:01 +0100754#' @importFrom urltools param_get url_decode
Marc Kupietze95108e2019-09-18 13:23:58 +0200755#' @export
756format.KorAPQuery <- function(x, ...) {
757 cat("<KorAPQuery>\n")
758 q <- x
Marc Kupietzd8851222025-05-01 10:57:19 +0200759 param <- urltools::param_get(q@request) |> lapply(urltools::url_decode)
Marc Kupietzb73ca0f2025-01-28 20:45:01 +0100760 cat(" Query: ", param$q, "\n")
761 if (!is.null(param$cq) && param$cq != "") {
762 cat(" Virtual corpus: ", param$cq, "\n")
763 }
764 if (!is.null(q@collectedMatches)) {
765 cat("==============================================================================================================", "\n")
766 print(summary(q@collectedMatches))
767 cat("==============================================================================================================", "\n")
768 }
769 cat(" Total results: ", q@totalResults, "\n")
770 cat(" Fetched results: ", q@nextStartIndex, "\n")
Marc Kupietz62da2b52019-09-12 17:43:34 +0200771}
772
Marc Kupietze95108e2019-09-18 13:23:58 +0200773#' show()
Marc Kupietz62da2b52019-09-12 17:43:34 +0200774#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200775#' @rdname KorAPQuery-class
776#' @param object KorAPQuery object
Marc Kupietz62da2b52019-09-12 17:43:34 +0200777#' @export
Marc Kupietze95108e2019-09-18 13:23:58 +0200778setMethod("show", "KorAPQuery", function(object) {
779 format(object)
780})