Add Individuals to owl file with SPARQL query - insert

i want to insert some individuals into my ontology owl file (OWL/XML) with SPARQL using Protege for example :
person1 is an instance of class person and has these object property assertions : hasname Alex, hasage 26
Here is my code
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX my_onto: <http://www.semanticweb.org/hp/ontologies/2020/5/personOnto.owl#>
INSERT DATA
{
my_onto:person1 rdf:type my_onto:person .
rdf:type owl:NamedIndividual .
my_onto:hasname Alex.
my_onto:hasage 26.
}
But, i had this error :
Caused by: org.openrdf.query.parser.sparql.ast.ParseException: Encountered " "insert" "INSERT "" at line 7, column 1.
Was expecting one of:
"base" ...
"prefix" ...
"select" ...
"construct" ...
"describe" ...
"ask" ...
at org.openrdf.query.parser.sparql.ast.SyntaxTreeBuilder.generateParseException(SyntaxTreeBuilder.java:8943) ~[na:na]
at org.openrdf.query.parser.sparql.ast.SyntaxTreeBuilder.jj_consume_token(SyntaxTreeBuilder.java:8813) ~[na:na]
at org.openrdf.query.parser.sparql.ast.SyntaxTreeBuilder.Query(SyntaxTreeBuilder.java:313) ~[na:na]
at org.openrdf.query.parser.sparql.ast.SyntaxTreeBuilder.QueryContainer(SyntaxTreeBuilder.java:188) ~[na:na]
at org.openrdf.query.parser.sparql.ast.SyntaxTreeBuilder.parseQuery(SyntaxTreeBuilder.java:31) ~[na:na]
at org.openrdf.query.parser.sparql.SPARQLParser.parseQuery(SPARQLParser.java:153) ~[na:na]
... 42 common frames omitted

Related

SPARQL - Filter all instances that only contain a condition

I have recipes with ingredients that have a category.
#prefix schema: <http://schema.org/> .
#prefix ex: <http://example.org> .
ex:recipe1 a schema:Recipe ;
schema:recipeIngredient ex:ingredient1 , ex:ingredient3 .
ex:recipe2 a schema:Recipe ;
schema:recipeIngredient ex:ingredient1, ex:ingredient2 .
ex:ingredient1 ex:category ex:plant .
ex:ingredient2 ex:category ex:spice .
ex:ingredient3 ex:category ex:meat .
ex:ingredient4 ex:category ex:fish .
I want to filter all recipes that only contain ingredients from the category ex:plants or ex:spice. I tried:
SELECT ?recipes
WHERE {
?recipes a schema:Recipe;
schema:recipeIngredient ?ingredient.
?ingredient ex:category ?category.
FILTER(?category NOT IN (ex:meat && ex:fish))
}
This returns both recipes, I guess because ex:recipe1 also includes a ex:plant. However, my desired output is only ex:recipe2 because it does not contain any ex:meat or ex:fish. If any ex:meat or ex:fish is included in the recipes, I want it to be excluded from the result set.

Stardog raises ConcurrentModificationException upon reasoned query on graph with SWRL Rules

When trying to execute a query with reasoning in a model, I get this error: 000012: com.complexible.stardog.plan.eval.operator.OperatorException: Uncaught error during query evaluation: ConcurrentModificationException
Ontology model has 2 SWRL rules and is consistent, as it runs fine in Protege (with built-in pellet reasoner). Model has been imported into a stardog rdf model and the query
SELECT ?tse
FROM <urn:test_graph>
{
?tse a :TaperedShaftEnd
}
fails with the above error message.
By deleting the SWRL rules the query runs fine, but of course the model does no longer represent the desired domain. By translating the SWRL rules into stardog native rules, the error appears again.
Reasoning level is set to DL, as SL would imply too high processing times for the target application.
Changing the sameAs flag in the reasoner options does not change the behavior.
Setting the reasoning level to SL, as advised generally in Stardog documentation would solve the problem on this simplified model, but as said would result impractical for the use on the final target application.
May you help me in identifying the root cause and the possible solution?
Did anyone experienced the same issue when dealing with SWRL rules?
Here below the concerned model in turtle format, to easily replicate the issue on a test graph.
Heartful thanks to anyone who may help me with this.
#prefix : <http://api.stardog.com/> .
#prefix owl: <http://www.w3.org/2002/07/owl#> .
#prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
#prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
#prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
#prefix stardog: <tag:stardog:api:> .
#prefix test: <urn:test_graph#> .
<http://swrl.stanford.edu/ontologies/3.3/swrla.owl#isRuleEnabled> a owl:AnnotationProperty .
<urn:test> a owl:Ontology .
:hasTorqueTransmissionConnectionWith a owl:ObjectProperty , owl:FunctionalProperty , owl:InverseFunctionalProperty , owl:SymmetricProperty , owl:IrreflexiveProperty .
:CouplingConnection a owl:Class ;
owl:disjointWith :ShaftEnd .
:ShaftEnd a owl:Class ;
owl:disjointWith :ShaftEnd .
:LeftCouplingConnection a owl:Class ;
rdfs:subClassOf :CouplingConnection ;
owl:disjointWith :RightCouplingConnection .
:RightCouplingConnection a owl:Class ;
rdfs:subClassOf :CouplingConnection .
:LeftShaftEnd a owl:Class ;
rdfs:subClassOf :ShaftEnd ;
owl:disjointWith :RightShaftEnd .
:RightShaftEnd a owl:Class ;
rdfs:subClassOf :ShaftEnd .
:TaperedCouplingConnection a owl:Class , <tag:stardog:api:rule:SPARQLRule> ;
rdfs:subClassOf :CouplingConnection ;
<tag:stardog:api:rule:content> """IF {
?tse a :TaperedShaftEnd .
?tse :hasTorqueTransmissionConnectionWith ?cc .
?cc a :CouplingConnection .
}
THEN {
?cc a :TaperedCouplingConnection .
}
""" .
:TaperedShaftEnd a owl:Class , <tag:stardog:api:rule:SPARQLRule> ;
rdfs:subClassOf :ShaftEnd ;
<tag:stardog:api:rule:content> """IF {
?tcc a :TaperedCouplingConnection .
?tcc :hasTorqueTransmissionConnectionWith ?se .
?se a :ShaftEnd .
}
THEN {
?se a :TaperedShaftEnd .
}
""" .
:lcc1 a :LeftCouplingConnection , owl:NamedIndividual .
:lse2 a :LeftShaftEnd , owl:NamedIndividual .
:rcc2 a :RightCouplingConnection , :TaperedCouplingConnection , owl:NamedIndividual ;
:hasTorqueTransmissionConnectionWith :lse2 .
:rse1 a :RightShaftEnd , owl:NamedIndividual ;
:hasTorqueTransmissionConnectionWith :lcc1 .

Is it possible for unit test cases for Spring boot data jpa #Query native queries?

I have a spring boot application with JPA configured. While querying the database i am running native sql query with the help of spring data #query annotation. Now i am planning to write test cases using spring boot test framework. Is it possible to write tests or not?
Code:
String searchQuery = "SELECT dh1.* FROM device_hist AS dh1 JOIN (" +
"SELECT rank() OVER (PARTITION BY dh.device_nm, dh.lst_log_in_user_id ORDER BY lst_chkin_ts DESC), " +
"dh.device_nm, dh.lst_log_in_user_id, dh.lst_chkin_ts FROM device_hist dh) AS T ON dh1.device_nm = T.device_nm " +
"AND dh1.lst_log_in_user_id = T.lst_log_in_user_id AND dh1.lst_chkin_ts = T.lst_chkin_ts WHERE T.rank = 1 AND " +
"dh1.lst_chkin_ts >= :lst_chkin_ts ";
String searchCountQuery = "SELECT count(*) FROM device_hist AS dh1 JOIN (" +
"SELECT rank() OVER (PARTITION BY dh.device_nm, dh.lst_log_in_user_id ORDER BY lst_chkin_ts DESC), " +
"dh.device_nm, dh.lst_log_in_user_id, dh.lst_chkin_ts FROM device_hist dh) AS T on h1.device_nm = T.device_nm " +
"AND dh1.lst_log_in_user_id = T.lst_log_in_user_id AND dh1.lst_chkin_ts = T.lst_chkin_ts WHERE T.rank = 1 " +
"AND dh1.lst_chkin_ts >= :lst_chkin_ts ";
#Query(value = searchQuery + "ORDER BY dh1.device_nm, dh1.lst_chkin_ts DESC",
countQuery = searchCountQuery,
nativeQuery = true)
Page<DeviceHistory> findAllLatestDeviceHistoryBylastCheckInTimeStamp(
#Param("lst_chkin_ts") Date lastCheckInTimeStamp, Pageable pageable);
Testcase:
#Test
void testfindAllLatestDeviceHistoryBylastCheckInTimeStamp() {
LocalDate localDateTime = LocalDate.now();
ZoneId defaultZoneId = ZoneId.systemDefault();
Instant instant = localDateTime.minusDays(10).atStartOfDay(defaultZoneId).toInstant();
Date timeStamp = Date.from(instant);
Page<DeviceHistory> devices = deviceHistoryRepository.findAllLatestDeviceHistoryBylastCheckInTimeStamp(timeStamp, pageable);
assertNotNull(devices.getContent());
}
Error:
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:281)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:528)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:149)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy138.findAllLatestDeviceHistoryBylastCheckInTimeStamp(Unknown Source)
at com.aexp.de.crypto.wde.server.repository.DeviceHistoryRepositoryTest.testfindAllLatestDeviceHistoryBylastCheckInTimeStamp(DeviceHistoryRepositoryTest.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
...
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
... 96 more
Caused by: org.postgresql.util.PSQLException: ERROR: missing FROM-clause entry for table "h1"
I think you have a problem in
String searchCountQuery
Exception told you that you have problem with something called h1 table
ERROR: missing FROM-clause entry for table "h1"
As far as I can see this string contains h1:
"dh.device_nm, dh.lst_log_in_user_id, dh.lst_chkin_ts FROM device_hist dh) AS T on h1.device_nm = T.device_nm ". (should be dh1 I guess)
Usually if you are facing SQLGrammarException: could not extract ResultSet then its probably a problem with your SQL. Also the rest of a stack trace usally helps to clarify the issue.

SPARQL INSERT query in Protege

I'm trying to map my Data Properties in Protege to owl:Class with Sparql but it doesn't work. If any one has an example, please don't hesitate to give me an answer.
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX myOnto: <http://imis/SNI/9.4.3#>
INSERT DATA
{
?s rdf:type owl:Class
}
WHERE { ?s ?o owl:DatatypeProperty}
When i was running it i got this message . Please help me to resolve this problem.
Error 61 Logged at Wed Oct 15 23:11:26 CEST 2014
SparqlReasonerException: org.openrdf.query.MalformedQueryException: Encountered " "insert" "INSERT "" at line 7, column 1.
Was expecting one of:
"base" ...
"prefix" ...
"select" ...
"construct" ...
"describe" ...
"ask" ...

RDflib results printing error on windows7

I use SPARQLWrapper to create SPARQL queries, but I don't know how to debug the following error message:
Warning (from warnings module):
File "D:\Python27\lib\site-packages\sparqlwrapper-1.5.2-py2.7.egg\SPARQLWrapper\Wrapper.py", line 550
RuntimeWarning: unknown response content type, returning raw response...
Traceback (most recent call last):
File "D:\Python27\testwrapper.py", line 31, in <module>
if (len(results["results"]["bindings"]) == 0):
AttributeError: addinfourl instance has no attribute '__getitem__'
This is my code:
from SPARQLWrapper import SPARQLWrapper,JSON
sparql = SPARQLWrapper('http://thedatahub.org/dataset/semanticquran');
queryString = """
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX olia-ar: <http://purl.org/olia/arabic_khoja.owl#>
PREFIX dcterms: <http://purl.org/dc/terms/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX lexvo: <http://lexvo.org/id/iso639-3/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX gold: <http://purl.org/linguistics/gold/>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX qvoc: <http://www.nlp2rdf.org/quranvocab#>
SELECT DISTINCT ?wordText ?pos
WHERE
{ ?wordPart rdf:type qvoc:LexicalItem .
?wordPart gold:Root "smw" .
?wordPart dcterms:isPartOf ?word .
?wordPart gold:PartOfSpeechProperty ?pos .
?word rdf:type qvoc:Word .
?word skos:prefLabel ?wordText
}
"""
sparql.setQuery(queryString)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
if (len(results["results"]["bindings"]) == 0):
print "No results found."
else:
for result in results["results"]["bindings"]:
print result["wordText"]["value"]
Any Help?
The return format is not JSON, so the setReturnFormat call is not working as expected:
Encode the return value depending on the return format:
in the case of XML, a DOM top element is returned;
in the case of JSON, a simplejson conversion will return a dictionary;
in the case of RDF/XML, the value is converted via RDFLib into a Graph instance.
In all other cases the input simply returned.

Resources