加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Neo4j中的定向路径

发布时间:2020-12-15 04:16:23 所属栏目:Java 来源:网络整理
导读:我面临着一个看似简单的问题.我想使用遍历 Java API遍历Neo4j图的节点.但是,我想仅包括所有关系具有相同方向的路径.如果我做的事情 db.traversalDescription().relationships(type,Direction.BOTH) 路径就像 [a]-[:TYPE]-[b]-[:TYPE]-[c] 也包括在内,我不想
我面临着一个看似简单的问题.我想使用遍历 Java API遍历Neo4j图的节点.但是,我想仅包括所有关系具有相同方向的路径.如果我做的事情

db.traversalDescription().relationships(<type>,Direction.BOTH)

路径就像

[a]-[:TYPE]->[b]<-[:TYPE]-[c]

也包括在内,我不想要.我只想要路径

[a]-[:TYPE]->[b]-[:TYPE]->[c]
[a]<-[:TYPE]-[b]<-[:TYPE]-[c]

有人可以帮忙吗?似乎解决方案应该非常简单.

解决方法

详细介绍了Wes的想法.在自定义PathEvaluator中,您需要设置分支状态以记住第一个关系的方向.所有后续访问都会检查最后一个关系是否与方向匹配.在伪代码中:

class SameDirectionPathEvaluator implements PathEvaluator<Direction> {

   public Evaluation evaluate(Path path,BranchState<Direction> state) {
      if (path.length()==0) {
         return Evaluation.EXCLUDE_AND_CONTINUE;
      } else if (path.length()==1) {
         state.setState(getDirectionOfLastRelationship(path));
         return Evaluation.INCLUDE_AND_CONTINUE;
      } else {
         if (state.getState().equals(getDirectionOfLastRelationship(path)) {
            return Evaluation.INCLUDE_AND_CONTINUE;
         } else {
            return Evaluation.EXCLUDE_AND_PRUNE;
         }
      }
   }

   private Direction getDirectionOfLastRelationship(Path path) {
      assert path.length() > 0;
      Direction direction = Direction.INCOMING
      if (path.endNode().equals(path.lastRelationship().getEndNode()) {
        direction = Direction.OUTGOING;
      }
      return direction;
   }

}

请注意我没有编译或测试上面的代码 – 它只是为了草拟这个想法.

UPDATE

似乎有一种更有效的方法来做到这一点.由于遍历在调用赋值器之前使用扩展器,因此在扩展器中实现此行为更有意义:

class ConstantDirectionExpander implements PathExpander<STATE>() {
        @Override
        public Iterable<Relationship> expand(Path path,BranchState<STATE> state) {
            if (path.length()==0) {
                return path.endNode().getRelationships(types);
            } else {
                Direction direction = getDirectionOfLastRelationship(path);
                return path.endNode().getRelationships(direction,types);
            }
        }

        @Override
        public PathExpander<STATE> reverse() {
            return this;
        }

        private Direction getDirectionOfLastRelationship(Path path) {
            assert path.length() > 0;
            Direction direction = Direction.INCOMING;
            if (path.endNode().equals(path.lastRelationship().getEndNode())) {
                direction = Direction.OUTGOING;
            }
            return direction;
        }
    }

在遍历中,您需要使用InitialBranchSate:

TraversersDescription td = graphDatabaseService.traversalDescriptioin().
  .expand(new ConstantDirectionExpander(reltype))
  .traverse(startNode)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读