blob: eb2afbd5081c45c6a117dfa6ed9cc30b39f955b5 [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 Kupietze95108e2019-09-18 13:23:58 +02008#' @import httr
9#'
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
45setMethod("initialize", "KorAPQuery",
Marc Kupietzb8972182019-09-20 21:33:46 +020046 function(.Object, korapConnection = NULL, request = NULL, vc="", totalResults=0, nextStartIndex=0, fields=c("corpusSigle", "textSigle", "pubDate", "pubPlace",
Marc Kupietze95108e2019-09-18 13:23:58 +020047 "availability", "textClass", "snippet"),
48 requestUrl="", webUIRequestUrl = "", apiResponse = NULL, hasMoreMatches= FALSE, collectedMatches = NULL) {
49 .Object <- callNextMethod()
Marc Kupietzb8972182019-09-20 21:33:46 +020050 .Object@korapConnection = korapConnection
Marc Kupietze95108e2019-09-18 13:23:58 +020051 .Object@request = request
52 .Object@vc = vc
53 .Object@totalResults = totalResults
54 .Object@nextStartIndex = nextStartIndex
55 .Object@fields = fields
56 .Object@requestUrl = requestUrl
57 .Object@webUIRequestUrl = webUIRequestUrl
58 .Object@apiResponse = apiResponse
59 .Object@hasMoreMatches = hasMoreMatches
60 .Object@collectedMatches = collectedMatches
61 .Object
62 })
Marc Kupietz632cbd42019-09-06 16:04:51 +020063
Marc Kupietze95108e2019-09-18 13:23:58 +020064setGeneric("corpusQuery", function(kco, ...) standardGeneric("corpusQuery") )
65setGeneric("fetchAll", function(kqo, ...) standardGeneric("fetchAll") )
66setGeneric("fetchNext", function(kqo, ...) standardGeneric("fetchNext") )
67setGeneric("fetchRest", function(kqo, ...) standardGeneric("fetchRest") )
Marc Kupietz3f575282019-10-04 14:46:04 +020068setGeneric("frequencyQuery", function(kco, ...) standardGeneric("frequencyQuery") )
Marc Kupietze95108e2019-09-18 13:23:58 +020069
70maxResultsPerPage <- 50
Marc Kupietz62da2b52019-09-12 17:43:34 +020071
Marc Kupietz4de53ec2019-10-04 09:12:00 +020072## quiets concerns of R CMD check re: the .'s that appear in pipelines
73if(getRversion() >= "2.15.1") utils::globalVariables(c("."))
Marc Kupietz632cbd42019-09-06 16:04:51 +020074
Marc Kupietzdbd431a2021-08-29 12:17:45 +020075#' Corpus query
76#'
Marc Kupietz67edcb52021-09-20 21:54:24 +020077#' **`corpusQuery`** performs a corpus query via a connection to a KorAP-API-server
Marc Kupietze95108e2019-09-18 13:23:58 +020078#'
Marc Kupietzdbd431a2021-08-29 12:17:45 +020079#' @rdname KorAPQuery-class
80#' @aliases corpusQuery
81#'
82#' @importFrom urltools url_encode
83#' @importFrom purrr pmap
84#' @importFrom dplyr bind_rows
85#'
Marc Kupietz67edcb52021-09-20 21:54:24 +020086#' @param kco [KorAPConnection()] object (obtained e.g. from `new("KorAPConnection")`
87#' @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 +020088#' @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 +020089#' @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 Kupietz7776dec2019-09-27 16:59:02 +020090#' @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, unless the connection is authorized (currently not possible).
Marc Kupietz67edcb52021-09-20 21:54:24 +020091#' @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 +020092#' @param fields (meta)data fields that will be fetched for every match.
Marc Kupietz43a6ade2020-02-18 17:01:44 +010093#' @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 +020094#' @param verbose print some info
Marc Kupietz4de53ec2019-10-04 09:12:00 +020095#' @param as.df return result as data frame instead of as S4 object?
Marc Kupietz67edcb52021-09-20 21:54:24 +020096#' @param expand logical that decides if `query` and `vc` parameters are expanded to all of their combinations
97#' @return Depending on the `as.df` parameter, a table 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()]).
98#' A corresponding URL to be used within a web browser is contained in `@webUIRequestUrl`
99#' 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 +0200100#'
101#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200102#' \dontrun{
103#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200104#' # Fetch metadata of every query hit for "Ameisenplage" and show a summary
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200105#' new("KorAPConnection") %>% corpusQuery("Ameisenplage") %>% fetchAll()
Marc Kupietz657d8e72020-02-25 18:31:50 +0100106#' }
Marc Kupietz3c531f62019-09-13 12:17:24 +0200107#'
Marc Kupietz6ae76052021-09-21 10:34:00 +0200108#' \dontrun{
109#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200110#' # Use the copy of a KorAP-web-frontend URL for an API query of "Ameise" in a virtual corpus
111#' # and show the number of query hits (but don't fetch them).
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200112#'
113#' new("KorAPConnection", verbose = TRUE) %>%
114#' corpusQuery(KorAPUrl =
115#' "https://korap.ids-mannheim.de/?q=Ameise&cq=pubDate+since+2017&ql=poliqarp")
Marc Kupietz6ae76052021-09-21 10:34:00 +0200116#' }
117#'
118#' \dontrun{
Marc Kupietz3c531f62019-09-13 12:17:24 +0200119#'
Marc Kupietz603491f2019-09-18 14:01:02 +0200120#' # Plot the time/frequency curve of "Ameisenplage"
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200121#' new("KorAPConnection", verbose=TRUE) %>%
122#' { . ->> kco } %>%
123#' corpusQuery("Ameisenplage") %>%
124#' fetchAll() %>%
125#' slot("collectedMatches") %>%
126#' mutate(year = lubridate::year(pubDate)) %>%
Marc Kupietz19e2ebd2019-10-07 11:45:30 +0200127#' dplyr::select(year) %>%
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200128#' group_by(year) %>%
Marc Kupietzcb3c59e2020-06-02 10:10:43 +0200129#' summarise(Count = dplyr::n()) %>%
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200130#' mutate(Freq = mapply(function(f, y)
131#' f / corpusStats(kco, paste("pubDate in", y))@tokens, Count, year)) %>%
Marc Kupietz19e2ebd2019-10-07 11:45:30 +0200132#' dplyr::select(-Count) %>%
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200133#' complete(year = min(year):max(year), fill = list(Freq = 0)) %>%
134#' plot(type = "l")
Marc Kupietz05b22772020-02-18 21:58:42 +0100135#' }
Marc Kupietz67edcb52021-09-20 21:54:24 +0200136#' @seealso [KorAPConnection()], [fetchNext()], [fetchRest()], [fetchAll()], [corpusStats()]
Marc Kupietz632cbd42019-09-06 16:04:51 +0200137#'
138#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200139#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz632cbd42019-09-06 16:04:51 +0200140#'
141#' @export
Marc Kupietze95108e2019-09-18 13:23:58 +0200142setMethod("corpusQuery", "KorAPConnection",
Marc Kupietza96537f2019-11-09 23:07:44 +0100143 function(kco,
144 query = if (missing(KorAPUrl))
145 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
146 else
147 httr::parse_url(KorAPUrl)$query$q,
148 vc = if (missing(KorAPUrl)) "" else httr::parse_url(KorAPUrl)$query$cq,
149 KorAPUrl,
150 metadataOnly = TRUE,
151 ql = if (missing(KorAPUrl)) "poliqarp" else httr::parse_url(KorAPUrl)$query$ql,
152 fields = c(
153 "corpusSigle",
154 "textSigle",
155 "pubDate",
156 "pubPlace",
157 "availability",
158 "textClass",
159 "snippet"
160 ),
161 accessRewriteFatal = TRUE,
162 verbose = kco@verbose,
163 expand = length(vc) != length(query),
164 as.df = FALSE) {
165 if (length(query) > 1 || length(vc) > 1) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200166 grid <- if (expand) expand_grid(query=query, vc=vc) else tibble(query=query, vc=vc)
167 purrr::pmap(grid, function(query, vc, ...)
168 corpusQuery(kco, query=query, vc=vc, ql=ql, verbose=verbose, as.df = TRUE)) %>%
169 bind_rows()
170 } else {
Marc Kupietza96537f2019-11-09 23:07:44 +0100171 contentFields <- c("snippet")
172 if (metadataOnly) {
173 fields <- fields[!fields %in% contentFields]
174 }
175 request <-
176 paste0('?q=',
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200177 url_encode(enc2utf8(query)),
178 ifelse (vc != '', paste0('&cq=', url_encode(enc2utf8(vc))), ''), '&ql=', ql)
Marc Kupietza96537f2019-11-09 23:07:44 +0100179 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
180 requestUrl <- paste0(
181 kco@apiUrl,
182 'search',
183 request,
184 '&fields=',
185 paste(fields, collapse = ","),
186 if (metadataOnly) '&access-rewrite-disabled=true' else ''
187 )
188 log.info(verbose, "Searching \"", query, "\" in \"", vc, "\"", sep =
189 "")
190 res = apiCall(kco, paste0(requestUrl, '&count=0'))
Marc Kupietza4675722022-02-23 23:55:15 +0100191 if (is.null(res)) {
192 log.info(verbose, " [failed]\n")
193 message("API call failed.")
194 totalResults <- 0
195 } else {
196 totalResults <-res$meta$totalResults
197 log.info(verbose, ": ", totalResults, " hits")
198 if(!is.null(res$meta$cached))
199 log.info(verbose, " [cached]\n")
200 else
201 log.info(verbose, ", took ", res$meta$benchmark, "\n", sep = "")
202 }
Marc Kupietza96537f2019-11-09 23:07:44 +0100203 if (as.df)
204 data.frame(
205 query = query,
Marc Kupietza4675722022-02-23 23:55:15 +0100206 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100207 vc = vc,
208 webUIRequestUrl = webUIRequestUrl,
209 stringsAsFactors = FALSE
210 )
211 else
212 KorAPQuery(
213 korapConnection = kco,
214 nextStartIndex = 0,
215 fields = fields,
216 requestUrl = requestUrl,
217 request = request,
Marc Kupietza4675722022-02-23 23:55:15 +0100218 totalResults = totalResults,
Marc Kupietza96537f2019-11-09 23:07:44 +0100219 vc = vc,
220 apiResponse = res,
221 webUIRequestUrl = webUIRequestUrl,
Marc Kupietza4675722022-02-23 23:55:15 +0100222 hasMoreMatches = (totalResults > 0),
Marc Kupietza96537f2019-11-09 23:07:44 +0100223 )
224 }
Marc Kupietz4de53ec2019-10-04 09:12:00 +0200225 })
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200226
Marc Kupietz62da2b52019-09-12 17:43:34 +0200227#' Fetch the next bunch of results of a KorAP query.
Marc Kupietze95108e2019-09-18 13:23:58 +0200228#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200229#' **`fetchNext`** fetches the next bunch of results of a KorAP query.
Marc Kupietz3f575282019-10-04 14:46:04 +0200230#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200231#' @param kqo object obtained from [corpusQuery()]
Marc Kupietz62da2b52019-09-12 17:43:34 +0200232#' @param offset start offset for query results to fetch
233#' @param maxFetch maximum number of query results to fetch
Marc Kupietz25aebc32019-09-16 18:40:50 +0200234#' @param verbose print progress information if true
Marc Kupietz67edcb52021-09-20 21:54:24 +0200235#' @param randomizePageOrder fetch result pages in pseudo random order if true. Use [set.seed()] to set seed for reproducible results.
236#' @return The `kqo` input object with updated slots `collectedMatches`, `apiResponse`, `nextStartIndex`, `hasMoreMatches`
Marc Kupietz62da2b52019-09-12 17:43:34 +0200237#'
Marc Kupietz05b22772020-02-18 21:58:42 +0100238#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200239#' \dontrun{
240#'
241#' q <- new("KorAPConnection") %>% corpusQuery("Ameisenplage") %>% fetchNext()
Marc Kupietz05b22772020-02-18 21:58:42 +0100242#' q@collectedMatches
Marc Kupietz657d8e72020-02-25 18:31:50 +0100243#' }
Marc Kupietz05b22772020-02-18 21:58:42 +0100244#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200245#' @references
Marc Kupietz67edcb52021-09-20 21:54:24 +0200246#' <https://ids-pub.bsz-bw.de/frontdoor/index/index/docId/9026>
Marc Kupietz62da2b52019-09-12 17:43:34 +0200247#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200248#' @aliases fetchNext
249#' @rdname KorAPQuery-class
Marc Kupietzcb3c59e2020-06-02 10:10:43 +0200250#' @importFrom dplyr rowwise bind_rows select summarise n
Marc Kupietz632cbd42019-09-06 16:04:51 +0200251#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200252setMethod("fetchNext", "KorAPQuery", function(kqo,
253 offset = kqo@nextStartIndex,
254 maxFetch = maxResultsPerPage,
255 verbose = kqo@korapConnection@verbose,
256 randomizePageOrder = FALSE) {
Marc Kupietze95108e2019-09-18 13:23:58 +0200257 if (kqo@totalResults == 0 || offset >= kqo@totalResults) {
258 return(kqo)
Marc Kupietz62da2b52019-09-12 17:43:34 +0200259 }
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200260
Marc Kupietz705488d2021-06-30 18:26:36 +0200261 page <- kqo@nextStartIndex / maxResultsPerPage + 1
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200262 results <- 0
Marc Kupietz25aebc32019-09-16 18:40:50 +0200263 pubDate <- NULL # https://stackoverflow.com/questions/8096313/no-visible-binding-for-global-variable-note-in-r-cmd-check
Marc Kupietze95108e2019-09-18 13:23:58 +0200264 collectedMatches <- kqo@collectedMatches
Marc Kupietz62da2b52019-09-12 17:43:34 +0200265
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200266 if (randomizePageOrder) {
267 pages <- head(sample.int(ceiling(kqo@totalResults / maxResultsPerPage)), maxFetch) - 1
268 }
269
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200270 repeat {
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200271 page = length(collectedMatches[,1]) %/% maxResultsPerPage + 1
272 currentOffset = ifelse(randomizePageOrder, pages[page], page - 1) * maxResultsPerPage
273 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 +0200274 res <- apiCall(kqo@korapConnection, query)
275 if (length(res$matches) == 0) {
276 break
277 }
278
Marc Kupietze95108e2019-09-18 13:23:58 +0200279 for (field in kqo@fields) {
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200280 if (!field %in% colnames(res$matches)) {
281 res$matches[, field] <- NA
282 }
283 }
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200284 currentMatches <-
Marc Kupietzf75ab0b2020-06-02 12:31:18 +0200285 res$matches %>%
Marc Kupietz19e2ebd2019-10-07 11:45:30 +0200286 dplyr::select(kqo@fields)
Marc Kupietz36d12d92019-09-27 18:13:27 +0200287 if ("pubDate" %in% kqo@fields) {
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200288 currentMatches$pubDate <- currentMatches$pubDate %>% as.Date(format = "%Y-%m-%d")
289 factorCols <- currentMatches %>% select(-pubDate) %>% colnames()
Marc Kupietz36d12d92019-09-27 18:13:27 +0200290 } else {
291 factorCols <- colnames(currentMatches)
292 }
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200293 currentMatches[factorCols] <- lapply(currentMatches[factorCols], factor)
Marc Kupietz62da2b52019-09-12 17:43:34 +0200294 if (!is.list(collectedMatches)) {
295 collectedMatches <- currentMatches
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200296 } else {
Marc Kupietz62da2b52019-09-12 17:43:34 +0200297 collectedMatches <- rbind(collectedMatches, currentMatches)
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200298 }
Marc Kupietzc2c59bd2019-08-30 16:50:49 +0200299 if (verbose) {
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200300 cat(paste0(
301 "Retrieved page ",
302 ceiling(length(collectedMatches[, 1]) / res$meta$itemsPerPage),
303 "/",
304 if (!is.na(maxFetch) && maxFetch < kqo@totalResults)
305 sprintf("%d (%d)", ceiling(maxFetch / res$meta$itemsPerPage), ceiling(kqo@totalResults / res$meta$itemsPerPage))
306 else
307 sprintf("%d", ceiling(kqo@totalResults / res$meta$itemsPerPage)),
308 ' in ',
309 res$meta$benchmark,
310 '\n'
311 ))
Marc Kupietzc2c59bd2019-08-30 16:50:49 +0200312 }
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200313 page <- page + 1
314 results <- results + res$meta$itemsPerPage
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200315 if (length(collectedMatches[,1]) >= kqo@totalResults || (!is.na(maxFetch) && results >= maxFetch)) {
Marc Kupietz5bbc9db2019-08-30 16:30:45 +0200316 break
317 }
318 }
Marc Kupietz68170952021-06-30 09:37:21 +0200319 nextStartIndex <- min(res$meta$startIndex + res$meta$itemsPerPage, kqo@totalResults)
Marc Kupietze95108e2019-09-18 13:23:58 +0200320 KorAPQuery(nextStartIndex = nextStartIndex,
Marc Kupietzd0d3e9b2019-09-24 17:36:03 +0200321 korapConnection = kqo@korapConnection,
Marc Kupietze95108e2019-09-18 13:23:58 +0200322 fields = kqo@fields,
323 requestUrl = kqo@requestUrl,
324 request = kqo@request,
Marc Kupietz68170952021-06-30 09:37:21 +0200325 totalResults = kqo@totalResults,
Marc Kupietze95108e2019-09-18 13:23:58 +0200326 vc = kqo@vc,
327 webUIRequestUrl = kqo@webUIRequestUrl,
Marc Kupietz68170952021-06-30 09:37:21 +0200328 hasMoreMatches = (kqo@totalResults > nextStartIndex),
Marc Kupietze95108e2019-09-18 13:23:58 +0200329 apiResponse = res,
330 collectedMatches = collectedMatches)
331})
Marc Kupietz62da2b52019-09-12 17:43:34 +0200332
333#' Fetch all results of a KorAP query.
Marc Kupietz62da2b52019-09-12 17:43:34 +0200334#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200335#' **`fetchAll`** fetches all results of a KorAP query.
Marc Kupietza6e4ee62021-03-05 09:00:15 +0100336#'
Marc Kupietz62da2b52019-09-12 17:43:34 +0200337#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200338#' \dontrun{
339#'
Marc Kupietz69cc54a2019-09-30 12:06:54 +0200340#' q <- new("KorAPConnection") %>% corpusQuery("Ameisenplage") %>% fetchAll()
Marc Kupietze95108e2019-09-18 13:23:58 +0200341#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100342#' }
Marc Kupietz62da2b52019-09-12 17:43:34 +0200343#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200344#' @aliases fetchAll
345#' @rdname KorAPQuery-class
Marc Kupietz62da2b52019-09-12 17:43:34 +0200346#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200347setMethod("fetchAll", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
348 return(fetchNext(kqo, offset = 0, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200349})
350
351#' Fetches the remaining results of a KorAP query.
352#'
353#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200354#' \dontrun{
355#'
Marc Kupietz05b22772020-02-18 21:58:42 +0100356#' q <- new("KorAPConnection") %>% corpusQuery("Ameisenplage") %>% fetchRest()
Marc Kupietze95108e2019-09-18 13:23:58 +0200357#' q@collectedMatches
Marc Kupietz05b22772020-02-18 21:58:42 +0100358#' }
Marc Kupietze95108e2019-09-18 13:23:58 +0200359#'
360#' @aliases fetchRest
361#' @rdname KorAPQuery-class
362#' @export
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200363setMethod("fetchRest", "KorAPQuery", function(kqo, verbose = kqo@korapConnection@verbose, ...) {
364 return(fetchNext(kqo, maxFetch = NA, verbose = verbose, ...))
Marc Kupietze95108e2019-09-18 13:23:58 +0200365})
366
Marc Kupietz3f575282019-10-04 14:46:04 +0200367#' Query relative frequency of search term(s)
368#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200369#' **`frequencyQuery`** combines [corpusQuery()], [corpusStats()] and
370#' [ci()] to compute a table with the relative frequencies and
Marc Kupietz3f575282019-10-04 14:46:04 +0200371#' confidence intervals of one ore multiple search terms across one or multiple
372#' virtual corpora.
373#'
374#' @aliases frequencyQuery
375#' @rdname KorAPQuery-class
376#' @examples
Marc Kupietz6ae76052021-09-21 10:34:00 +0200377#' \dontrun{
378#'
Marc Kupietz3f575282019-10-04 14:46:04 +0200379#' new("KorAPConnection", verbose = TRUE) %>%
380#' frequencyQuery(c("Mücke", "Schnake"), paste0("pubDate in ", 2000:2003))
Marc Kupietz05b22772020-02-18 21:58:42 +0100381#' }
Marc Kupietz3f575282019-10-04 14:46:04 +0200382#'
Marc Kupietz67edcb52021-09-20 21:54:24 +0200383#' @param kco [KorAPConnection()] object (obtained e.g. from `new("KorAPConnection")`
384#' @param query string that contains the corpus query. The query language depends on the `ql` parameter. Either `query` must be provided or `KorAPUrl`.
385#' @param conf.level confidence level of the returned confidence interval (passed through [ci()] to [prop.test()]).
386#' @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 Kupietz3f575282019-10-04 14:46:04 +0200387#' @export
388setMethod("frequencyQuery", "KorAPConnection",
Marc Kupietz71d6e052019-11-22 18:42:10 +0100389 function(kco, query, vc = "", conf.level = 0.95, as.alternatives = FALSE, ...) {
390 (if (as.alternatives) {
391 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) %>%
392 group_by(vc) %>%
393 mutate(total = sum(totalResults))
394 } else {
395 corpusQuery(kco, query, vc, metadataOnly = TRUE, as.df = TRUE, ...) %>%
396 mutate(total = corpusStats(kco, vc=vc, as.df=TRUE)$tokens)
397 } ) %>%
Marc Kupietz0c29cea2019-10-09 08:44:36 +0200398 ci(conf.level = conf.level)
Marc Kupietz3f575282019-10-04 14:46:04 +0200399})
400
Marc Kupietzdbd431a2021-08-29 12:17:45 +0200401
402#' buildWebUIRequestUrl
403#'
404#' @rdname KorAPQuery-class
405#' @importFrom urltools url_encode
406#' @export
407buildWebUIRequestUrl <- function(kco,
408 query = if (missing(KorAPUrl))
409 stop("At least one of the parameters query and KorAPUrl must be specified.", call. = FALSE)
410 else
411 httr::parse_url(KorAPUrl)$query$q,
412 vc = if (missing(KorAPUrl)) "" else httr::parse_url(KorAPUrl)$query$cq,
413 KorAPUrl,
414 metadataOnly = TRUE,
415 ql = if (missing(KorAPUrl)) "poliqarp" else httr::parse_url(KorAPUrl)$query$ql,
416 fields = c(
417 "corpusSigle",
418 "textSigle",
419 "pubDate",
420 "pubPlace",
421 "availability",
422 "textClass",
423 "snippet"
424 ),
425 accessRewriteFatal = TRUE) {
426 request <-
427 paste0(
428 '?q=',
429 urltools::url_encode(enc2utf8(as.character(query))),
430 ifelse(vc != '',
431 paste0('&cq=', urltools::url_encode(enc2utf8(vc))),
432 ''),
433 '&ql=',
434 ql
435 )
436 webUIRequestUrl <- paste0(kco@KorAPUrl, request)
437 requestUrl <- paste0(
438 kco@apiUrl,
439 'search',
440 request,
441 '&fields=',
442 paste(fields, collapse = ","),
443 if (metadataOnly)
444 '&access-rewrite-disabled=true'
445 else
446 ''
447 )
448 webUIRequestUrl
449}
450
Marc Kupietze95108e2019-09-18 13:23:58 +0200451#´ format()
452#' @rdname KorAPQuery-class
453#' @param x KorAPQuery object
454#' @param ... further arguments passed to or from other methods
455#' @export
456format.KorAPQuery <- function(x, ...) {
457 cat("<KorAPQuery>\n")
458 q <- x
459 aurl = parse_url(q@request)
Marc Kupietz0d4c9092020-03-23 09:02:30 +0100460 cat(" Query: ", aurl$query$q, "\n")
461 if (!is.null(aurl$query$cq) && aurl$query$cq != "") {
462 cat(" Virtual corpus: ", aurl$query$cq, "\n")
Marc Kupietze95108e2019-09-18 13:23:58 +0200463 }
464 if (!is.null(q@collectedMatches)) {
465 cat("==============================================================================================================", "\n")
466 print(summary(q@collectedMatches))
467 cat("==============================================================================================================", "\n")
468 }
469 cat(" Total results: ", q@totalResults, "\n")
470 cat(" Fetched results: ", q@nextStartIndex, "\n")
Marc Kupietz62da2b52019-09-12 17:43:34 +0200471}
472
Marc Kupietze95108e2019-09-18 13:23:58 +0200473#' show()
Marc Kupietz62da2b52019-09-12 17:43:34 +0200474#'
Marc Kupietze95108e2019-09-18 13:23:58 +0200475#' @rdname KorAPQuery-class
476#' @param object KorAPQuery object
Marc Kupietz62da2b52019-09-12 17:43:34 +0200477#' @export
Marc Kupietze95108e2019-09-18 13:23:58 +0200478setMethod("show", "KorAPQuery", function(object) {
479 format(object)
480})
Marc Kupietz006b47c2021-01-13 17:00:59 +0100481