neo4j 入门实例

 

 

neo4j 2.0.1实例

 

package com.neo4j.demo1;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;


public class HelloWorldTest {
	
	private static enum RelTypes implements RelationshipType{
		KNOWS
	};
	
	GraphDatabaseService graphDb;
	Node firstNode;
	Node secondNode;
	Relationship relationship;
	

	private static final String DB_PATH = "demo1/db1";//"neo4j-db";//

	public static void main(String[] args) {
		HelloWorldTest hwt = new HelloWorldTest();
		hwt.run();
	}
	
	public void run() {
		//创建连接,生成图
		GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
		registerShutdownHook( graphDb );
		//创建事务,
		Transaction tx = graphDb.beginTx();
		try {
			//添加节点
			firstNode = graphDb.createNode();
			firstNode.setProperty("message", "Hello,");
			secondNode = graphDb.createNode();
			secondNode.setProperty("message", "World!");
			relationship = firstNode.createRelationshipTo(secondNode, RelTypes.KNOWS);
			relationship.setProperty("message", "brave neo4j");
			
			print();
			
			delete();
			tx.success();//提交
		} finally{
			tx.finish();
			graphDb.shutdown();
		}
	}
	
	private void delete(){
		firstNode.getSingleRelationship(RelTypes.KNOWS, Direction.OUTGOING).delete();
		firstNode.delete();
		secondNode.delete();
	}
	
	private void print() {
		System.out.println(firstNode.getProperty("message"));
		System.out.println(relationship.getProperty("message"));
		System.out.println(secondNode.getProperty("message"));
	}

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


}

 

你可能感兴趣的:(实例,neo4j)