javardfjenasesamerdf4j

How to merge two or more models in RDF4J (formerly Sesame)?


In Apache Jena there is a way to append one model to another by just calling model1.add(model2), for example.

Is this also possible with RDF4J in case you interpret a model just as a set of statements?


Solution

  • In Eclipse RDF4J, a Model is a Java Collection (similar to a Set or a List). So you can use standard Java collection operations. To append two models, simply do:

    model1.addAll(model2);
    

    Note that this operation only appends statements. If model2 contains any namespace declarations that you wish to copy over as well, you will have to do that separately. For example, to have model2 namespace declarations simply copied over, overwriting any existing declarations in model1:

    model2.getNamespaces().stream().forEach(model1::setNamespace);
    

    Or if you only wish to copy over those prefixes for which model1 has no declaration yet:

    model2.getNamespaces().stream()
          .filter(ns -> !model1.getNamespace(ns.getPrefix()).isPresent())
          .forEach(model1::setNamespace);