当前位置:首页 > 开发 > 系统架构 > 架构 > 正文

neo4j 入门实例

发表于: 2014-02-14   作者:blackproof   来源:转载   浏览:
摘要:     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

 

 

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 入门实例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号