Querying an Ontology from R

This article explores how we can query an ontology in GraphDB from R opening it up for analytics.

Step-by-step: Query competency questions using R

GraphDB exposes a SPARQL endpoint to which you can send SPARQL queries using HTTP POST and parse the JSON results. The endpoint is located at:

http://192.168.1.102:7200/repositories/banking

The entire R code is given below that will help raising the competency questions to the end-point and receiving the json responses:


# Install required R packages
# install.packages("httr")
# install.packages("jsonlite")

library(httr)
library(jsonlite)

# Define your GraphDB endpoint
endpoint <- "http://192.168.1.102:7200/repositories/banking"

# Create a helper function to run SPARQL queries
run_sparql <- function(query) {
  res <- POST(
    url = endpoint,
    body = list(query = query),
    encode = "form",
    accept_json()
  )
  
  json <- content(res, "text", encoding = "UTF-8")
  parsed <- fromJSON(json)
  
  parsed$results$bindings
}

# Run your competency questions
# CQ1 - Which accounts belong to Alice?
query <- "
PREFIX : <http://example.org/banking#>

SELECT ?account
WHERE {
  ?account a :BankAccount .
  ?account :hasOwner :Alice .
}
"

run_sparql(query)

# CQ2 — What is the balance of AliceSavings?
query <- "
PREFIX : <http://example.org/banking#>

SELECT ?balance
WHERE {
  :AliceSavings :balance ?balance .
}
"

run_sparql(query)

# CQ3 — What transactions occurred on 2025‑01‑15?
query <- "
PREFIX : <http://example.org/banking#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>

SELECT ?txn ?amount
WHERE {
  ?txn a :Transaction .
  ?txn :transactionDate \"2025-01-15T10:30:00\"^^xsd:dateTime .
  ?txn :amount ?amount .
}
"

run_sparql(query)

# CQ4 — Which transactions were deposits?
query <- "
PREFIX : <http://example.org/banking#>

SELECT ?txn
WHERE {
  ?txn a :Deposit .
}
"

run_sparql(query)

df <- as.data.frame(run_sparql(query))
print(df)

The output of the final CQ is shown in the figure below:

In the ensuing articles, we will explore how to scale this ontology graph with additional data and classes to explore complex graph queries and features.

Comments

Leave a Reply

Check also

View Archive [ -> ]

Discover more from ANALYTI

Subscribe now to keep reading and get access to the full archive.

Continue reading