1

I have a project where the goal is to add user input into a turtle file (Named Main_Triples) that contains data about countries. I am using python to create functions that takes parameters to insert using SPARQL. I have to use SPARQL. How do I write this in SPARQL, and update the file?

My rdf structure:

ex:Afghanistan a country:addressCountry ;
    ex:HappyLifeYear_Index 1.24e+01 ;
    ex:SCI 37 ;
    ex:UHC 34 ;
    ex:average_wellbeing 3.8e+00 ;
    ex:avglifeexp 5.97e+01 ;
    ex:gdp 691 ;
    ex:hpi_rank 110 ;
    ex:hpi_total_score 2.02e+01 ;
    ex:inequality_of_Outcome 43 ;
    ex:info_availability "high" ;
    ex:inregion "MiddleEastandNorthAfrica" ;
    ex:population_count 29726803 .

My basic python code (not functioning. I want to take the parameters as input, and add a predicate/object to say Afghanistan.

def addcountryfact(country, fact, data):
    country = URIRef(ex + country)
    fact = URIRef(ex + fact)
    data = URIRef(ex + data)
    addto = ("""
         PREFIX ex: <http://example.org/>
         INSERT ?country ?fact ?data 
         WHERE {
         ?country ?fact ?data
           }
         """)
    addto = g.query(cd, initBindings={'fact': fact, 'country': country, 'data': data})

cdlane
  • 40,441
  • 5
  • 32
  • 81
Maffe
  • 13
  • 3
  • you have to call `g.update` for SPARQL Update queries: https://rdflib.readthedocs.io/en/stable/apidocs/rdflib.html#rdflib.graph.Graph.update - moreover, your query is wrong as braces are missing: `INSERT {?country ?fact ?data} WHERE { ?country ?fact ?data}` - that said, if all entities of the triple pattern are bound `INSERT DATA {?country ?fact ?data}` is the better query. Or just use rdflib methods `g.add((country, fact, data))` – UninformedUser May 14 '20 at 14:11
  • @UninformedUser you should put this in as an answer, not a comment, so the questioner can select it as an answer and others can see it's been answered. – Nicholas Car May 19 '20 at 06:48

1 Answers1

2
EX = Namespace("http://example.org/")

def add_country_fact(country, fact, data):
    q = """
        INSERT DATA {
            ?country ?fact ?data .
        }
        """
    g.update(
        q, 
        initBindings={
            'fact': EX[fact], 
            'country': EX[country], 
            'data': EX[data]
        }
    )

I presume this is a student exercise to use SPARQL else you would do as @UninformedUser suggests in comments:

def add_country_fact(country, fact, data):
    g.add((
        EX[country],
        EX[fact],
        EX[data]
    ))

Using g.add(()) is simpler and faster (no need to translate to/from SPARQL.

Nicholas Car
  • 1,164
  • 4
  • 7