Search in sources :

Example 16 with RelationshipType

use of org.neo4j.graphdb.RelationshipType in project neo4j-apoc-procedures by neo4j-contrib.

the class Nodes method link.

@Procedure(mode = Mode.WRITE)
@Description("apoc.nodes.link([nodes],'REL_TYPE') - creates a linked list of nodes from first to last")
public void link(@Name("nodes") List<Node> nodes, @Name("type") String type) {
    Iterator<Node> it = nodes.iterator();
    if (it.hasNext()) {
        RelationshipType relType = RelationshipType.withName(type);
        Node node = it.next();
        while (it.hasNext()) {
            Node next = it.next();
            node.createRelationshipTo(next, relType);
            node = next;
        }
    }
}
Also used : Node(org.neo4j.graphdb.Node) RelationshipType(org.neo4j.graphdb.RelationshipType)

Example 17 with RelationshipType

use of org.neo4j.graphdb.RelationshipType in project neo4j-apoc-procedures by neo4j-contrib.

the class DegreeDistribution method prepareStats.

public List<DegreeStats> prepareStats(@Name(value = "types", defaultValue = "") String types, ReadOperations ops) {
    List<DegreeStats> stats = new ArrayList<>();
    if ("*".equals(types)) {
        Iterator<Token> tokens = ops.relationshipTypesGetAllTokens();
        while (tokens.hasNext()) {
            Token token = tokens.next();
            long total = ops.countsForRelationship(ANY_LABEL, token.id(), ANY_LABEL);
            stats.add(new DegreeStats(token.name(), token.id(), Direction.OUTGOING, total));
            stats.add(new DegreeStats(token.name(), token.id(), Direction.INCOMING, total));
        }
        return stats;
    }
    List<Pair<RelationshipType, Direction>> pairs = RelationshipTypeAndDirections.parse(types);
    for (Pair<RelationshipType, Direction> pair : pairs) {
        String typeName = pair.first() == null ? null : pair.first().name();
        int type = typeName == null ? ANY_RELATIONSHIP_TYPE : ops.relationshipTypeGetForName(typeName);
        long total = ops.countsForRelationship(ANY_LABEL, type, ANY_LABEL);
        stats.add(new DegreeStats(typeName, type, pair.other(), total));
    }
    return stats;
}
Also used : ArrayList(java.util.ArrayList) RelationshipType(org.neo4j.graphdb.RelationshipType) Token(org.neo4j.storageengine.api.Token) Direction(org.neo4j.graphdb.Direction) Pair(org.neo4j.helpers.collection.Pair)

Example 18 with RelationshipType

use of org.neo4j.graphdb.RelationshipType in project neo4j-apoc-procedures by neo4j-contrib.

the class Centrality method closeness.

@Deprecated
@Procedure("apoc.algo.closeness")
@Description("CALL apoc.algo.closeness(['TYPE',...],nodes, INCOMING) YIELD node, score - calculate closeness " + "centrality for given nodes")
public Stream<NodeScore> closeness(@Name("types") List<String> types, @Name("nodes") List<Node> nodes, @Name("direction") String direction) {
    assertParametersNotNull(types, nodes);
    try {
        RelationshipType[] relationshipTypes = types.isEmpty() ? Util.allRelationshipTypes(db) : Util.toRelTypes(types);
        SingleSourceShortestPath<Double> sssp = new SingleSourceShortestPathDijkstra<>(0.0, null, (relationship, dir) -> 1.0, new DoubleAdder(), new DoubleComparator(), Util.parseDirection(direction), relationshipTypes);
        ClosenessCentrality<Double> closenessCentrality = new ClosenessCentrality<>(sssp, new DoubleAdder(), 0.0, new HashSet<>(nodes), new CostDivider<Double>() {

            @Override
            public Double divideByCost(Double d, Double c) {
                return d / c;
            }

            @Override
            public Double divideCost(Double c, Double d) {
                return c / d;
            }
        });
        return nodes.stream().map(node -> new NodeScore(node, closenessCentrality.getCentrality(node)));
    } catch (Exception e) {
        String errMsg = "Error encountered while calculating centrality";
        log.error(errMsg, e);
        throw new RuntimeException(errMsg, e);
    }
}
Also used : ClosenessCentrality(org.neo4j.graphalgo.impl.centrality.ClosenessCentrality) RelationshipType(org.neo4j.graphdb.RelationshipType) DoubleComparator(org.neo4j.graphalgo.impl.util.DoubleComparator) DoubleAdder(org.neo4j.graphalgo.impl.util.DoubleAdder) SingleSourceShortestPathDijkstra(org.neo4j.graphalgo.impl.shortestpath.SingleSourceShortestPathDijkstra) NodeScore(apoc.result.NodeScore)

Example 19 with RelationshipType

use of org.neo4j.graphdb.RelationshipType in project neo4j-apoc-procedures by neo4j-contrib.

