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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM