0

My question is probably a simple one: how can I use python variables in a SPARQL query? I'm trying to make the query to recognize something that a user typed.

For example, if the user types "house", the software will run the query with that entry. For now, I've run a test with this code (I'm using Tkinter):

self.queryonto = Entry(self.frame1)
self.queryonto.pack(side=LEFT)

self.btnquery = Button(self.frame1, text='Query ontology')
     self.btnquery['command'] = self.makequery
     self.btnquery.pack(side=LEFT)

def makequery(self):
    self.ontology = World()
    self.onto = self.ontology.get_ontology('file://file.owl').load()
    self.baseiri = self.onto.base_iri
    self.graph = self.ontology.as_rdflib_graph()

    self.request = """PREFIX ont: <{}> 
                               SELECT ?class  
                               WHERE {  
                               ont:{} a ?class . 
                               }""".format(self.baseiri, self.queryonto)
    self.results = list(self.graph.query(self.request))
    print(self.results)

I'm almost sure that my use of .format is wrong. So, I ask: how to use the variables I created in this query? And, if I can do this with string manipulation, how is the right way to do it in this case?

Daniel
  • 27
  • 5

1 Answers1

0

I use these Python functions:

def createConcat(self, data, separator = ";;;"):
    """ Creates concat string. """
    return "(group_concat(distinct ?"+data+";separator='"+separator+"') as ?"+data+"_s)" 

def createSparqlQuery(self, data, separator = ";;;", key = "root", offset = 100):
    """Generates SPARQL query from input file."""
    query = []
    orderby = []
    select = "SELECT DISTINCT"
    #from_each_subpage
    for prop in data['select']:
        if prop.endswith("_s"):
            select +=" "+ self.createConcat(prop.split("_")[0])
        else:
            v = "?"+ prop.replace('_X','')
            select += " "+ v
            orderby.append(v)
    where = " WHERE { "
    closing = 1
    query.append(select)
    query.append(where)
    try:
        service = "SERVICE "+data['service'] + " {"
        query.append(service)
        closing += 1
    except:
        pass
    query.append('\n'.join(data[key]))
    while closing > 0:
        query.append('}')
        closing -= 1
    o = " ORDER BY " + ' '.join(orderby)
    query.append(o)
    try:
        limit = data['limit']
        l = " LIMIT %s" % limit
        query.append(l)
    except:
        pass

    complete_query = '\n'.join(query)
    print complete_query
    return complete_query

So really a bit of string manipulation with " distinct?" + data + ";", l = " LIMIT %s" % limit substitution, appending each string to a list and then joining the list to create the query with: complete_query = '\n'.join(query)

UPDATE:

To answer OP request more clearly:

query_parts = []
baseiri = "PREFIX ont: <%s>" % self.baseiri
select_where = "SELECT ?class WHERE {"
queryonto = "ont: %s a ?class ." % self.queryonto
closing = "}"
query_parts.append(baseiri)
query_parts.append(select_where)
query_parts.append(queryonto)
query_parts.append(closing)
self.request = "\n".join(query_parts)

Also make sure that self.queryonto has a string representation.

andrea-f
  • 1,045
  • 9
  • 23
  • Sorry, but I'm new at python, so I don't really understand how those functions can help solve my problem... Could you explain? I just want to know how can I use informations given by the user (using Entry) in a SPARQL query. – Daniel Nov 27 '18 at 16:13
  • self.query_parts = [] self.prefix = "PREFIX ont: <%s>" % self.baseiri self.select_where = "SELECT ?class WHERE {" self.term = "ont: %s a ?class ." % str(self.queryonto) self.closing = "}" self.query_parts.append(self.prefix) self.query_parts.append(self.select_where) self.query_parts.append(self.term) self.query_parts.append(self.closing) self.request = "\n".join(self.query_parts) self.results = list(self.graph.query(self.request)) print(self.results) – Daniel Nov 27 '18 at 22:01
  • I just figured it out! Your code worked. Thank you! The problem was that I wasn't converting self.queryonto to string properly. When I used str(self.queryonto.get()) it finally worked. – Daniel Nov 27 '18 at 23:22