대메뉴로 바로가기 검색창 바로가기 메인 컨텐츠 바로가기 풋터 바로가기

SPARQL 예제

1. 소개
이 문서는 강원관광의 링크드 오픈데이터 서비스(http://lod.gangwon.go.kr)에서 제공하는 SPARQL Endpoint를 설명합니다.
2. SPARQL Endpoint
강원관광의 SPARQL Endpoint 주소는 <http://lod.gangwon.go.kr/sparql>이며, SPARQL1.1을 지원합니다. REST URL를 통해서 접근할 수 있으며, 텍스트 형식의 SPARQL편집기와 GUI형식의 SPARQL Builder를 통해서 SPARQL를 작성할 수 있습니다.
  • 2.1 SPARQL API

    SPARQL은 RDF 데이터베이스와 상호작용하기 위한 웹표준 질의언어입니다. SPARQL은 표준화된 질의언어와 질의응답형식(query response formats), HTTP이용한 SPARQL Endpoint와의 상호작용 프로토콜에 대한 명세서로 구성됩니다.
    강원도청에 의해서 링크드 데이터(Linked Data)로 발행된 데이터셋은 SPARQL Endpoint를 통해서 접근할 수 있으며, SPARQL1.1질의언어<http://www.w3.org/TR/sparql11-query/>와 SAPRQL1.1 HTTP 프로토콜<http://www.w3.org/TR/sparql11-protocol/>을 지원합니다.

    1. 2.1.1 API파라미터
      파마미터, 필요여부, 설명
      파라미터 필요여부 설명
      query 필수 URL인코딩된 질의언어(SELECT, ASK, DESCRIBE, CONSTRUCT)
      format 선택 질의 결과에 대한 포맷(SPARQL1.1<http://www.w3.org/TR/sparql11-protocol/>)
    1. 2.1.2 HTTP 요청메소드(Request Methods)

      SPARQL Endpoint에 전송되는 SPARQL 질의는 GET과 POST방식을 지원합니다. 일반적으로 클라이언트는 GET방식을 통해서 질의하기를 권고합니다.

    1. 2.1.3 응답형식(Response Formats)

      SPARQL Endpoint는 SPARQL질의에 대한 응답형식으로 다양한 형태를 지원합니다. 여기서 클라이언트는 다음과 같이 지원되는 포맷에 따라 SPARQL Endpoint에 요청하시기 바랍니다.
      ◼ SELECT와 ASK는 application/sparql-results+xml 형식으로 반환됨
      ◼ DESCRIBE와 CONSTRUCT는 RDF graph이므로 application/rdf+xml형식으로 반환됨
      응답형식을 선택은 HTTP Accept 헤더를 이용하며, 아래와 같이 다양한 형식의 SPARQL질의와 Accept, 반환 파라미터를 참조하시기 바랍니다

      응답형식 설명
      질의형식 Accept헤더 반환포맷 명세서
      ASK, SELECT application/sparql-results+xml xml SPARQL XML Results Format
      ASK, SELECT application/sparql-results+json json SPARQL XML JSON Format
      SELECT text/csv csv SPARQL CSV Results Format
      CONSTRUCT, DESCRIBE text/turtle ttl Turtle
      CONSTRUCT, DESCRIBE application/rdf+xml rdf RDF/XML
      CONSTRUCT, DESCRIBE application/rdf+json json RDF/JSON
    1. 2.1.4 응답 캐싱(Response Caching)

      SPARQL Endpoint는 요청에 대한 빠른 응답을 위해 필요시 동일한 질의에 대한 캐싱을 수행합니다. 캐시는 RDF 데이터베이스에 새로운 데이터가 추가/삭제되거나 필요에 의해 RDF데이터베이스를 재시작할 경우 캐시가 초기화될 수 있습니다.

  • 2.2 SPARQL 편집 및 실행

    SPARQL 편집기는 강원관광 링크드 데이터에 직접 질의할 수 있는 텍스트 형식의 질의 작성기입니다. SPARQL1.1<http://www.w3.org/TR/sparql11-query/>의 구문을 제공하며, 사용자가 다양한 질의를 작성하여 결과를 얻을 수 있습니다. 질의결과 포맷은 HTML, RDF/XML, N-Triples, Turtle, RDF/JSON, CSV 형식으로 받을 수 있으며, 어플리케이션 활용에 맞게형식을 선택하시면 됩니다.

  • 2.3 GUI기반 SPARQL 편집기

    GUI기반 SPARQL 편집기는 트리플 패턴(Subject, Predicate, Object)의 입력을 쉽게 할 수 있는 클래스와 속성 자동선택기능을 제공합니다. 사용자는 버튼을 클릭하여 새로운 트리플 패턴을 추가/작성할 수 있으며, OFFSET과 LIMIT를 설정한 후 버튼을 클릭하면 SPARQL 구문이 완성됩니다.

3. SPARQL 질의 예
  • 3.1 PREFIX 정의

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    PREFIX ns: <http://lod.culture.go.kr/ontology/>
    PREFIX pf: <http://www.saltlux.com/DARQ/property#>
    PREFIX schema: <https://schema.org/>
    PREFIX wgs: <http://www.w3.org/2003/01/geo/wgs84_pos#>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX gwo: <http://lod.gwd.go.kr/ontology/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    PREFIX kto: <http://data.visitkorea.or.kr/ontology/>
    PREFIX geo: <http://www.saltlux.com/geo/property#>
    PREFIX f: <http://www.saltlux.com/geo/functions#>
    PREFIX res: <http://lod.gwd.go.kr/resource/>
  • 3.2 강원관광 정보 중, 라벨에 "평창"인 포함된 리소스 조회 - FILTER

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    
    SELECT distinct(?s_uri as ?resourceUri) ?label ?locationUri ?locationName ?description ?categoryUri ?categoryName
    FROM <http://www.ontotext.com/disable-sameAs>
    {
    	?s_uri gwp:category ?categoryUri.
    	?categoryUri rdfs:label ?categoryName.
    	FILTER langMatches(lang(?categoryName), "KO")
    	?s_uri rdfs:label ?label.
    	FILTER regex(?label , '평창').
    	FILTER langMatches(lang(?label), "KO")
    	?s_uri ktop:location ?locationUri.
    	?locationUri rdfs:label ?locationName.
    	FILTER langMatches(lang(?locationName), "KO")
    	?s_uri dc:description ?description.
    	FILTER langMatches(lang(?description), "KO")
    } LIMIT 10
    
  • 3.3 특정 리소스에 포함된 이미지 오름차순 조회 - ORDER BY

    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    
    SELECT distinct ?image 
    {
      <http://lod.gwd.go.kr/resource/AM0040_T>  foaf:depiction ?image.
    } ORDER BY ASC(?image)
    
  • 3.4 강원관광 대분류 조회(관광스키마)

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    
    SELECT  ?categoryUri ?label
    WHERE
    { 
    	<http://lod.gwd.go.kr/resource/GangwonTourismScheme> skos:hasTopConcept ?categoryUri.
    	?categoryUri rdfs:label ?label.
    	FILTER langMatches(lang(?label), "KO").
    } ORDER BY ASC(?categoryUri)
    LIMIT   100
    
  • 3.5 강원관광 세부분류 조회 - 관광

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    
    SELECT ?category
    WHERE
      { 
        ?res gwp:category ?categoryUri.
        FILTER REGEX(STR(?categoryUri) ,'http://lod.gwd.go.kr/resource/CLASSIFICATION:A').
        ?categoryUri rdfs:label ?category.
        FILTER langMatches(lang(?category), "ko").
      } GROUP BY ?category
    LIMIT   100
    
  • 3.6 특정 리소스 세부 내용 조회 - BIND

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX wgs: <http://www.w3.org/2003/01/geo/wgs84_pos#>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX schema: <https://schema.org/>
    
    SELECT 
    ?lat ?lng
    ?label ?upperLocation ?detailLocation ?creator ?description ?upperCategory ?detailCategory   
    ?relationKeywords ?depiction  
    ?differentiation ?address ?tel ?homepage ?closedForTheDay ?showTime 
    ?entrancefee ?admissionfee ?parking ?parkingFee ?etcinfo ?tourguide ?tourtip
    ?disableFacility ?nearbyattractions ?recommendation
    { 
      BIND(<http://lod.gwd.go.kr/resource/AM0040_T> AS ?resourceUri).
      ?resourceUri  rdfs:label ?label 
      FILTER langMatches(lang(?label), "KO").
      ?resourceUri  wgs:lat ?lat . 
      ?resourceUri  wgs:long ?lng . 
    
      OPTIONAL {
        ?resourceUri  gwp:category ?categoryUri .
        ?categoryUri rdfs:label ?detailCategory 
        FILTER langMatches(lang(?detailCategory), "KO"). 
        ?categoryUri skos:broader ?upperUri .
        ?upperUri rdfs:label ?upperCategory
        FILTER langMatches(lang(?upperCategory), "KO").  
      }
      OPTIONAL {
        ?resourceUri  ktop:location ?locationUri .
        ?locationUri rdfs:label ?detailLocation.
        FILTER langMatches(lang(?detailLocation), "KO").
      }
      OPTIONAL {
        ?resourceUri  ktop:location ?locationUri . 
        ?locationUri skos:broader ?upperLocationUri .
        ?upperLocationUri rdfs:label ?upperLocation
        FILTER langMatches(lang(?upperLocation), "KO").
      }
      OPTIONAL {    			
        ?resourceUri  dc:creator ?creator
        FILTER langMatches(lang(?creator), "KO").
      }
      OPTIONAL {
        ?resourceUri  dc:description ?description
        FILTER langMatches(lang(?description), "KO").
      }
      OPTIONAL {
        ?resourceUri  foaf:thumbnail ?depiction.
      }
      OPTIONAL {
        ?resourceUri schema:keywords ?relationKeywords
        FILTER langMatches(lang(?relationKeywords), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:differentiation ?differentiation
        FILTER langMatches(lang(?differentiation), "KO").
      }
      OPTIONAL {
        ?resourceUri ktop:address ?address
        FILTER langMatches(lang(?address), "KO").
      }
      OPTIONAL {
        ?resourceUri ktop:tel ?tel.
      }
      OPTIONAL {
        ?resourceUri foaf:homepage ?homepage.
      }
      OPTIONAL {
        ?resourceUri ktop:closedForTheDay ?closedForTheDay
        FILTER langMatches(lang(?closedForTheDay), "KO").
      }
      OPTIONAL {
        ?resourceUri ktop:showTime ?showTime
        FILTER langMatches(lang(?showTime), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:entrancefee ?entrancefee
        FILTER langMatches(lang(?entrancefee), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:admissionfee ?admissionfee
        FILTER langMatches(lang(?admissionfee), "KO").
      }
      OPTIONAL {
        ?resourceUri ktop:parking ?parking
        FILTER langMatches(lang(?parking), "KO").
      }
      OPTIONAL {
        ?resourceUri ktop:parkingFee ?parkingFee
        FILTER langMatches(lang(?parkingFee), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:etcinfo ?etcinfo
        FILTER langMatches(lang(?etcinfo), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:tourguide ?tourguide
        FILTER langMatches(lang(?tourguide), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:tourtip ?tourtip
        FILTER langMatches(lang(?tourtip), "KO").
      }
      OPTIONAL {
        ?resourceUri ktop:disableFacility ?disableFacility
        FILTER langMatches(lang(?disableFacility), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:nearbyattractions ?nearbyattractions
        FILTER langMatches(lang(?nearbyattractions), "KO").
      }
      OPTIONAL {
        ?resourceUri gwp:recommendation ?recommendation
        FILTER langMatches(lang(?recommendation), "KO").
      }
    } 
    LIMIT 1
    
  • 3.7 특정 리소스 주변 5km내 강원관광 정보 조회 - geo함수

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    PREFIX wgs: <http://www.w3.org/2003/01/geo/wgs84_pos#>
    PREFIX geo: <http://www.saltlux.com/geo/property#>
    
    SELECT  ?nearLabel ?distance ?nearUri ?depiction  ?lat ?lng ?address
    WHERE 
    {
    	<http://lod.gwd.go.kr/resource/AM0040_T> wgs:lat ?lat1 ;
    							wgs:long ?lng1 . 
    	(?nearUri ?distance) geo:nearby(?lat1 ?lng1 "5000") .
    	?nearUri rdfs:label ?nearLabel.
    	FILTER contains (str(?nearUri), 'lod.gwd.go.kr').
    	FILTER langMatches(lang(?nearLabel), "KO").
    	?nearUri ktop:address ?address.
    	FILTER langMatches(lang(?address), "KO").
    	?nearUri foaf:thumbnail ?depiction.	
    	?nearUri wgs:lat ?lat .
    	?nearUri wgs:long ?lng .
    }
    ORDER BY asc(?distance)
    
  • 3.8 특정 리소스 주변 5km내 국립공원 정보 조회 - SERVICE

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    PREFIX wgs: <http://www.w3.org/2003/01/geo/wgs84_pos#>
    PREFIX geo: <http://www.saltlux.com/geo/property#>
    
    SELECT 
    ?nearUri ?nearLabel ?lat ?lng ?distance (sample(?image) as ?depiction) ?address
    WHERE
    {
      BIND(<http://lod.gwd.go.kr/resource/AM0040_T> as ?uri).
       ?uri wgs:lat ?lat1 ;
    			 wgs:long ?lng1 .
    
      SERVICE <http://data.visitkorea.or.kr/sparql/> {
    		(?nearUri ?distance) geo:nearby(?lat1 ?lng1 "5000") .
    		?nearUri rdfs:label ?nearLabel. 
    		FILTER contains (str(?nearUri), 'data.visitkorea.or.kr').
    		FILTER langMatches(lang(?nearLabel), "KO").
    		?nearUri ktop:address ?address.
    		FILTER langMatches(lang(?address), "KO").
    		?nearUri wgs:lat ?lat .
    		?nearUri wgs:long ?lng .
    		?nearUri foaf:depiction ?image .
    	}
    } 
    GROUP BY  ?nearUri ?nearLabel ?lat ?lng ?distance ?address
    ORDER BY asc(?distance)
    
  • 3.9 특정 리소스 주변 5km내 한국관광공사 정보 조회 - distance함수

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    PREFIX wgs: <http://www.w3.org/2003/01/geo/wgs84_pos#>
    PREFIX f: <http://www.saltlux.com/geo/functions#>
    
    SELECT 
    ?nearUri ?nearLabel ?lat ?lng ?distance (sample(?image) as ?depiction) ?address
    WHERE
    {
      BIND(<http://lod.gwd.go.kr/resource/AM0040_T> as ?uri).
      ?uri wgs:lat ?lat1 ;
    	   wgs:long ?lng1 .
      
      SERVICE <http://lod.knps.or.kr/sparql/> {
    	?nearUri rdfs:label ?nearLabel.
    	FILTER contains (str(?nearUri), 'lod.knps.or.kr'). 
    	FILTER langMatches(lang(?nearLabel), "KO").
    	?nearUri <http://lod.knps.or.kr/schema/property/address> ?address.
    	?nearUri wgs:lat ?lat .
    	?nearUri wgs:long ?lng .
    	?nearUri foaf:depiction ?image .
    	FILTER (f:distance(?lat1, ?lng1, ?lat, ?lng) < 5000)
      }
    } 
    GROUP BY  ?nearUri ?nearLabel ?lat ?lng ?distance ?address
    ORDER BY asc(?distance)
    
  • 3.10 특정 리소스의 SameAs 걸린 리소스 조회

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX owl: <http://www.w3.org/2002/07/owl#>
    
    SELECT ?uri
    WHERE
    {
      bind(<http://lod.gwd.go.kr/resource/AH0041_T> as ?resourcUri ).
      ?resourcUri owl:sameAs ?uri .
      FILTER contains(str(?resourcUri), 'lod.gwd.go.kr').
      FILTER (!contains(str(?uri), 'lod.gwd.go.kr')).
    } 
    LIMIT 100
    
  • 3.11 강원도 지역별 관광정보 건수 - GROUP BY

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    
    SELECT ?locationUri (count(?locationUri) as ?cnt)
    WHERE {
    	?s ktop:location ?locationUri.
    }
    GROUP BY ?locationUri 
    
  • 3.12 분류가 "관광"인 인스턴스 구축건수

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX ktop: <http://data.visitkorea.or.kr/property/>
    PREFIX gwp: <http://lod.gwd.go.kr/property/>
    PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
    PREFIX res: <http://lod.gwd.go.kr/resource/>
    PREFIX dc: <http://purl.org/dc/elements/1.1/>
    
    SELECT ("http://lod.gwd.go.kr/resource/CLASSIFICATION:A" as ?typeUri) (count(?uri) as ?cnt) 
    FROM <http://www.ontotext.com/disable-sameAs>
    {
    	SELECT distinct(?s_uri as ?uri) ?label ?loc ?image ?description
    	{
    		?s_uri gwp:category ?cat.
    		?cat  skos:broader res:CLASSIFICATION:A.
    		?s_uri rdfs:label ?label.
    		FILTER langMatches(lang(?label), "KO")
    		?s_uri ktop:location ?location.
    		?location rdfs:label ?loc.
    		FILTER langMatches(lang(?loc), "KO")
    		?s_uri dc:description ?description.
    		FILTER langMatches(lang(?description), "KO")
    		?s_uri foaf:thumbnail ?image.
    	}
    } LIMIT 1
    
  • 3.13 특산품 클래스내의 "영문" 인스턴스 결과 조회

    PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    
    SELECT DISTINCT ?instance ?label
    {
    	?instance rdf:type <http://lod.gwd.go.kr/ontology/Specialproduct>. 
    	filter contains (str(?instance) , 'lod.gwd.go.kr')
    	optional {?instance rdfs:label  ?label 
    	FILTER langMatches(lang(?label), "EN") .
    	}
    }
    LIMIT 10