All Downloads are FREE. Search and download functionalities are using the official Maven repository.

apoc.graph.document.builder.RelationshipBuilder Maven / Gradle / Ivy

There is a newer version: 5.25.1
Show newest version
package apoc.graph.document.builder;

import apoc.graph.util.GraphsConfig;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class RelationshipBuilder {

    private GraphsConfig config;

    public RelationshipBuilder(GraphsConfig config) {
        this.config = config;
    }

    public Collection buildRelation(Node parent, Node child, String relationName) {
        
        RelationshipType type = RelationshipType
                .withName(config.getRelMapping().getOrDefault(relationName, relationName.toUpperCase()));

        // check if already exists
        // find only relation between parent and child node
        List rels = getRelationshipsForRealNodes(parent, child, type);
        if (rels.isEmpty()) {
            return Collections.singleton(parent.createRelationshipTo(child, type));
        } else {
            return rels;
        }
    }

    private List getRelationshipsForRealNodes(Node parent, Node child, RelationshipType type) {
        Iterable relationships = child.getRelationships(Direction.INCOMING, type);
        return StreamSupport.stream(relationships.spliterator(), false)
                .filter(rel -> rel.getOtherNode(child).equals(parent))
                .collect(Collectors.toList());
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy