Article

本体库开发示例

更新于:2026-07-16

Active Ontology(本体)

1. Ontology IRI

本体 IRI 用于明确指出本体的身份,从而确保在不同的上下文中本体可以被唯一识别。

注意:http 链接是 IRI,一般不可访问,仅用于唯一标识本体。

@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 data: <http://example.com/ontology/my_ontology#> .

<http://example.com/ontology/my_ontology>
  rdf:type owl:Ontology .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person in the system." .

data:hasName rdf:type rdf:Property ;
             rdfs:label "has name" ;
             rdfs:comment "The name of a person." ;
             rdfs:domain data:Person ;
             rdfs:range rdfs:Literal .

2. Ontology Version IRI

用于确保即使本体发生了更改,也可以引用本体的特定版本。

注意:前缀是 owl

@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 data: <http://example.com/ontology/my_ontology#> .

<http://example.com/ontology/my_ontology/versions/v1.0>
  rdf:type owl:Ontology ;
  owl:versionInfo "1.0" .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person in the system." .

data:hasName rdf:type rdf:Property ;
             rdfs:label "has name" ;
             rdfs:comment "The name of a person." ;
             rdfs:domain data:Person ;
             rdfs:range rdfs:Literal .

3. Ontology Imports

通过 Imports,一个本体可以从另一个本体中导入定义,避免重复定义相同的类、属性等。

定义本体 A:

@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 data: <http://example.com/ontology/A#> .

<http://example.com/ontology/A>
  rdf:type owl:Ontology ;
  owl:versionInfo "1.0" .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person in the system." .

data:hasName rdf:type rdf:Property ;
             rdfs:label "has name" ;
             rdfs:comment "The name of a person." ;
             rdfs:domain data:Person ;
             rdfs:range rdfs:Literal .

在本体 B 中导入本体 A:

@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 data: <http://example.com/ontology/B#> .

<http://example.com/ontology/B>
  rdf:type owl:Ontology ;
  owl:imports <http://example.com/ontology/A> ;
  owl:versionInfo "1.0" .

data:Student rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Student" ;
             rdfs:comment "Represents a student in the system." .

data:hasStudentID rdf:type rdf:Property ;
                  rdfs:label "has student ID" ;
                  rdfs:comment "The student ID of a student." ;
                  rdfs:domain data:Student ;
                  rdfs:range xsd:integer .

4. Ontology Prefixes

使用前缀可以使得 RDF 语法更加简洁易读,并且方便在不同的文档之间共享命名空间。

@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person in the system." .

data:hasName rdf:type rdf:Property ;
             rdfs:label "has name" ;
             rdfs:comment "The name of a person." ;
             rdfs:domain data:Person ;
             rdfs:range rdfs:Literal .

5. General Class Axioms

特殊的逻辑规则,用于定义类之间的关系。这类规则允许你对类进行更复杂的逻辑描述,而不仅仅是简单的子类关系。

a. 等价类 (Equivalent Classes)

表示两个或多个类是等价的,即它们具有相同的成员。

data:Employee owl:equivalentClass data:Worker .

b. 子类 (Subclasses)

表示一个类是另一个类的子类。

data:Employee rdfs:subClassOf data:Worker .

c. 交集 (Intersection of Classes)

表示一个类是两个或多个类的交集。

data:FullTimeEmployee owl:equivalentClass [
  rdf:type owl:Class ;
  owl:intersectionOf (data:Employee data:FullTimeWorker)
] .

d. 并集 (Union of Classes)

表示一个类是两个或多个类的并集。

data:Worker owl:equivalentClass [
  rdf:type owl:Class ;
  owl:unionOf (data:Employee data:Contractor)
] .

e. 补集 (Complement of a Class)

表示一个类是另一个类的补集,即不属于原始类的所有事物。

data:NonEmployee owl:equivalentClass [
  rdf:type owl:Class ;
  owl:complementOf data:Employee
] .

f. 存在限制 (Existential Restrictions)

表示一个类的所有成员都必须有一个或多个特定类型的属性。

