Skip to content

Instantly share code, notes, and snippets.

@tts
Last active January 8, 2022 18:38
Show Gist options
  • Save tts/c90a9cd4c074cd80f09082e2bb6585a4 to your computer and use it in GitHub Desktop.
Save tts/c90a9cd4c074cd80f09082e2bb6585a4 to your computer and use it in GitHub Desktop.
library(tidyverse)
sparql_endpoint <- "http://dbpedia.org/sparql"
# Query example from https://medium.com/virtuoso-blog/dbpedia-basic-queries-bc1ac172cc09
q <- "
SELECT ?athlete ?cityName
WHERE
{
?athlete rdfs:label 'Cristiano Ronaldo'@en ;
dbo:birthPlace ?place .
?place a dbo:City ;
rdfs:label ?cityName .
FILTER ( LANG ( ?cityName ) = 'en' )
}"
# Simplified/modified functions from https://github.com/kvasilopoulos/uklr/blob/master/R/query.R
sparql <- function(query, endpoint = sparql_endpoint, ...){
enc_query <- gsub("\\+", "%2B", URLencode(q, reserved = TRUE))
res <- httr::GET(
paste(endpoint, "?query=", enc_query, sep = ""),
httr::add_headers("Accept" = "application/sparql-results+json"),
...
)
res
}
process_json <- function(res) {
res <- jsonlite::parse_json(res, simplifyVector = TRUE)$results$bindings
}
result <- process_json(sparql(q))
result_df <- do.call(data.frame, result) %>%
select(ends_with("value"))
@msoengas
Copy link

I ran the code and the result was :

result <- process_json(sparql(q))
No encoding supplied: defaulting to UTF-8.

@tts
Copy link
Author

tts commented Jan 8, 2022

Yes, but that's only a warning/notification. The final step of the code should still work fine:

result_df <- do.call(data.frame, result) %>% 
  select(ends_with("value"))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment