Skip to content

Instantly share code, notes, and snippets.

@jjkoehorst
Created April 12, 2023 17:03
Show Gist options
  • Save jjkoehorst/3b1ccdad800f34b4b1039bf88f58bc44 to your computer and use it in GitHub Desktop.
Save jjkoehorst/3b1ccdad800f34b4b1039bf88f58bc44 to your computer and use it in GitHub Desktop.
SPARQL function for R
# Script to query the triple store
library(stringr)
library(httr)
library(jsonlite)
# SPARQL endpoint where the triple store endpoint is located
endpoint = "http://localhost:7200/repositories/wur_unlock_hivghana_drp0070"
# create a named character vector of URLs and prefixes
url_dict <- c("http://example.com/" = "ex:",
"http://gbol.life/0.1/" = "gbol:",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#" = "rdf:",
"http://www.w3.org/2000/01/rdf-schema#" = "rdfs:",
"http://www.w3.org/2002/07/owl#" = "owl:",
"http://www.w3.org/2001/XMLSchema#" = "xsd:",
"http://purl.org/dc/terms/" = "dcterms:",
"http://purl.org/dc/elements/1.1/" = "dc:",
"http://purl.org/dc/dcmitype/" = "dcmitype:",
"http://purl.org/dc/dcam/" = "dcam:",
"http://purl.org/dc/qualifiers/1.0/" = "dcq:"
)
prefix_cleaner <- function(x, prefixes = url_dict) {
x <- as.character(x)
for (u in names(url_dict)) {
x <- str_replace(x, u, url_dict[u])
}
return(x)
}
# SPARQL function to query the triple store
sparql <- function(query, endpoint, prefixes = NULL) {
res <- httr::GET(endpoint, query = list(query = query, format = "json"))
if (res$status_code != 200) {
stop("Error: ", res$status_code, " ", res$reason)
}
# return(content(res, "text", encoding = "UTF-8"))
dfGraph = jsonlite::fromJSON(content(res, "text", encoding = "UTF-8"))
dfGraph <- as.data.table(dfGraph$results$bindings)
# Keep only the columns that contain the value
table = dfGraph[,grep(".value", names(dfGraph), value=TRUE), with=FALSE]
# Clean the table
table <- mapply(prefix_cleaner, table, prefixes)
# table$library.value <- prefix(table$library.value)
return(as.data.frame(table))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment