Bridge619

Bridge619

Bridge619

命定的局限尽可永在,不屈的挑战却不可须臾或缺!

101 文章数
11 评论数
来首音乐
光阴似箭
今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

Python查询Jena的电影知识图谱

Bridge619
2022-10-18 / 0 评论 / 557 阅读 / 1 点赞

1.使用数据库管理工具Navicat连接kg_demo_movie数据库,将数据转化到本地的数据库中

2. D2RQ:关系数据库到RDF

2.1 第一步:生成mapping文件

进入D2RQ​目录,运行下面的命令根据mysql数据库生成的默认mapping文件(当前文件夹下):

 ./generate-mapping -o movie_mapping.ttl "jdbc:mysql://localhost/kg_demo_movie?useSSL=false&useUnicode=true&characterEncodeing=utf8"

参数解读:-o指定输出文件路径及名称,jdbc:mysql://localhost/kg_demo_movie 指定我们要映射的数据库,useSSL=false 不使用安全访问协议,useUnicode=true 使用Unicode编码,characterEncodeing=utf8 编码方式为utf8。

image-20221017192149547

2.2 D2RQ第二步:修改mapping文件

将mapping文件中的数据列名 对应到 我们设计的本体文件中。修改规则如下

  • 为了表达简练,给本体的IRI设置一个前缀:@prefix : <http://www.kgdemo.com#> .
  • 删除开头和正文中带有 vocab 的部分。
  • 把默认的映射词汇改为本体.owl中的词汇。

image-20221017222617938

2.3 D2RQ第三步:根据修改后的mapping文件生成RDF

进入D2RQ​目录,运行下面的命令根据修改后的mapping文件生成demo_movie.ttl文件(当前文件夹下):

./dump-rdf -f TURTLE -o demo_movie.ttl ./movie_mapping.ttl

image-20221017195312565

3.Apache Jena中形成知识图谱的物理存储

3.1 装载 RDF 数据,将 demo_movie.ttl 文件加载到 TDB 中

进入apache-jena-3.12.0/bin目录,运行下面的命令将demo_movie.ttl加载到TDB文件中:

./tdbloader --loc="/home/kg/kg_practice/exp5.2/apache-jena-fuseki-3.12.0/tdb" /home/kg/kg_practice/exp5.1/d2rq-0.8.1/demo_movie.ttl

参数说明:–loc 指定 tdb的存储位置,第二个参数/home/kg/kg_practice/exp5.1/d2rq-0.8.1/demo_movie.ttl为通过d2rq生成的ttl文件。

image-20221017201525237

3.2 Fuseki 服务的开启

  • 运行./fuseki-server,程序会在当前目录下自动创建 run 文件夹,在 run 文件夹下的 configuration 内创建名为 fuseki_conf.ttl 的文本文件。

image-20221017202711210

  • 简单的查询以验证是否成功

4. Python实现对Jena的电影知识查询

4.1 Inquire1

  • 查询描述: 警察故事4之简单任务这部电影有哪些演员参演

  • 查询代码及语句:

    from SPARQLWrapper import SPARQLWrapper, JSON
    
    sparql = SPARQLWrapper("http://localhost:3030/kg_movie_20205441/sparql")
    # 警察故事4之简单任务这部电影有哪些演员参演
    sparql.setQuery("""
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX : <http://www.kgdemo.com#>
    
        SELECT ?m WHERE {
            ?s rdf:type :Movie.
            ?s :movieTitle '警察故事4之简单任务'.
            ?a :hasActedIn ?s.
            ?a :personName ?m
    }
    """)
    
    sparql.setReturnFormat(JSON)
    #convert是为了将<class 'SPARQLWrapper.Wrapper.QueryResult'>转换为字典
    results = sparql.query().convert()
    
    for result in results["results"]["bindings"]:
        print(result['m']['value'])
    
  • 查询结果:

    image-20221017220814480

