python使用rdflib创建rdf,在jena fuseki上执行SPARQL查询

  1. 建立并启动jena fuseki服务
    参考:https://www.cnblogs.com/bincoding/p/11223372.html
  2. 使用rdflib创建rdf文件
import rdflib

def create_rdf():
    g = rdflib.Graph()
    # 实体
    pinganfu = rdflib.URIRef('http://www.example.org/pinganfu')
    yiwaixian = rdflib.URIRef('http://www.example.org/yiwaixian')
    # 关系
    price = rdflib.URIRef('http://www.example.org/price')
    product_from = rdflib.URIRef('http://www.example.org/from')
    # 属性
    price_100 = rdflib.URIRef('http://www.example.org/100')
    price_200 = rdflib.URIRef('http://www.example.org/200')
    from_paic = rdflib.URIRef('http://www.example.org/paic')
    from_pajiankang = rdflib.URIRef('http://www.example.org/pingan jiankangxian')
    g.add((pinganfu, price, price_100))
    g.add((yiwaixian, price, price_200))
    g.add((pinganfu, product_from, from_paic))
    g.add((yiwaixian, product_from, from_pajiankang))

    g.serialize("graph.rdf")

if __name__ == "__main__":
    create_rdf()

  1. jena fuseki导入生成的rdf文件,需要utf-8格式

  2. 执行查询

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

select *
where {
  ?product <http://www.example.org/price> ?price .
}

where里的三个值分别表示主谓宾
其中?product ?price表示需要展示的字段,http://www.example.org/price相当于sql中的where条件,查询谓语等于http://www.example.org/price的所有结果

查询结果

jena数据格式

参考:
https://blog.csdn.net/Oeljeklaus/article/details/65436866
https://www.w3.org/TR/sparql11-query/#WritingSimpleQueries

posted @ 2019-07-22 00:52  致林  阅读(2663)  评论(1编辑  收藏  举报