Jena替代RDF4J中的ModelBuilder

时间:2018-02-20 08:36:59

标签: jena rdf4j

在Apache Jena中是否有一些接口可用,如RDF4J中的ModelBuilder

我可以在耶拿看到ModelMaker,但这与我认为的建筑师不太相似。 以下是使用rdf4j的函数,需要在Jena中实现:

public static org.eclipse.rdf4j.model.Model convertGraph2RDFModel(Graph graph, String label) {
        ModelBuilder builder = new ModelBuilder();
        GraphTraversalSource t = graph.traversal();
        GraphTraversal<Vertex, Vertex> hasLabel = t.V().hasLabel(label);
        Vertex s;
        if(hasLabel.hasNext()){
            s = hasLabel.next();
            extractModelFromVertex(builder, s);
        }
        return builder.build();
    }

private static void extractModelFromVertex(ModelBuilder builder, Vertex s) {
        builder.subject(s.label());
        Iterator<VertexProperty<String>> propertyIter = s.properties();
        while (propertyIter.hasNext()){
            VertexProperty<String> property = propertyIter.next();
            builder.add(property.label(), property.value());
        }
        Iterator<Edge> edgeIter = s.edges(Direction.OUT);
        Edge edge;
        Stack<Vertex> vStack = new Stack<Vertex>();
        while(edgeIter.hasNext()){
            edge = edgeIter.next();
            s = edge.inVertex();
            builder.add(edge.label(), s.label());
            vStack.push(s);
        }
        Iterator<Vertex> vIterator = vStack.iterator();
        while(vIterator.hasNext()){
            s = vIterator.next();
            extractModelFromVertex(builder,s);
        }
    }

1 个答案:

答案 0 :(得分:1)

我不知道Jena是否有类似的功能,但你当然可以继续使用RDF4J ModelBuilder,将其输出模型序列化为Turtle或TriG字符串(或文件),然后使用Jena读取它再次。

 org.eclipse.rdf4j.model.Model m = ...; // RDF4J Model built by the ModelBuilder
 java.io.Writer writer = new StringWriter();
 org.eclipse.rdf4j.rio.Rio.write(m, writer, RDFFormat.TRIG); 

 String = writer.toString();

 // Use Jena's parser to read the string back in.

或者只是迭代RDF4J模型并直接转换每个语句(不需要在它们之间进行序列化和反序列化):

 org.eclipse.rdf4j.model.Model rdf4jModel = ...; // RDF4J Model built by the ModelBuilder
 org.apache.jena.rdf.model.Model jenaModel = ...; // (empty) Jena model to receive converted rdf4j model 
 rdf4jModel.forEach(stmt -> jenaModel.add(convert(stmt)));

 ...

 public org.apache.jena.rdf.model.Statement convert(
                org.eclipse.rdf4j.model.Statement stmt) {
      ... // create a Jena statement from the RDF4J one. 
 }

我承认在大多数应用程序中使用单个框架可能更容易,但没有根本原因你不能组合使用RDF4J和Jena的位。