data:Manager owl:equivalentClass [
  rdf:type owl:Class ;
  owl:intersectionOf (
    data:Employee
    [ rdf:type owl:Restriction ;
      owl:onProperty data:manages ;
      owl:someValuesFrom data:Employee
    ]
  )
] .

g. 全称限制 (Universal Restrictions)

表示一个类的所有成员都必须有所有特定类型的属性。

data:FullTimeEmployee owl:equivalentClass [
  rdf:type owl:Class ;
  owl:intersectionOf (
    data:Employee
    [ rdf:type owl:Restriction ;
      owl:onProperty data:worksFor ;
      owl:allValuesFrom data:Company
    ]
  )
] .

完整示例:

@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 data: <http://example.com/ontology#> .

data:Employee rdf:type rdfs:Class ;
             rdfs:label "Employee" ;
             rdfs:comment "Represents an employee in the company." .

data:Worker rdf:type rdfs:Class ;
            rdfs:label "Worker" ;
            rdfs:comment "Represents a worker in the company." .

data:Manager rdf:type rdfs:Class ;
             rdfs:label "Manager" ;
             rdfs:comment "Represents a manager in the company." .

data:FullTimeEmployee rdf:type rdfs:Class ;
                      rdfs:label "Full Time Employee" ;
                      rdfs:comment "Represents a full time employee in the company." .

data:Contractor rdf:type rdfs:Class ;
                rdfs:label "Contractor" ;
                rdfs:comment "Represents a contractor in the company." .

data:Company rdf:type rdfs:Class ;
             rdfs:label "Company" ;
             rdfs:comment "Represents a company." .

data:worksFor rdf:type rdf:Property ;
              rdfs:label "works for" ;
              rdfs:comment "The company an employee works for." ;
              rdfs:domain data:Employee ;
              rdfs:range data:Company .

data:manages rdf:type rdf:Property ;
             rdfs:label "manages" ;
             rdfs:comment "The employees managed by a manager." ;
             rdfs:domain data:Manager ;
             rdfs:range data:Employee .

data:Manager owl:equivalentClass [
  rdf:type owl:Class ;
  owl:intersectionOf (
    data:Employee
    [ rdf:type owl:Restriction ;
      owl:onProperty data:manages ;
      owl:someValuesFrom data:Employee
    ]
  )
] .

data:FullTimeEmployee owl:equivalentClass [
  rdf:type owl:Class ;
  owl:intersectionOf (
    data:Employee
    [ rdf:type owl:Restriction ;
      owl:onProperty data:worksFor ;
      owl:allValuesFrom data:Company
    ]
  )
] .

data:Worker owl:equivalentClass [
  rdf:type owl:Class ;
  owl:unionOf (data:Employee data:Contractor)
] .

data:Employee rdfs:subClassOf data:Worker .

data:NonEmployee owl:equivalentClass [
  rdf:type owl:Class ;
  owl:complementOf data:Employee
] .

Classes(类)

本体中的基本构建块之一,用于描述领域内的实体类型。

1. 定义(Define)

使用 rdf:type rdfs:Class 来声明一个 Class。

data:Book rdf:type rdfs:Class .

2. 描述(Description)

a. Equivalent To(等价类)

使用 owl:equivalentClass 来声明等价类。

data:Novel owl:equivalentClass data:Fiction .

b. SubClass Of(子类)

使用 rdfs:subClassOf 来声明一个子类。

data:Fiction rdfs:subClassOf data:Book .

c. Disjoint With(不相交)

定义这两个类是不相交的。

@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 data: <http://example.com/ontology#> .

data:Student rdf:type rdfs:Class ;
             rdfs:label "Student" ;
             rdfs:comment "Represents a student." ;
             owl:disjointWith data:Teacher .

data:Teacher rdf:type rdfs:Class ;
             rdfs:label "Teacher" ;
             rdfs:comment "Represents a teacher." ;
             owl:disjointWith data:Student .

d. Disjoint Union Of(不相交并集)

