Jena操作RDF文档,加载、输出、查询、规则推理

最近在学习接触知识图谱,采用Jena操作Protege实体文档。主要内容为:对Protege生成的RDF实体文档进行加载、输出、查询、规则推理等。

IDEA建立项目

pom.xml文档内容主要引入Jena


	org.apache.jena
	apache-jena-libs
	pom
	2.13.0

RDF文档加载

public Model fillEmptyModel(String base, String filePath) {
        Model model = ModelFactory.createDefaultModel();

        try (InputStream is = FileManager.get().open(filePath)) {
            model.read(is, base);
        } catch (Exception e) {
            logger.error("fillEmptyModel failed, refer", e);
        }

        return model;
    }

RDF文档输出

以RDF格式输出

model.write(System.out, "RDF/XML-ABBREV");

以三元组格式输出

model.write(System.out, "N-TRIPLES");

PS:System.out可以修改为文档路径,将其保存在本地

循环查看RDF文档中的内容,并以三元组(主谓宾)格式输出

public void printRDF(Model model){
	StmtIterator iter = model.listStatements();
	while (iter.hasNext()){
		Statement statement = iter.nextStatement();
		Resource subject = statement.getSubject();
		Property predicate = statement.getPredicate();
		RDFNode object = statement.getObject();

		System.out.print("主语" + subject.toString());
		System.out.print("谓语");
		System.out.print(" " + predicate.toString() + " ");
		if (object instanceof Resource){
			System.out.print("宾语"+object.toString());
		}else {
			System.out.print("宾语");
			System.out.print(" /" + object.toString() + "/");
		}
		System.out.println(".");
	}
   }

SPARQL查询

void inferenceTest() {
    //init and load model
    // 根据RDF和所查询不同,base是自定义文档中的uri
    Model model = fillEmptyModel(base, filePath)

    // query the inserted facts
    StringBuilder query = new StringBuilder();
    sb.append("PREFIX rdf: ").append(System.getProperty("line.separator"))
            .append("PREFIX owl: ").append(System.getProperty("line.separator"))
            .append("PREFIX xsd: ").append(System.getProperty("line.separator"))
            .append("PREFIX rdfs: ").append(System.getProperty("line.separator"));
    query.append("SELECT DISTINCT ?p WHERE {?e foaf:nick ?p FILTER regex(?p,'e', 'i')}");
    queryResult(model, query, "?q");
}
	
public void queryResult(Model model, String query, String... queryFields){
    // query
    Query q = QueryFactory.create(query.toString());
    QueryExecution qexec = QueryExecutionFactory.create(q, model);
    ResultSet rs = qexec.execSelect();

    // print query result
    while (rs.hasNext()) {
        QuerySolution qs = rs.nextSolution();
        for (int i = 0; i < queryFieldSize; i++) {
            RDFNode name = qs.get(queryFields[i]);
            if (name != null) {
                System.out.print(name + "\t");
            } else {
                System.out.print("NULL" + "\t");
            }
        }
        System.out.println();
    }
}

添加推导规则

在初始化模型,并加载内容时,将rules规则添加到model中代码如下

public static final InfModel createInfModel(Model model, String rules) {
      Reasoner reasoner = new GenericRuleReasoner(Rule.parseRules(rules));
       InfModel infModel = ModelFactory.createInfModel(reasoner, model);
       return infModel;
   }

采用InfModel进行SPARQL查询,将得到推理结果。

共同学习共同进步,加油

你可能感兴趣的:(java)