N:::만지작 거리기

N_19. SPARQLWrapper로 SPARQL Endpoint 사용하기

joyHong 2021. 9. 10. 00:39
SPARQL Endpoint를 제공하는 곳이 있으면 SPARQL 을 통해 원하는 데이터를 웹상에서 가져올 수 있다. 이전 내용(https://joyhong.tistory.com/144) 에서는 Fuseki를 활용하여 간단하게 SPARQL Endpoint를 구성해 보았는데 로컬에 SPARQL Endpoint를 구성하고 여기에 질의를 해보는 내용을 기술하였다. 사용하는 라이브러리는 SPARQLWrapper와 RDFLib 이다. 04.QueryToSPARQLEndpoint
SPARQL Endpoint에 질의하기

SPARQL Endpoint를 제공하면 웹상에서 자유롭게 질의를 하여 결과를 받아 올 수 있다.

이 전에 Fuseki를 활용하여 간단하게 SPARQL Endpoint를 구축하였는데, 이를 활용하여 테스트를 진행한다.

다양한 형태의 SPARQL을 구성하고 여러가지 포맷으로 결과를 받아온다.

작성자 : 허홍수
e-mail : su4620@gmail.com
blog : http://joyhong.tistory.com

SPARQL 실행

기본적으로 SPARQL 실행 후 결과 리턴 포맷은 XML이기 때문에 별다른 설정을 하지 않으면 XML 포맷으로 결과값이 넘어온다.
아래 예시들에서는 디폴트인 XML을 그대로 사용하고 있다.

SELECT

In [1]:
from SPARQLWrapper import SPARQLWrapper

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT *
    WHERE { 
        ?s ?p ?o 
    } LIMIT 10
""")

results = sparql.query().convert()
# convert()가 자동으로 결과를 변환시킨다. 리턴이 xml이기 때문에 xml.dom.minidom 형태로 바꾸어준다.
print(results.toxml())
<?xml version="1.0" ?><sparql xmlns="http://www.w3.org/2005/sparql-results#">
  <head>
    <variable name="s"/>
    <variable name="p"/>
    <variable name="o"/>
  </head>
  <results>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</uri>
      </binding>
      <binding name="o">
        <uri>http://schema.org/Hospital</uri>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://www.w3.org/2000/01/rdf-schema#label</uri>
      </binding>
      <binding name="o">
        <literal>가톨릭대학교인천성모병원</literal>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://joyhong.tistory.com/ontology/openedDate</uri>
      </binding>
      <binding name="o">
        <literal datatype="http://www.w3.org/2001/XMLSchema#date">1981-08-06</literal>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://joyhong.tistory.com/ontology/totalNumberOfDoctor</uri>
      </binding>
      <binding name="o">
        <literal>324</literal>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://purl.org/dc/terms/identifier</uri>
      </binding>
      <binding name="o">
        <literal>JDQ4MTYyMiM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQ3OSQyNjE4MzIjNDEjJDEjJDgjJDgz</literal>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://purl.org/dc/terms/subject</uri>
      </binding>
      <binding name="o">
        <uri>http://joyhong.tistory.com/resource/cat_1</uri>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://purl.org/dc/terms/subject</uri>
      </binding>
      <binding name="o">
        <uri>http://joyhong.tistory.com/resource/rg_220000</uri>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://purl.org/dc/terms/subject</uri>
      </binding>
      <binding name="o">
        <uri>http://joyhong.tistory.com/resource/rg_220003</uri>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://schema.org/geo</uri>
      </binding>
      <binding name="o">
        <uri>http://joyhong.tistory.com/resource/geo_h1</uri>
      </binding>
    </result>
    <result>
      <binding name="s">
        <uri>http://joyhong.tistory.com/resource/h_1</uri>
      </binding>
      <binding name="p">
        <uri>http://schema.org/telephone</uri>
      </binding>
      <binding name="o">
        <literal>032-1544-9004</literal>
      </binding>
    </result>
  </results>
</sparql>

ASK

In [2]:
from SPARQLWrapper import SPARQLWrapper

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    ASK WHERE {
        <http://joyhong.tistory.com/resource/h_1> ?p ?label 
    }
""")

results = sparql.query().convert()
print(bool(results))
True

CONSTRUCT