通过定义一个类为其不相交子类的并集,可以明确地划分该类的成员。

@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 data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." ;
           owl:equivalentClass [
             rdf:type owl:Class ;
             owl:unionOf (data:Student data:Teacher)
           ] .

data:Student rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Student" ;
             rdfs:comment "Represents a student." ;
             owl:disjointWith data:Teacher .

data:Teacher rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Teacher" ;
             rdfs:comment "Represents a teacher." ;
             owl:disjointWith data:Student .

e. Intersection(交集)

使用 owl:intersectionOf 来定义两个或多个类的交集。

data:HardcoverFiction owl:equivalentClass [
  rdf:type owl:Class ;
  owl:intersectionOf (data:Fiction data:Hardcover)
] .

f. Union(并集)

使用 owl:unionOf 来定义两个或多个类的并集。

data:PublishedMaterial owl:equivalentClass [
  rdf:type owl:Class ;
  owl:unionOf (data:Book data:JournalArticle)
] .

g. Complement(补集)

使用 owl:complementOf 来定义一个类的补集。

data:UnpublishedMaterial owl:equivalentClass [
  rdf:type owl:Class ;
  owl:complementOf data:PublishedMaterial
] .

完整示例:

@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 data: <http://example.com/ontology#> .

data:Book rdf:type rdfs:Class ;
          rdfs:label "Book" ;
          rdfs:comment "Represents a book." .

data:Fiction rdf:type rdfs:Class ;
             rdfs:subClassOf data:Book ;
             rdfs:label "Fiction" ;
             rdfs:comment "Represents a work of fiction." .

data:NonFiction rdf:type rdfs:Class ;
                rdfs:subClassOf data:Book ;
                rdfs:label "NonFiction" ;
                rdfs:comment "Represents a non-fiction work." .

data:Hardcover rdf:type rdfs:Class ;
               rdfs:label "Hardcover" ;
               rdfs:comment "Represents a hardcover book." .

data:Paperback rdf:type rdfs:Class ;
               rdfs:label "Paperback" ;
               rdfs:comment "Represents a paperback book." .

data:HardcoverFiction rdf:type rdfs:Class ;
                      owl:equivalentClass [
                        rdf:type owl:Class ;
                        owl:intersectionOf (data:Fiction data:Hardcover)
                      ] .

data:PublishedMaterial rdf:type rdfs:Class ;
                       owl:equivalentClass [
                         rdf:type owl:Class ;
                         owl:unionOf (data:Book data:JournalArticle)
                       ] .

data:UnpublishedMaterial rdf:type rdfs:Class ;
                         owl:equivalentClass [
                           rdf:type owl:Class ;
                           owl:complementOf data:PublishedMaterial
                         ] .

Object Properties(对象属性)

对象属性,用于描述实体之间的关系。

1. 定义(Define)

Object Properties 用于表示实体之间的关系。例如,data:hasParent 可以表示一个人与其父母之间的关系。

@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 data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." .

data:Student rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Student" ;
             rdfs:comment "Represents a student." .

data:Teacher rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Teacher" ;
             rdfs:comment "Represents a teacher." .

data:hasChild rdf:type owl:ObjectProperty ;
              rdfs:label "has child" ;
              rdfs:comment "The children of a person." ;
              rdfs:domain data:Person ;
              rdfs:range data:Person .

2. 描述(Description)

a. Equivalent To(等价属性)

表示两个 Object Properties 是等价的,即它们具有相同的含义和用法。

data:hasChild owl:equivalentProperty data:isChildOf .

b. SubProperty Of(子属性)

表示一个 Object Property 是另一个 Object Property 的子属性,即前者所表达的关系是后者所表达关系的一个特例。

data:hasChild rdfs:subPropertyOf data:relatedTo .

c. Inverse Of(逆属性)

表示两个 Object Properties 是互逆的,即如果实体 A 通过 Property1 与实体 B 相关联,则实体 B 通过 Property2 与实体 A 相关联。

data:isChildOf rdf:type owl:ObjectProperty ;
               rdfs:label "is child of" ;
               rdfs:comment "The parents of a person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:inverseOf data:hasChild .

d. Domains (Intersection)(域交集)

表示一个 Object Property 的域是两个或多个类的交集,即只有当实体属于这些类的交集时,该属性才适用。

data:relatedTo rdf:type owl:ObjectProperty ;
               rdfs:label "related to" ;
               rdfs:comment "A person is related to another person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person .

e. Ranges (Intersection)(值域交集)

表示一个 Object Property 的值域是两个或多个类的交集,即只有当属性的值属于这些类的交集时,该属性才适用。

data:relatedTo rdf:type owl:ObjectProperty ;
               rdfs:label "related to" ;
               rdfs:comment "A person is related to another person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person .

f. Disjoint With(不相交属性)

表示两个 Object Properties 是不相交的,即一个实体不能同时通过这两个属性与另一个实体相关联。

data:hasChild owl:disjointWith data:isChildOf .

g. SuperProperty Of (Chain)(属性链)

表示通过一系列 Object Properties 的链式组合可以推导出一个更广泛的 Object Property。

data:relatedTo owl:propertyChainAxiom (data:hasChild data:isChildOf) .

3. 特性(Characteristics)

前置定义:

@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 data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." .

a. Functional(函数性)

表示对于每个实体,一个 Object Property 最多只能有一个值。

data:hasChild rdf:type owl:ObjectProperty ;
              rdfs:label "has child" ;
              rdfs:comment "The children of a person." ;
              rdfs:domain data:Person ;
              rdfs:range data:Person ;
              owl:FunctionalProperty .

b. Inverse Functional(逆函数性)

表示对于每个实体,一个 Object Property 的逆属性最多只能有一个值。

data:isChildOf rdf:type owl:ObjectProperty ;
               rdfs:label "is child of" ;
               rdfs:comment "The parents of a person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:InverseFunctionalProperty ;
               owl:inverseOf data:hasChild .

c. Transitive(传递性)

表示如果实体 A 通过 Property1 与实体 B 相关联,且实体 B 通过 Property1 与实体 C 相关联,则实体 A 也通过 Property1 与实体 C 相关联。

data:relatedTo rdf:type owl:ObjectProperty ;
               rdfs:label "related to" ;
               rdfs:comment "A person is related to another person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:SymmetricProperty ;
               owl:TransitiveProperty .

d. Symmetric(对称性)

表示如果实体 A 通过 Property1 与实体 B 相关联,则实体 B 也通过 Property1 与实体 A 相关联。

data:relatedTo rdf:type owl:ObjectProperty ;
               rdfs:label "related to" ;
               rdfs:comment "A person is related to another person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:SymmetricProperty .

e. Asymmetric(非对称性)

表示如果实体 A 通过 Property1 与实体 B 相关联,则实体 B 不会通过 Property1 与实体 A 相关联。

data:marriedTo rdf:type owl:ObjectProperty ;
               rdfs:label "married to" ;
               rdfs:comment "A person is married to another person." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:AsymmetricProperty .

f. Reflexive(自反性)

表示每个实体都必须通过 Property1 与自身相关联。

data:lovesSelf rdf:type owl:ObjectProperty ;
               rdfs:label "loves self" ;
               rdfs:comment "A person loves themselves." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:ReflexiveProperty .

g. Irreflexive(非自反性)

表示没有实体能够通过 Property1 与自身相关联。

data:hatesSelf rdf:type owl:ObjectProperty ;
               rdfs:label "hates self" ;
               rdfs:comment "A person hates themselves." ;
               rdfs:domain data:Person ;
               rdfs:range data:Person ;
               owl:IrreflexiveProperty .

Data Properties(数据属性)

代表了实体与数据值之间的关系。这些数据值通常是简单的数据类型,如字符串、整数或日期。

1. 定义(Define)

@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 xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." .

data:Student rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Student" ;
             rdfs:comment "Represents a student." .

