Search code examples
pythonpandasdataframesparqlrdflib

Using variables with stored values in RDFLIB and Python for Sparql update statement


I am quite new to RDFLIB and I am trying to learn how to use Delete/Insert statement to continually update data property values of individuals in my ontology from a CSV file. I am using pandas dataframe to do this but I am now stuck.

I am able to do this successfully if I am to use values directly such as 23, 34.6, 13330, etc. but my challenge is that this does not work if I read data from CSV and store it a variable say 'x'. Here is the section of my codes that works fine:

g.update( """ DELETE { ?Product myontology:LifecycleData ?lifecycle } INSERT { ?Product myontology:LifecycleData 243 } WHERE { ?Product myontology:LifecycleData ?lifecycle . } """)

Now, if I assign the value 243 to x, that is x=243 and replace 243 with x in the code above, I get errors. Can somebody help me on how to manipulate this? I can provide more information if needed but I am trying to keep it short. Thank you in advance.


Solution

  • I would separate your string query building from query submission and test the query (visually) and ensure that it's correct like this:

    q = """
        DELETE {
            ?Product myontology:LifecycleData ?lifecycle 
        }
        INSERT {
            ?Product myontology:LifecycleData xxx 
        }
        WHERE {
            ?Product myontology:LifecycleData ?lifecycle  
        }
        """.replace("xxx", str(df.tail(1)['Usecycle left'].values[0]))
    
    # I like to use replace() rather than string templating
    # so I don't have to escape characters like { in the query
    
    print(q)  # does it look like you expect it to at this point?
    
    # then...
    g.update(
        q, 
        initNs={
            "myontology": Namespace("http://example.com/myontology#")
        }
    )