CONSTRUCT와 DESCRIBE RDF/XML 구문으로 리턴된다.

In [3]:
from SPARQLWrapper import SPARQLWrapper
from rdflib import Graph

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    CONSTRUCT {
        ?s ?p ?o.
    } WHERE {
        ?s ?p ?o . 
        FILTER(?s=<http://joyhong.tistory.com/resource/h_1>)
    }
""")

results = sparql.query().convert()
# CONSTRUCT 구문은 RDF/XML 형태로 리턴이 되기 때문에 convert()가 자동으로 Graph 인스턴스로 변환시킨다.
# 따라서 results는 타입이 Graph 임으로 바로 serialize() 를 통해 직렬화가 가능하다.

print(results.serialize().decode('utf-8'))
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:dcterms="http://purl.org/dc/terms/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ont="http://joyhong.tistory.com/ontology/"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:schema="http://schema.org/"
>
  <rdf:Description rdf:about="http://joyhong.tistory.com/resource/h_1">
    <schema:telephone>032-1544-9004</schema:telephone>
    <rdf:type rdf:resource="http://schema.org/Hospital"/>
    <dcterms:identifier>JDQ4MTYyMiM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQ3OSQyNjE4MzIjNDEjJDEjJDgjJDgz</dcterms:identifier>
    <foaf:homepage rdf:resource="http://www.cmcism.or.kr/"/>
    <ont:totalNumberOfDoctor>324</ont:totalNumberOfDoctor>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/cat_1"/>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/rg_220003"/>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/rg_220000"/>
    <schema:geo rdf:resource="http://joyhong.tistory.com/resource/geo_h1"/>
    <ont:openedDate rdf:datatype="http://www.w3.org/2001/XMLSchema#date">1981-08-06</ont:openedDate>
    <rdfs:label>가톨릭대학교인천성모병원</rdfs:label>
    <foaf:page rdf:resource="http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTYyMiM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQ3OSQyNjE4MzIjNDEjJDEjJDgjJDgz"/>
  </rdf:Description>
</rdf:RDF>

DESCRIBE

In [4]:
from SPARQLWrapper import SPARQLWrapper
from rdflib import Graph

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    DESCRIBE <http://joyhong.tistory.com/resource/h_16>
""")

results = sparql.query().convert()
# DESCRIBE 구문은 CONSTRUCT와 마찬가지로 RDF/XML 형태로 리턴이 되기 때문에 convert()가 자동으로 Graph 인스턴스로 변환시킨다.
# 따라서 results는 타입이 Graph 임으로 바로 serialize() 를 통해 직렬화가 가능하다.

print(results.serialize().decode('utf-8'))
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:dcterms="http://purl.org/dc/terms/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ont="http://joyhong.tistory.com/ontology/"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:schema="http://schema.org/"
>
  <rdf:Description rdf:about="http://joyhong.tistory.com/resource/h_16">
    <schema:geo rdf:resource="http://joyhong.tistory.com/resource/geo_h16"/>
    <dcterms:identifier>JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz</dcterms:identifier>
    <ont:totalNumberOfDoctor>1399</ont:totalNumberOfDoctor>
    <ont:openedDate rdf:datatype="http://www.w3.org/2001/XMLSchema#date">1994-06-13</ont:openedDate>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/cat_1"/>
    <rdfs:label>삼성서울병원</rdfs:label>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/rg_110000"/>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/rg_110001"/>
    <foaf:homepage rdf:resource="http://www.samsunghospital.com"/>
    <rdf:type rdf:resource="http://schema.org/Hospital"/>
    <foaf:page rdf:resource="http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz"/>
    <schema:telephone>02-3410-2114</schema:telephone>
  </rdf:Description>
</rdf:RDF>

Graph 리턴인 경우 여러가지 직렬화

CONSTRUCT와 DESCRIBE 구문은 RDF/XML 형태로 리턴이 되고, convert()를 통해 Graph의 인스턴스로 변환되기 때문에 여러가지 직렬화를 사용할 수 있다.

RDF/XML

In [5]:
from SPARQLWrapper import SPARQLWrapper
from rdflib import Graph

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    DESCRIBE <http://joyhong.tistory.com/resource/h_16>
""")

results = sparql.query().convert()

print('XML(디폴트) 형태로 출력')
print('='*100)
print(results.serialize().decode('utf-8'))
XML(디폴트) 형태로 출력
====================================================================================================
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
   xmlns:dcterms="http://purl.org/dc/terms/"
   xmlns:foaf="http://xmlns.com/foaf/0.1/"
   xmlns:ont="http://joyhong.tistory.com/ontology/"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
   xmlns:schema="http://schema.org/"
>
  <rdf:Description rdf:about="http://joyhong.tistory.com/resource/h_16">
    <dcterms:identifier>JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz</dcterms:identifier>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/cat_1"/>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/rg_110001"/>
    <ont:openedDate rdf:datatype="http://www.w3.org/2001/XMLSchema#date">1994-06-13</ont:openedDate>
    <dcterms:subject rdf:resource="http://joyhong.tistory.com/resource/rg_110000"/>
    <rdf:type rdf:resource="http://schema.org/Hospital"/>
    <schema:geo rdf:resource="http://joyhong.tistory.com/resource/geo_h16"/>
    <foaf:page rdf:resource="http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz"/>
    <foaf:homepage rdf:resource="http://www.samsunghospital.com"/>
    <rdfs:label>삼성서울병원</rdfs:label>
    <ont:totalNumberOfDoctor>1399</ont:totalNumberOfDoctor>
    <schema:telephone>02-3410-2114</schema:telephone>
  </rdf:Description>
</rdf:RDF>

Turtle

In [6]:
print('TURTLE 형태로 출력')
print('='*100)
print(results.serialize(format='turtle').decode('utf-8'))
TURTLE 형태로 출력
====================================================================================================
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix ont: <http://joyhong.tistory.com/ontology/> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix rs: <http://joyhong.tistory.com/resource/> .
@prefix schema: <http://schema.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

rs:h_16 a schema:Hospital ;
    rdfs:label "삼성서울병원" ;
    ont:openedDate "1994-06-13"^^xsd:date ;
    ont:totalNumberOfDoctor "1399" ;
    dcterms:identifier "JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz" ;
    dcterms:subject rs:cat_1,
        rs:rg_110000,
        rs:rg_110001 ;
    schema:geo rs:geo_h16 ;
    schema:telephone "02-3410-2114" ;
    foaf:homepage <http://www.samsunghospital.com> ;
    foaf:page <http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz> .


JSON-LD

In [7]:
print('JSON-LD 형태로 출력')
print('='*100)
print(results.serialize(format='json-ld').decode('utf-8'))
JSON-LD 형태로 출력
====================================================================================================
[
  {
    "@id": "http://joyhong.tistory.com/resource/h_16",
    "@type": [
      "http://schema.org/Hospital"
    ],
    "http://joyhong.tistory.com/ontology/openedDate": [
      {
        "@type": "http://www.w3.org/2001/XMLSchema#date",
        "@value": "1994-06-13"
      }
    ],
    "http://joyhong.tistory.com/ontology/totalNumberOfDoctor": [
      {
        "@value": "1399"
      }
    ],
    "http://purl.org/dc/terms/identifier": [
      {
        "@value": "JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz"
      }
    ],
    "http://purl.org/dc/terms/subject": [
      {
        "@id": "http://joyhong.tistory.com/resource/rg_110000"
      },
      {
        "@id": "http://joyhong.tistory.com/resource/rg_110001"
      },
      {
        "@id": "http://joyhong.tistory.com/resource/cat_1"
      }
    ],
    "http://schema.org/geo": [
      {
        "@id": "http://joyhong.tistory.com/resource/geo_h16"
      }
    ],
    "http://schema.org/telephone": [
      {
        "@value": "02-3410-2114"
      }
    ],
    "http://www.w3.org/2000/01/rdf-schema#label": [
      {
        "@value": "삼성서울병원"
      }
    ],
    "http://xmlns.com/foaf/0.1/homepage": [
      {
        "@id": "http://www.samsunghospital.com"
      }
    ],
    "http://xmlns.com/foaf/0.1/page": [
      {
        "@id": "http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz"
      }
    ]
  }
]

N-Triples

In [8]:
print('N-Triples 형태로 출력')
print('='*100)
print(results.serialize(format='nt').decode('utf-8'))
N-Triples 형태로 출력
====================================================================================================
<http://joyhong.tistory.com/resource/h_16> <http://purl.org/dc/terms/identifier> "JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz" .
<http://joyhong.tistory.com/resource/h_16> <http://purl.org/dc/terms/subject> <http://joyhong.tistory.com/resource/cat_1> .
<http://joyhong.tistory.com/resource/h_16> <http://purl.org/dc/terms/subject> <http://joyhong.tistory.com/resource/rg_110001> .
<http://joyhong.tistory.com/resource/h_16> <http://joyhong.tistory.com/ontology/openedDate> "1994-06-13"^^<http://www.w3.org/2001/XMLSchema#date> .
<http://joyhong.tistory.com/resource/h_16> <http://purl.org/dc/terms/subject> <http://joyhong.tistory.com/resource/rg_110000> .
<http://joyhong.tistory.com/resource/h_16> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Hospital> .
<http://joyhong.tistory.com/resource/h_16> <http://schema.org/geo> <http://joyhong.tistory.com/resource/geo_h16> .
<http://joyhong.tistory.com/resource/h_16> <http://xmlns.com/foaf/0.1/page> <http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz> .
<http://joyhong.tistory.com/resource/h_16> <http://xmlns.com/foaf/0.1/homepage> <http://www.samsunghospital.com> .
<http://joyhong.tistory.com/resource/h_16> <http://www.w3.org/2000/01/rdf-schema#label> "\uC0BC\uC131\uC11C\uC6B8\uBCD1\uC6D0" .
<http://joyhong.tistory.com/resource/h_16> <http://joyhong.tistory.com/ontology/totalNumberOfDoctor> "1399" .
<http://joyhong.tistory.com/resource/h_16> <http://schema.org/telephone> "02-3410-2114" .


반환 포맷 설정

SELECT 구문

중요! SELECT와 ASK 구문은 XML, JSON, CSV/TSV 형태로만 결과를 반환한다.

JSON 형태로 결과 반환

In [9]:
from SPARQLWrapper import SPARQLWrapper, JSON

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT *
    WHERE { 
        ?s ?p ?o .
    } LIMIT 10
""")