data:Teacher rdf:type rdfs:Class ;
             rdfs:subClassOf data:Person ;
             rdfs:label "Teacher" ;
             rdfs:comment "Represents a teacher." .

data:age rdf:type owl:DatatypeProperty ;
         rdfs:label "age" ;
         rdfs:comment "The age of a person." ;
         rdfs:domain data:Person ;
         rdfs:range xsd:integer .

data:birthYear rdf:type owl:DatatypeProperty ;
               rdfs:label "birth year" ;
               rdfs:comment "The birth year of a person." ;
               rdfs:domain data:Person ;
               rdfs:range xsd:integer .

2. 描述(Description)

a. Equivalent To(等价属性)

表示两个 Data Properties 是等价的,即它们具有相同的含义和用法。

data:age owl:equivalentProperty data:birthYear .

b. SubProperty Of(子属性)

表示一个 Data Property 是另一个 Data Property 的子属性,即前者所表达的属性是后者所表达属性的一个特例。

data:age rdfs:subPropertyOf data:birthYear .

c. Domains (Intersection)(域交集)

表示一个 Data Property 的域是两个或多个类的交集,即只有当实体属于这些类的交集时,该属性才适用。

data:age owl:equivalentProperty [
  rdf:type owl:DatatypeProperty ;
  rdfs:domain [
    rdf:type owl:Class ;
    owl:intersectionOf (data:Student data:Teacher)
  ] ;
  rdfs:range xsd:integer
] .

d. Ranges(值域)

表示一个 Data Property 的值域,即属性的值所属的数据类型。

data:age rdfs:range xsd:integer .

e. Disjoint With(不相交属性)

表示两个 Data Properties 是不相交的,即一个实体不能同时通过这两个属性与另一个实体相关联。

data:age owl:disjointWith data:birthYear .

3. 特性(Characteristics)

a. Functional(函数性)

表示对于每个实体,一个 Data Property 最多只能有一个值。

@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 xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." .

data:age rdf:type owl:DatatypeProperty ;
         rdfs:label "age" ;
         rdfs:comment "The age of a person." ;
         rdfs:domain data:Person ;
         rdfs:range xsd:integer ;
         owl:FunctionalProperty .

Individuals by Class(按类划分的实例)

表示根据定义的类来创建 Individuals,这些 Individuals 属于特定的类。

1. 定义(Define)

@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 data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." .

data:John rdf:type data:Person ;
          rdfs:label "John Doe" .

data:Mary rdf:type data:Person ;
          rdfs:label "Mary Smith" .

2. 描述(Description)

a. Types

表示 Individuals 属于特定的类。

data:JohnAltId rdf:type data:Person ;
               rdfs:label "John Doe Alternative ID" .

b. Same Individual As

表示两个 Individuals 实际上是指同一个实体。

data:John owl:sameAs data:JohnAltId .

c. Different Individuals

表示两个 Individuals 不是指同一个实体。

data:Mary owl:differentFrom data:John .

3. Property Assertions(属性断言)

描述实例之间的关系和属性。

前置定义:

@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 xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix data: <http://example.com/ontology#> .

data:Person rdf:type rdfs:Class ;
           rdfs:label "Person" ;
           rdfs:comment "Represents a person." .

data:John rdf:type data:Person ;
          rdfs:label "John Doe" .

data:Mary rdf:type data:Person ;
          rdfs:label "Mary Smith" .

data:Bob rdf:type data:Person ;
         rdfs:label "Bob Brown" .

data:age rdf:type owl:DatatypeProperty ;
         rdfs:label "age" ;
         rdfs:comment "The age of a person." ;
         rdfs:domain data:Person ;
         rdfs:range xsd:integer .

a. Object Property Assertions(对象属性断言)

表示一个 Individual 通过 Object Property 与另一个 Individual 相关联。

data:knows rdf:type owl:ObjectProperty ;
           rdfs:label "knows" ;
           rdfs:comment "One person knows another person." ;
           rdfs:domain data:Person ;
           rdfs:range data:Person .
