如何排除一些节点

时间:2014-02-26 20:45:00

标签: java neo4j dijkstra

有没有办法根据属性从Neo4j Dijkstra算法中排除某些节点?

我知道,我可以在方法 forTypeAndDirection 中设置允许的版权和方向,但在我的情况下,这对我没有帮助。

我们假设我有以下代码:

try (Transaction tx = graphDb.beginTx()) {

    Node startNode = graphDb.getNodeById(12353);
    Node endNode = graphDb.getNodeById(12356);

    CostEvaluator<Double> costEvaluator = new CostEvaluator<Double>() {
        @Override
        public Double getCost(Relationship relationship, Direction direction) {
        Integer cost = Integer.parseInt(relationship.getProperty("cost").toString());               
            return cost.doubleValue();
        }
    };      

    PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra(
        PathExpanders.forTypeAndDirection( RelationshipTypes.RELATED, Direction.OUTGOING), costEvaluator );

        WeightedPath path = finder.findSinglePath( startNode, endNode );        
        System.out.println(path.length());
        tx.success();
    }
}

当Dijkstra通过属性名称进入节点时:'伦敦'如何停止执行此路径并继续其他地方?

1 个答案:

答案 0 :(得分:1)

我最近遇到了类似的问题,我需要自定义PathExpander来执行一些遍历。我做了类似的事情(我修改了原始代码以适合你的情况,但它仍然可能有问题,所以仔细看看):

final private static class FilteringExpander implements PathExpander {
    private final Direction direction;

    private FilteringExpander(final Direction direction) {
        this.direction = direction;
    }

    public FilteringExpander() {
        this.direction = Direction.OUTGOING;
    }

    @Override
    public Iterable<Relationship> expand(Path neoPath, BranchState state) {
        if (!neoPath.endNode().getProperty("name").equals("London")) {
            return neoPath.endNode().getRelationships(RelationshipTypes.RELATED, direction);
        } else {
            return Collections.emptyList();
        }
    }

    @Override
    public PathExpander reverse() {
        return new FilteringExpander(direction.reverse());
    }
}

希望它足够清楚。如果您有任何问题,请随时问我。