4.2 Inquire2

  • 查询描述: 出生于中国香港的演员

  • 查询代码及语句:

    from SPARQLWrapper import SPARQLWrapper, JSON
    
    sparql = SPARQLWrapper("http://localhost:3030/kg_movie_20205441/sparql")
    # 出生于中国香港的演员
    sparql.setQuery("""
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX : <http://www.kgdemo.com#>
    
        SELECT ?name
        WHERE {
            ?s rdf:type :Person.
    
            ?s :personName ?name.
    
            ?s :personBirthPlace ?p.
    
      FILTER( ?p='Hong Kong' )
    }
    """)
    
    sparql.setReturnFormat(JSON)
    #convert是为了将<class 'SPARQLWrapper.Wrapper.QueryResult'>转换为字典
    results = sparql.query().convert()
    # print(results)
    for result in results["results"]["bindings"]:
        print("name:%s"%result["name"]["value"])
    
    
  • 查询结果:

4.3 Inquire3

  • 查询描述: 成龙和吴辰君共同参演的电影

  • 查询代码及语句:

    from SPARQLWrapper import SPARQLWrapper, JSON
    
    sparql = SPARQLWrapper("http://localhost:3030/kg_movie_20205441/sparql")
    # 成龙和吴辰君共同参演的电影
    sparql.setQuery("""
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX : <http://www.kgdemo.com#>
    
        SELECT distinct ?n WHERE {
            ?s1 rdf:type :Person.
            ?s2 rdf:type :Person.
            ?s1 :personName '成龙'.
            ?s2 :personName '吴辰君'.
            ?s1 :hasActedIn ?m.
            ?s2 :hasActedIn ?m.
            ?m :movieTitle ?n
    }
    """)
    
    sparql.setReturnFormat(JSON)
    #convert是为了将<class 'SPARQLWrapper.Wrapper.QueryResult'>转换为字典
    results = sparql.query().convert()
    #print(results)
    for result in results["results"]["bindings"]:
        print("movie:%s"%result["n"]["value"])
    
    
  • 查询结果:

4.4 Inquire4

  • 查询描述: 以演员出演的电影数目排序

  • 查询代码及语句:

    from SPARQLWrapper import SPARQLWrapper, JSON
    
    sparql = SPARQLWrapper("http://localhost:3030/kg_movie_20205441/sparql")
    # 以演员出演的电影数目排序
    sparql.setQuery("""
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX : <http://www.kgdemo.com#>
    
        SELECT (?n as ?演员) (count(?t) as ?出演电影数目)
        WHERE { 
            ?x :personName ?n.
            ?x :hasActedIn ?t.
        }
        GROUP BY ?n
        ORDER BY DESC(?出演电影数目)
        LIMIT 4
    """)
    
    sparql.setReturnFormat(JSON)
    #convert是为了将<class 'SPARQLWrapper.Wrapper.QueryResult'>转换为字典
    results = sparql.query().convert()
    
    for result in results["results"]["bindings"]:
        print("演员:%s"%result["演员"]["value"])
        print("出演电影数目:%s" % result["出演电影数目"]["value"])
    
    
    
  • 查询结果:

4.5 Inquire5

  • 查询描述: 唐国强出演过哪些类型的电影

  • 查询代码及语句:

    from SPARQLWrapper import SPARQLWrapper, JSON
    
    sparql = SPARQLWrapper("http://localhost:3030/kg_movie_20205441/sparql")
    # 唐国强出演过哪些类型的电影
    sparql.setQuery("""
        PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX : <http://www.kgdemo.com#>
    
        SELECT ?x
        WHERE {
            ?s rdf:type :Person.
            ?s :personName "唐国强".
            ?s :hasActedIn ?m.
            ?m :hasGenre ?g.
            ?g :genreName ?x
    }
    
    """)
    
    sparql.setReturnFormat(JSON)
    #convert是为了将<class 'SPARQLWrapper.Wrapper.QueryResult'>转换为字典
    results = sparql.query().convert()
    
    for result in results["results"]["bindings"]:
        print("Genre:%s"%result["x"]["value"])
    
    
    
  • 查询结果:

    image-20221017234612175

文章不错,扫码支持一下吧~
上一篇 下一篇
评论