data:John data:knows data:Mary .
# 声明 John 认识 Mary

b. Data Property Assertions(数据属性断言)

表示一个 Individual 具有特定的属性值。

data:age rdf:type owl:DatatypeProperty ;
         rdfs:label "age" ;
         rdfs:comment "The age of a person." ;
         rdfs:domain data:Person ;
         rdfs:range xsd:integer .
data:Mary data:age "25"^^xsd:integer .
# 声明 Mary 的年龄是 25 岁

c. Negative Object Property Assertions(否定对象属性断言)

表示一个 Individual 与另一个 Individual 之间不存在特定的关系。

{
  data:John data:knows data:Bob .
} owl:negativePropertyAssertion .
# 声明 John 不认识 Bob

d. Negative Data Property Assertions(否定数据属性断言)

表示一个 Individual 不具有特定的属性值。

{
  data:Bob data:age "30"^^xsd:integer .
} owl:negativePropertyAssertion .
# 声明 Bob 的年龄不是 30 岁

Entities(实体)

通用术语,用于指代本体中的所有类型的概念和实体。

1. Classes(类)

  • 代表一类事物或概念。
  • 例如:PersonAnimalVehicle

2. Object Properties(对象属性)

  • 代表实体之间的关系。
  • 例如:hasParentownsisPartOf

3. Data Properties(数据属性)

  • 代表实体与简单数据值之间的关系。
  • 例如:ageheightcolor

4. Annotation Properties(注解属性)

  • 用于存储关于本体元素的元数据。
  • 例如:versionauthorsource

5. Datatype(数据类型)

  • 用于定义 Data Properties 的值域。
  • 例如:xsd:stringxsd:integerxsd:date

6. Individuals(实例)

  • 代表本体中的具体实例或对象。
  • 例如:JohnCar1NewYorkCity

示例:

假设你在 Protege 中创建了一个本体,其中包括以下 Entities:

  • ClassesPersonBook
  • Object PropertieshasFriendreads
  • Data Propertiesagetitle
  • IndividualsJohnHarryPotterBook

你可以使用这些 Entities 来描述具体的事物,例如:

  • 创建一个 Individual John,并设置它的 age30
  • 创建一个 Individual HarryPotterBook,并设置它的 title"Harry Potter and the Sorcerer's Stone"
  • 创建一个 Object Property hasFriend,并声明 John 通过 hasFriend 与另一个 Individual Mary 相关联。
  • 创建一个 Object Property reads,并声明 John 通过 readsHarryPotterBook 相关联。

rdflib 支持的 SPARQL 操作

基本查询

1. SELECT 查询

返回满足查询条件的变量值。

SELECT [DISTINCT | REDUCED] ?var1 ?var2 ...
WHERE
{
  graph-pattern
}
[GROUP BY ?var1 ?var2 ...]
[HAVING (expression)]
[ORDER BY [ASC | DESC] (expression) ...]
[LIMIT integer]
[OFFSET integer]
  • SELECT:指定要返回的变量。
  • DISTINCT:去除重复结果。
  • REDUCED:类似 DISTINCT,但可能更快。
  • graph-pattern:匹配模式,由三元组组成。
  • GROUP BY:对结果进行分组。
  • HAVING:在分组后过滤结果。
  • ORDER BY:排序结果。
  • LIMIT:限制结果数量。
  • OFFSET:跳过初始结果。

示例:

from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef
from rdflib.namespace import FOAF, XSD

g = Graph()
g.parse("example.rdf", format="xml")

qres = g.query(
    """
    SELECT ?name ?age
    WHERE {
      ?person foaf:name ?name ;
              foaf:age ?age .
    }
    """,
    initNs=dict(foaf=FOAF)
)

for row in qres:
    print(row)

2. DESCRIBE 查询

返回与查询中指定的资源相关的所有三元组。

示例:

qres = g.query(
    """
    DESCRIBE ?s
    WHERE {
      ?s foaf:name ?name .
    }
    """,
    initNs=dict(foaf=FOAF)
)

