neo4j连接java目前主要有嵌入式、jdbc和rest api。
嵌入式:使用到的lib包在neo4j下载包的lib里(对于windows,不建议下载exe版,因为不包含代码需要的lib包)
创建节点和关系:
final String DB_PATH = "E:/neo4jdb"; //数据库路径 GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH ); //连接一次比较耗时 Transaction tx = graphDb.beginTx(); //事务 tx.success(); Node firstNode,secondNode; Relationship relationship; firstNode = graphDb.createNode(); //创建一个节点 firstNode.setProperty( "name", "node1" );//指明节点的属性 secondNode = graphDb.createNode(); secondNode.setProperty( "name", "node2" ); relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS ); //创建两个节点间的关系 relationship.setProperty( "weight", 10 ); //设置关系的属性
在创建节点(关系)时如果需要指定类型,则需要声明一个枚举:
private static enum RelTypes implements RelationshipType //节点的类型和关系的类型 { KNOWS }
使用cypher查询数据
ExecutionEngine engine = new ExecutionEngine(this.graphDb); ExecutionResult result = engine.execute("match n return n.name as name;"); ResourceIterator<String> iterator = result.columnAs("name"); //获取某列值,如果不用as XXX,取值的时候要用n.name while(iterator.hasNext()) { System.out.println(iterator.next()); }
查询两点直接的最短路径:目前内嵌式提供多种算法计算最短路径,不过目前只看了shorestPath和dijkstra这两种算法,shorestPath计算两个节点间经过的节点数最小的路径(不考虑节点之间的权重),dijkstra计算两个节点之间权重最小的路径。
//节点之间的最短路径,计算两点之间的经过节点数最小的路径,无关关系的权重 PathFinder<Path> finder = GraphAlgoFactory.shortestPath(Traversal.expanderForTypes(RelTypes.KNOWS, Direction.OUTGOING), 5); Node startNode = this.graphDb.getNodeById(14); Node endNode = this.graphDb.getNodeById(17); //将经过的节点数相同的路径全部查询回来 Iterable<Path> paths = finder.findAllPaths(startNode, endNode); Iterator<Path> iterator = paths.iterator(); Path p; while(iterator.hasNext()) { p = iterator.next(); System.out.println("shortestPath" + p.toString()); System.out.println(p.startNode().getId() + "\t" + p.endNode().getId()); } //取所有路径中的第一条 p = finder.findSinglePath(startNode, endNode); System.out.println("shorestPath singlePath :" + p.toString()); PathFinder<WeightedPath> finder1 = GraphAlgoFactory.dijkstra( Traversal.expanderForTypes( RelTypes.KNOWS, Direction.BOTH ), "weight" ); WeightedPath path = finder1.findSinglePath(startNode, endNode); // Get the weight for the found path System.out.println(path.weight()); System.out.println(path.toString());