遍历的路径

package com.fly.demo;


import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.traversal.*;
import org.neo4j.io.fs.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import static org.neo4j.graphdb.RelationshipType.withName;

/**
 * 遍历的路径
 */
public class OrderedPath {
    private static final File DB_PATH = new File("demo/neo4j-orderedpath-db");
    private static GraphDatabaseService graphDb;
    private static final RelationshipType
            R1 = withName("R1"),
            R2 = withName("R2"),
            R3 = withName("R3"),
            R4 = withName("R4"),
            R5 = withName("R5");

    public OrderedPath() throws IOException {
        FileUtils.deleteRecursively(DB_PATH);
        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
    }

    public static void main(String...args) throws IOException {
        OrderedPath op = new OrderedPath();
        System.out.println(op.printPaths(op.findPaths(), op.createTheGraph()));
        op.shutdownGraph();
    }

    public Node createTheGraph(){
        try (Transaction tx = graphDb.beginTx()){
            Node A = graphDb.createNode();
            Node B = graphDb.createNode();
            Node C = graphDb.createNode();
            Node D = graphDb.createNode();
            Node E = graphDb.createNode();

            A.setProperty("name", "A");
            B.setProperty("name", "B");
            C.setProperty("name", "C");
            D.setProperty("name", "D");
            E.setProperty("name", "E");

            A.createRelationshipTo(B, R1);
            B.createRelationshipTo(C, R2);
            C.createRelationshipTo(D, R3);
            A.createRelationshipTo(C, R2);
            C.createRelationshipTo(E, R5);
            D.createRelationshipTo(E, R4);

            tx.success();
            return A;
        }
    }

    public TraversalDescription findPaths() {
        // 遍历的路径
        final ArrayList<RelationshipType> orderPaths = new ArrayList<>();
//        orderPaths.add(R1);
//        orderPaths.add(R2);
//        orderPaths.add(R3);

        orderPaths.add(R2);
        orderPaths.add(R5);
        return graphDb.traversalDescription().evaluator(path -> {
            if (path.length() == 0){
                return Evaluation.EXCLUDE_AND_CONTINUE; //排除并继续
            }
            RelationshipType expectedType = orderPaths.get(path.length() - 1);
            boolean isExpectedType = path.lastRelationship().isType(expectedType);
            boolean included = path.length() == orderPaths.size() && isExpectedType;
            boolean continued = path.length() < orderPaths.size() && isExpectedType;
            return Evaluation.of(included, continued);
        }).uniqueness(Uniqueness.NODE_PATH);// 访问节点路径的唯一性
    }

    String printPaths(TraversalDescription td, Node A) {
        try (Transaction tx = graphDb.beginTx()) {
            StringBuilder output = new StringBuilder();
            Traverser traverser = td.traverse(A);
            Paths.PathDescriptor<Path> pathPrinter = new Paths.PathDescriptor<Path>() {
                private final String nodePropertyKey = "name";

                // 节点表示
                @Override
                public String nodeRepresentation(Path path, Node node) {
                    return "(" + node.getProperty(nodePropertyKey, "") + ")";
                }

                // 关系表示
                @Override
                public String relationshipRepresentation(Path path, Node from, Relationship relationship) {
                    String prefix = "--", suffix = "--";
                    if (from.equals(relationship.getEndNode())) {
                        prefix = "<--";
                    } else {
                        suffix = "-->";
                    }
                    return prefix + "[" + relationship.getType().name() + "]" + suffix;
                }
            };
            for (Path path : traverser) {
                output.append(Paths.pathToString(path, pathPrinter));
            }
            output.append("\n");
            return output.toString();
        }
    }

    public void shutdownGraph() {
        try {
            if (graphDb != null) {
                graphDb.shutdown();
            }
        } finally {
            graphDb = null;
        }
    }
}

posted @ 2022-03-29 16:07  fly_bk  阅读(44)  评论(0编辑  收藏  举报