for row in qres:
    print(row)

3. CONSTRUCT 查询

根据查询构造一个新的 RDF 图形。

示例:

qres = g.query(
    """
    CONSTRUCT {
      ?s foaf:name ?name .
    }
    WHERE {
      ?s foaf:name ?name .
    }
    """,
    initNs=dict(foaf=FOAF)
)

for row in qres:
    print(row)

4. ASK 查询

返回一个布尔值,表示是否存在满足条件的三元组。

示例:

result = g.query(
    """
    ASK {
      ?s foaf:name ?name .
    }
    """,
    initNs=dict(foaf=FOAF)
)

print(result.askAnswer)

更新操作(SPARQL Update)

rdflib 支持 SPARQL Update 语法,允许对 RDF 图形进行修改。需要注意的是,这些操作可能会影响图形的内容。

INSERT DATA

插入一组新的三元组。

g.update(
    """
    INSERT DATA {
      <http://example.com/alice> foaf:name "Alice" .
    }
    """
)

DELETE DATA

删除一组三元组。

g.update(
    """
    DELETE DATA {
      <http://example.com/alice> foaf:name "Alice" .
    }
    """
)

INSERT INTO

将一组新的三元组插入到指定图中。

g.update(
    """
    INSERT INTO <http://example.com/graph1> {
      <http://example.com/alice> foaf:name "Alice" .
    }
    """
)

DELETE FROM

从指定图中删除一组三元组。

g.update(
    """
    DELETE FROM <http://example.com/graph1> {
      <http://example.com/alice> foaf:name "Alice" .
    }
    """
)

DELETE WHERE

根据模式删除一组三元组。

g.update(
    """
    DELETE WHERE {
      ?s foaf:name ?name .
    }
    """
)

CLEAR GRAPH

清空整个图。

g.update(
    """
    CLEAR GRAPH <http://example.com/graph1>
    """
)

其他功能

PREFIX

定义命名空间前缀。

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?age
WHERE {
  ?person foaf:name ?name ;
          foaf:age ?age .
}

UNION

合并两个模式的结果。

PREFIX foaf: <http://xmlns.com/foaf/0.1/>
SELECT ?name ?age
WHERE {
  {
    ?person foaf:name ?name .
  }
  UNION
  {
    ?person foaf:age ?age .
  }
}

FILTER

在 WHERE 子句中过滤结果。

SELECT ?name ?age
WHERE {
  ?person foaf:name ?name ;
          foaf:age ?age .
  FILTER (?age > 30)
}

GROUP BY 和 HAVING

对结果进行分组和过滤。

SELECT ?name (COUNT(?age) AS ?count)
WHERE {
  ?person foaf:name ?name ;
          foaf:age ?age .
}
GROUP BY ?name
HAVING (?count > 1)

ORDER BY

对结果进行排序。

SELECT ?name ?age
WHERE {
  ?person foaf:name ?name ;
          foaf:age ?age .
}
ORDER BY ?name

LIMIT 和 OFFSET

限制结果的数量和偏移量。

SELECT ?name ?age
WHERE {
  ?person foaf:name ?name ;
          foaf:age ?age .
}
LIMIT 10 OFFSET 5

BIND

给变量赋值。

SELECT ?name ("Alice" AS ?name)
WHERE {
  ?person foaf:name ?name .
}

VALUES

设置变量的值列表。

SELECT ?name
WHERE {
  ?person foaf:name ?name .
  VALUES ?name { "Alice" "Bob" }
}

MINUS

差集运算。

SELECT ?name
WHERE {
  ?person foaf:name ?name .
} MINUS {
  ?person foaf:age ?age .
}

SPARQL 内置函数

过滤与条件

函数描述
FILTER (expr)应用一个布尔表达式来过滤结果
FILTER NOT EXISTS检查一个图模式是否不存在
FILTER EXISTS检查一个图模式是否存在
BIND绑定一个变量到一个值
IF条件表达式
COALESCE返回第一个非空值

类型判断