the class SchemaIndex method related.

@Procedure
@Description("apoc.index.relatedNodes([nodes],label,key,'<TYPE'/'TYPE>'/'TYPE',limit) yield node - schema range scan which keeps index order and adds limit and checks opposite node of relationship against the given set of nodes")
public Stream<NodeResult> related(@Name("nodes") List<Node> nodes, @Name("label") String label, @Name("key") String key, @Name("relationship") String relationship, @Name("limit") long limit) throws SchemaRuleNotFoundException, IndexNotFoundKernelException, IOException, DuplicateSchemaRuleException, IndexNotApplicableKernelException {
    Set<Node> nodeSet = new HashSet<>(nodes);
    Pair<RelationshipType, Direction> relTypeDirection = parse(relationship).get(0);
    RelationshipType type = relTypeDirection.first();
    Direction dir = relTypeDirection.other();
    return queryForRange(label, key, Long.MIN_VALUE, Long.MAX_VALUE, 0).filter((node) -> {
        for (Relationship rel : node.getRelationships(dir, type)) {
            Node other = rel.getOtherNode(node);
            if (nodeSet.contains(other)) {
                return true;
            }
        }
        return false;
    }).map(NodeResult::new).limit(limit);
}
Also used : Node(org.neo4j.graphdb.Node) Relationship(org.neo4j.graphdb.Relationship) RelationshipType(org.neo4j.graphdb.RelationshipType) Direction(org.neo4j.graphdb.Direction) Description(org.neo4j.procedure.Description) Procedure(org.neo4j.procedure.Procedure)

Example 20 with RelationshipType

use of org.neo4j.graphdb.RelationshipType in project neo4j by neo4j.

the class TestMultipleStartNodes method myFriendsAsWellAsYourFriends.

@Test
void myFriendsAsWellAsYourFriends() {
    /*
         * Hey, this looks like a futuristic gun or something
         *
         *  (f8)     _----(f1)--(f5)
         *   |      /      /
         * (f7)--(you)--(me)--(f2)--(f6)
         *         |   /   \
         *         (f4)    (f3)
         */
    createGraph("you KNOW me", "you KNOW f1", "you KNOW f4", "me KNOW f1", "me KNOW f4", "me KNOW f2", "me KNOW f3", "f1 KNOW f5", "f2 KNOW f6", "you KNOW f7", "f7 KNOW f8");
    try (Transaction tx = beginTx()) {
        RelationshipType knowRelType = withName("KNOW");
        Node you = getNodeWithName(tx, "you");
        Node me = getNodeWithName(tx, "me");
        String[] levelOneFriends = { "f1", "f2", "f3", "f4", "f7" };
        TraversalDescription levelOneTraversal = tx.traversalDescription().relationships(knowRelType).evaluator(atDepth(1));
        expectNodes(levelOneTraversal.depthFirst().traverse(you, me), levelOneFriends);
        expectNodes(levelOneTraversal.breadthFirst().traverse(you, me), levelOneFriends);
        String[] levelTwoFriends = { "f5", "f6", "f8" };
        TraversalDescription levelTwoTraversal = tx.traversalDescription().relationships(knowRelType).evaluator(atDepth(2));
        expectNodes(levelTwoTraversal.depthFirst().traverse(you, me), levelTwoFriends);
        expectNodes(levelTwoTraversal.breadthFirst().traverse(you, me), levelTwoFriends);
    }
}
Also used : Transaction(org.neo4j.graphdb.Transaction) Node(org.neo4j.graphdb.Node) RelationshipType(org.neo4j.graphdb.RelationshipType) TraversalDescription(org.neo4j.graphdb.traversal.TraversalDescription) Test(org.junit.jupiter.api.Test)

Aggregations

RelationshipType (org.neo4j.graphdb.RelationshipType)147 Node (org.neo4j.graphdb.Node)84 Relationship (org.neo4j.graphdb.Relationship)59 Transaction (org.neo4j.graphdb.Transaction)52 Test (org.junit.Test)35 Test (org.junit.jupiter.api.Test)32 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)20 Direction (org.neo4j.graphdb.Direction)19 Label (org.neo4j.graphdb.Label)18 GraphDatabaseService (org.neo4j.graphdb.GraphDatabaseService)15 InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)15 ArrayList (java.util.ArrayList)13 NotFoundException (org.neo4j.graphdb.NotFoundException)10 Traverser (org.neo4j.graphdb.Traverser)10 HashSet (java.util.HashSet)9 RelationshipRecord (org.neo4j.kernel.impl.nioneo.store.RelationshipRecord)7 GraphDatabaseAPI (org.neo4j.kernel.internal.GraphDatabaseAPI)7 Collection (java.util.Collection)6 HashMap (java.util.HashMap)6 LinkedList (java.util.LinkedList)6