如何在java程序中引入neo4j数据库

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在java程序中引入neo4j数据库相关的知识,希望对你有一定的参考价值。

参考技术A package com.neo4j;
import java.io.File;
import java.io.IOException;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.kernel.Traversal;
import org.neo4j.kernel.impl.util.FileUtils;
import org.neo4j.kernel.impl.util.StringLogger;
import org.neo4j.cypher.ExecutionEngine;
import org.neo4j.cypher.ExecutionResult;
import org.neo4j.graphalgo.PathFinder;
import org.neo4j.graphalgo.GraphAlgoFactory;

public class Example

// private static final String DB_PATH = "target/neo4jexample";
private static final String DB_PATH = "testgraph.db";
private static final String PRIMARY_KEY = "name";
private GraphDatabaseService graphDB;
private Index<Node> nodeIndex;
private long startNodeId;

private static enum RelTypes implements RelationshipType
NEO_NODE,
KNOWS,
CODED_BY


private void clearDB()
try
FileUtils.deleteRecursively(new File(DB_PATH));

catch(IOException e)
throw new RuntimeException(e);



public void createDB()
clearDB();

graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
nodeIndex = graphDB.index().forNodes("nodes");
registerShutdownHook(graphDB);

Transaction tx = graphDB.beginTx();
try
Node startNode = graphDB.createNode();
startNodeId = startNode.getId();

Node thomas = graphDB.createNode();
thomas.setProperty( "name", "Thomas Anderson" );
thomas.setProperty( "age", 29 );
nodeIndex.add(thomas, PRIMARY_KEY, thomas.getProperty("name"));

startNode.createRelationshipTo( thomas, RelTypes.NEO_NODE );

Node trinity = graphDB.createNode();
trinity.setProperty( "name", "Trinity" );
nodeIndex.add(trinity, PRIMARY_KEY, trinity.getProperty("name"));
Relationship rel = thomas.createRelationshipTo( trinity,
RelTypes.KNOWS );
rel.setProperty( "age", "3 days" );
Node morpheus = graphDB.createNode();
morpheus.setProperty( "name", "Morpheus" );
morpheus.setProperty( "rank", "Captain" );
morpheus.setProperty( "occupation", "Total badass" );
nodeIndex.add(morpheus, PRIMARY_KEY, morpheus.getProperty("name"));
thomas.createRelationshipTo( morpheus, RelTypes.KNOWS );
rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS );
rel.setProperty( "age", "12 years" );
Node cypher = graphDB.createNode();
cypher.setProperty( "name", "Cypher" );
cypher.setProperty( "last name", "Reagan" );
nodeIndex.add(cypher, PRIMARY_KEY, cypher.getProperty("name"));
trinity.createRelationshipTo( cypher, RelTypes.KNOWS );
rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS );
rel.setProperty( "disclosure", "public" );
Node smith = graphDB.createNode();
smith.setProperty( "name", "Agent Smith" );
smith.setProperty( "version", "1.0b" );
smith.setProperty( "language", "C++" );
nodeIndex.add(smith, PRIMARY_KEY, smith.getProperty("name"));
rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS );
rel.setProperty( "disclosure", "secret" );
rel.setProperty( "age", "6 months" );
Node architect = graphDB.createNode();
architect.setProperty( "name", "The Architect" );
nodeIndex.add(architect, PRIMARY_KEY, architect.getProperty("name"));
smith.createRelationshipTo( architect, RelTypes.CODED_BY );

tx.success();

finally
tx.finish();



public Traverser getFriends(final Node person)
TraversalDescription td = Traversal.description()
.breadthFirst()
.relationships(RelTypes.KNOWS, Direction.OUTGOING)
.evaluator(Evaluators.excludeStartPosition());
return td.traverse(person);


