存档

文章标签 ‘三元组’

用jena api来理解RDF——三元组

2010年1月1日

JENA中有一个最底层的接口:RDFNode,它代表RDF这张巨大图中的节点,这个节点可以是一个资源,可以是一个字符窜或者数字。因此它对应与2个子接口:
interface Literal extends RDFNode
interface Resource extends RDFNode
Literal接口代表了一些原始类型节点,比如:32位整型、布尔型等等。
Resource接口还可以继续衍生出2个重要的接口:
interface Container extends Resource
interface Property extends Resource
Container接口就对应了RDF的容器表达能力,里面有bag,seq,alt
Property接口就是所谓的资源属性了

在RDF的世界中,其实描述资源只有一种方式,那就是三元组,包括:主体(subject),谓词(predicate),客体(object)。主体和客体就是图中的2个节点,谓词就是一条边。这三元组在JENA中用Statement接口来描述,该接口中有下面3个方法:
public Resource getSubject();
public Property getPredicate();
public RDFNode getObject();

我们可以发现,主体一定是一种资源,不可能是一个Literal原始类型,因此主体必定属于Resource接口实现,但是客体可以是原始类型,比如:人有2条腿。为主体;为谓词;2为客体。

用一个例子来巩固下:

  1. <?xml version="1.0"?>
  2.  <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  3.           xmlns:s="http://example.org/students/vocab#">
  4.  
  5.     <rdf:Description rdf:about="http://example.org/courses/6.001">
  6.        <s:students>
  7.           <rdf:Bag>
  8.              <rdf:li rdf:resource="http://example.org/students/Amy"/>
  9.              <rdf:li rdf:resource="http://example.org/students/Mohamed"/>
  10.              <rdf:li rdf:resource="http://example.org/students/Johann"/>
  11.              <rdf:li rdf:resource="http://example.org/students/Maria"/>
  12.              <rdf:li rdf:resource="http://example.org/students/Phuong"/>
  13.           </rdf:Bag>
  14.        </s:students>
  15.     </rdf:Description>
  16.  </rdf:RDF>

如果要一下子看出这个RDF中有几个三元组,一定不是很方便吧?如果用图来表示:
201001011021
是不是非常清晰呢?图中有一个主体http://example.org/courses/6.001,它有一条边http://example.org/students/vocab#students,对应的客体就是那个空节点。同理还有这个空节点所对应的那些三元组。用JENA来解析这个例子:

  1. Model model = ModelFactory.createDefaultModel();
  2.  
  3. model.read(new FileInputStream("student.rdf"), null);
  4.  
  5. StmtIterator  it = model.listStatements();
  6.  
  7. while(it.hasNext())
  8. {
  9.     System.out.println(it.next());
  10. }

打印的结果如下:
[http://example.org/courses/6.001, http://example.org/students/vocab#students, -23ba78ea:125e9da42c8:-8000]
[-23ba78ea:125e9da42c8:-8000, http://www.w3.org/1999/02/22-rdf-syntax-ns#_5, http://example.org/students/Phuong]
[-23ba78ea:125e9da42c8:-8000, http://www.w3.org/1999/02/22-rdf-syntax-ns#_4, http://example.org/students/Maria]
[-23ba78ea:125e9da42c8:-8000, http://www.w3.org/1999/02/22-rdf-syntax-ns#_3, http://example.org/students/Johann]
[-23ba78ea:125e9da42c8:-8000, http://www.w3.org/1999/02/22-rdf-syntax-ns#_2, http://example.org/students/Mohamed]
[-23ba78ea:125e9da42c8:-8000, http://www.w3.org/1999/02/22-rdf-syntax-ns#_1, http://example.org/students/Amy]
[-23ba78ea:125e9da42c8:-8000, http://www.w3.org/1999/02/22-rdf-syntax-ns#type, http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag]

JENA ,