函数描述
IS IRI检查变量是否为 IRI
IS LITERAL检查变量是否为字面量
IS NUMERIC检查变量是否为数字
IS URI检查变量是否为 URI

字符串函数

函数描述
STR将值转换为字符串
LANG获取字面量的自然语言标签
LANGMATCHES检查语言标签是否匹配
LCASE将字符串转换为小写
UCASE将字符串转换为大写
STRSTARTS检查一个字符串是否以另一个字符串开头
STRENDS检查一个字符串是否以另一个字符串结尾
STRBEFORE获取一个字符串在另一个字符串之前的子串
STRAFTER获取一个字符串在另一个字符串之后的子串
REPLACE替换字符串中的模式
CONCAT连接多个字符串
STRLEN获取字符串长度
SUBSTR获取字符串的子串
CONTAINS检查一个字符串是否包含另一个字符串
STRDT获取字面量的数据类型
STRLANG获取字面量的语言标签

数学函数

函数描述
ABS返回绝对值
CEIL向上取整
FLOOR向下取整
ROUND四舍五入
RAND返回随机数

日期时间函数

函数描述
YEAR获取日期的年份
MONTH获取日期的月份
DAY获取日期的日
HOURS获取时间的小时数
MINUTES获取时间的分钟数
SECONDS获取时间的秒数
NOW返回当前时间戳

哈希与 UUID

函数描述
STRUUID生成一个字符串形式的 UUID
MD5计算 MD5 哈希值
SHA1计算 SHA-1 哈希值
SHA256计算 SHA-256 哈希值
SHA384计算 SHA-384 哈希值
SHA512计算 SHA-512 哈希值

聚合函数

函数描述
COUNT计数
SUM求和
MIN最小值
MAX最大值
AVG平均值
GROUP_CONCAT按分组连接字符串
SAMPLE随机样本

比较与正则

函数描述
=, !=, <, <=, >, >=比较运算符
REGEX检查字符串是否匹配正则表达式
REPLACE替换字符串中的模式
REPLACE_REGEX使用正则表达式替换字符串中的模式

路径表达式(Path Expressions)

支持路径表达式。

示例:

SELECT ?name
WHERE {
  ?person foaf:name ?name ;
          foaf:mbox [ a foaf:Document ] .
}

子查询(Subquery)

查询内部嵌套的查询使用花括号,可以完成对变量的绑定。

示例:

SELECT ?table
WHERE {
    ?table rdf:type ?type .
    {
        SELECT ?type
        WHERE {
            ?type rdfs:subClassOf* data:Table .
        }
    }
}

SPARQL 路径表达式通配符

1. *(Zero or More Times)

表示零次或多次的关系。

例如:?type rdfs:subClassOf* data:Table 表示 ?type 可以是 data:Table 的直接子类、间接子类,甚至是 data:Table 本身。

2. +(One or More Times)

表示一次或多次的关系。

例如:?type rdfs:subClassOf+ data:Table 表示 ?type 必须是 data:Table 的直接子类或间接子类,但不能是 data:Table 本身。

3. ?(Zero or One Time)

表示零次或一次的关系。

例如:?type rdfs:subClassOf? data:Table 表示 ?type 可能是 data:Table 的直接子类,也可能不是。

存盘操作

update 接口只是修改了内存中的 RDF 图,如果需要保存到磁盘,需要调用 serialize 接口。

示例:

from rdflib import Graph, Namespace, Literal, URIRef
from rdflib.namespace import FOAF

# 创建一个 Graph 对象
g = Graph()

# 加载 RDF 数据
# 假设你有一个 RDF 文件 example.rdf
g.parse("example.rdf", format="xml")

# 定义命名空间
FOAF = Namespace("http://xmlns.com/foaf/0.1/")

# 执行 SPARQL Update 查询
g.update(
    """
    INSERT INTO <http://example.com/graph1> {
      <http://example.com/alice> foaf:name "Alice" .
    }
    """
)

# 将修改后的图形写回到文件
g.serialize(destination="example.rdf", format="xml")