sparql.setReturnFormat(JSON)
results = sparql.query().convert()
# JSON 형태로 결과를 받으면 convert()가 자동으로 dictionary 변환하기 때문에 아래와 같이 결과를 확인할 수 있다.

for result in results["results"]["bindings"]:
    print(result["p"]["value"], "\t", result["o"]["value"])
http://www.w3.org/1999/02/22-rdf-syntax-ns#type 	 http://schema.org/Hospital
http://www.w3.org/2000/01/rdf-schema#label 	 가톨릭대학교인천성모병원
http://joyhong.tistory.com/ontology/openedDate 	 1981-08-06
http://joyhong.tistory.com/ontology/totalNumberOfDoctor 	 324
http://purl.org/dc/terms/identifier 	 JDQ4MTYyMiM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQ3OSQyNjE4MzIjNDEjJDEjJDgjJDgz
http://purl.org/dc/terms/subject 	 http://joyhong.tistory.com/resource/cat_1
http://purl.org/dc/terms/subject 	 http://joyhong.tistory.com/resource/rg_220000
http://purl.org/dc/terms/subject 	 http://joyhong.tistory.com/resource/rg_220003
http://schema.org/geo 	 http://joyhong.tistory.com/resource/geo_h1
http://schema.org/telephone 	 032-1544-9004

CSV 형태로 결과 반환

In [10]:
from SPARQLWrapper import SPARQLWrapper, CSV

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT *
    WHERE { 
        ?s ?p ?o .
    } LIMIT 10