public void printNodeFriends(Node node)
// Node neo = graphDB.getNodeById(startNodeId)
// .getSingleRelationship(RelTypes.NEO_NODE, Direction.OUTGOING)
// .getEndNode();
int friendsNumbers = 0;
System.out.println(node.getProperty(PRIMARY_KEY) + "'s friends:");
for(Path friendPath: getFriends(node))
System.out.println("At depth " + friendPath.length() + " => "
+ friendPath.endNode().getProperty(PRIMARY_KEY));
friendsNumbers++;

System.out.println("Number of friends found: " + friendsNumbers);


public void printCypherFriends(String name)
graphDB = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
ExecutionEngine engine = new ExecutionEngine(graphDB, StringLogger.logger(DB_PATH));
// ExecutionResult result = engine.execute(
// "start n=node:nodes(name=\"" + name + "\") "
// + "match n-[:KNOWS*..]->f "
// + "return distinct f, f.name");
ExecutionResult result = engine.execute("start n=node(500000) return n;");
System.out.println(result.dumpToString());


public void printThomasFriends()
printNodeFriends(nodeIndex.get(PRIMARY_KEY, "Thomas Anderson").getSingle());


public Iterable<Path> findShortestPath(Node node1, Node node2)
PathFinder<Path> finder = GraphAlgoFactory.shortestPath(
Traversal.expanderForTypes(RelTypes.KNOWS, Direction.OUTGOING), 5);
Iterable<Path> paths = finder.findAllPaths(node1, node2);
return paths;


public void printShortestPaths()
Node node1 = nodeIndex.get(PRIMARY_KEY, "Thomas Anderson").getSingle();
Node node2 = nodeIndex.get(PRIMARY_KEY, "Agent Smith").getSingle();
for(Path shortestPath: findShortestPath(node1, node2))
System.out.println(shortestPath.toString());



private static void registerShutdownHook(final GraphDatabaseService graphDB)
Runtime.getRuntime().addShutdownHook(new Thread()
@Override
public void run()
graphDB.shutdown();

);


private void shutdown()
graphDB.shutdown();


/**
* @param args
*/
public static void main(String[] args)
Example example = new Example();
// example.createDB();
long t1 = System.currentTimeMillis();
// example.printThomasFriends();
example.printCypherFriends("Thomas Anderson");
long t2 = System.currentTimeMillis();
System.out.print(t2-t1);
//example.printShortestPaths();
example.shutdown();


本回答被提问者和网友采纳

如何在Maven项目中引入自己的jar包

Maven 构建的项目都有自己的POM文件 ,而在pom文件中添加自己需要依赖的jar的信息就可以在项目中引入自己需要的依赖jar;

添加方法如下

groupId :是指这个jar在本地仓库的包路径;

artifactId:是这个jar的包名;

version:是这个jar版本号;

scope:scope在maven的依赖管理中主要负责项目的部署他的值有:

默认就是compile,什么都不配置也就是意味着compile。compile表示被依赖项目需要参与当前项目的编译,当然后续的测试,运行周期也参与其中,是一个比较强的依赖。打包的时候通常需要包含进去

scope为test表示依赖项目仅仅参与测试相关的工作,包括测试代码的编译

runntime表示被依赖项目无需参与项目的编译,不过后期的测试和运行周期需要其参与。

provided意味着打包的时候可以不用包进去,别的设施(Web Container)会提供

从参与度来说,也provided相同,不过被依赖项不会从maven仓库抓,而是从本地文件系统拿,一定需要配合systemPath属性使用。

参考技术A 如果是用eclipse或者idea,可以在pom.xml中加入依赖,Maven会根据依赖在中央仓库自动下载

以上是关于如何在java程序中引入neo4j数据库的主要内容,如果未能解决你的问题,请参考以下文章

java 如何引入 jar包?

neo4j:在 java 中发送的有限查询

neo4j如何与其它系统集成

如何从 java 中获取 Neo4j 图形数据库的节点数,我们可以从磁盘存储和重用 graphdb 吗?

Java连接Neo4j的两种方式

neo4j:如何更改数据库存储位置?