Skip to content

Commit

Permalink
ENH: Add function for extracting all triples with a given predicate
Browse files Browse the repository at this point in the history
  • Loading branch information
davidkleiven committed Mar 9, 2024
1 parent f32deac commit 9e36552
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/main/ExternalTripleStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,10 @@ fun extractPrefixes(catalog: QueryCatalog): Map<String, String> {
val matches = catalog.values.map { query -> regex.findAll(query) }.asSequence().flatten()
return matches.map { match -> Pair(match.groupValues[0], match.groupValues[1]) }.toMap()
}

fun createExtractionQuery(query: ParsedSparqlQuery): String {
val prefix = query.prefixes.map { entry -> "PREFIX ${entry.key}: ${entry.value}" }.joinToString(separator = "\n")
val predicates = query.predicates.joinToString(separator = " ")
val select = "SELECT ?graph ?s ?p ?o {\nVALUES ?p { $predicates }\nGRAPH ?graph {?s ?p ?o}}"
return "$prefix\n$select"
}
18 changes: 18 additions & 0 deletions src/test/TestExternalTripleStore.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import com.github.statnett.loadflowservice.ParsedSparqlQuery
import com.github.statnett.loadflowservice.createExtractionQuery
import com.github.statnett.loadflowservice.parseQuery
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class TestExternalTripleStore {
Expand All @@ -10,4 +13,19 @@ class TestExternalTripleStore {
assertTrue { queryContent.predicates.containsAll(expect) }
assertTrue { queryContent.prefixes.isNotEmpty() }
}

@Test
fun `test create extraction query`() {
val parsedQuery =
ParsedSparqlQuery(
mapOf("md" to "<http://md>", "cim" to "<http://cim>"),
setOf("cim:a", "md:b"),
)

val expectedQuery = (
"PREFIX md: <http://md>\nPREFIX cim: <http://cim>\nSELECT ?graph ?s ?p ?o {\n" +
"VALUES ?p { cim:a md:b }\nGRAPH ?graph {?s ?p ?o}}"
)
assertEquals(createExtractionQuery(parsedQuery), expectedQuery)
}
}

0 comments on commit 9e36552

Please sign in to comment.