""")

sparql.setReturnFormat(CSV)
results = sparql.query().convert()
# CSV 형태로 결과를 받으면 convert()가 자동으로 string으로 변환하기 때문에 아래와 같이 결과를 확인할 수 있다.
print(results.decode('utf-8'))
s,p,o
http://joyhong.tistory.com/resource/h_1,http://www.w3.org/1999/02/22-rdf-syntax-ns#type,http://schema.org/Hospital
http://joyhong.tistory.com/resource/h_1,http://www.w3.org/2000/01/rdf-schema#label,가톨릭대학교인천성모병원
http://joyhong.tistory.com/resource/h_1,http://joyhong.tistory.com/ontology/openedDate,1981-08-06
http://joyhong.tistory.com/resource/h_1,http://joyhong.tistory.com/ontology/totalNumberOfDoctor,324
http://joyhong.tistory.com/resource/h_1,http://purl.org/dc/terms/identifier,JDQ4MTYyMiM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQ3OSQyNjE4MzIjNDEjJDEjJDgjJDgz
http://joyhong.tistory.com/resource/h_1,http://purl.org/dc/terms/subject,http://joyhong.tistory.com/resource/cat_1
http://joyhong.tistory.com/resource/h_1,http://purl.org/dc/terms/subject,http://joyhong.tistory.com/resource/rg_220000
http://joyhong.tistory.com/resource/h_1,http://purl.org/dc/terms/subject,http://joyhong.tistory.com/resource/rg_220003
http://joyhong.tistory.com/resource/h_1,http://schema.org/geo,http://joyhong.tistory.com/resource/geo_h1
http://joyhong.tistory.com/resource/h_1,http://schema.org/telephone,032-1544-9004

DESCRIBE 구문

중요! DESCRIBE와 CONSTRUCT 구문은 RDF/XML 혹은 그와 동일한 그래프 형태로만 결과를 반환한다.

Turtle 형태로 결과 반환

In [11]:
from SPARQLWrapper import SPARQLWrapper, TURTLE
from rdflib import Graph

sparql = SPARQLWrapper("http://localhost:3030/publicdata/query")

sparql.setQuery("""
    DESCRIBE <http://joyhong.tistory.com/resource/h_16>
""")

sparql.setReturnFormat(TURTLE)
sparql.setOnlyConneg(True)
results = sparql.query().convert()
print('='*100)
print('string 형태의 결과')
print('='*100)
print(results.decode('utf-8'))
print('='*100)
print('turtle 직렬화 결과')
print('='*100)
# results는 string 으로 변환된 상태 이기 때문에 이를 Graph에 담아야 한다.
g = Graph()
g.parse(data=results, format="turtle")
print(g.serialize(format='turtle').decode('utf-8'))
====================================================================================================
string 형태의 결과
====================================================================================================
@prefix schema: <http://schema.org/> .
@prefix rs:    <http://joyhong.tistory.com/resource/> .
@prefix ont:   <http://joyhong.tistory.com/ontology/> .
@prefix xsd:   <http://www.w3.org/2001/XMLSchema#> .
@prefix skos:  <http://www.w3.org/2004/02/skos/core#> .
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix rdfs:  <http://www.w3.org/2000/01/rdf-schema#> .
@prefix foaf:  <http://xmlns.com/foaf/0.1/> .

rs:h_16  a                       schema:Hospital ;
        rdfs:label               "삼성서울병원" ;
        ont:openedDate           "1994-06-13"^^xsd:date ;
        ont:totalNumberOfDoctor  "1399" ;
        dcterms:identifier       "JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz" ;
        dcterms:subject          rs:rg_110000 , rs:cat_1 , rs:rg_110001 ;
        schema:geo               rs:geo_h16 ;
        schema:telephone         "02-3410-2114" ;
        foaf:homepage            <http://www.samsunghospital.com> ;
        foaf:page                <http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz> .

====================================================================================================
turtle 직렬화 결과
====================================================================================================
@prefix dcterms: <http://purl.org/dc/terms/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix ont: <http://joyhong.tistory.com/ontology/> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix rs: <http://joyhong.tistory.com/resource/> .
@prefix schema: <http://schema.org/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

rs:h_16 a schema:Hospital ;
    rdfs:label "삼성서울병원" ;
    ont:openedDate "1994-06-13"^^xsd:date ;
    ont:totalNumberOfDoctor "1399" ;
    dcterms:identifier "JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz" ;
    dcterms:subject rs:cat_1,
        rs:rg_110000,
        rs:rg_110001 ;
    schema:geo rs:geo_h16 ;
    schema:telephone "02-3410-2114" ;
    foaf:homepage <http://www.samsunghospital.com> ;
    foaf:page <http://www.hira.or.kr/re/diag/getDiagAmtInfo.do?ykiho=JDQ4MTg4MSM1MSMkMSMkMCMkODkkMzgxMzUxIzExIyQxIyQzIyQxMyQzNjEwMDIjODEjJDEjJDIjJDgz> .


Finish !!