欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

neo4j简单操作

程序员文章站 2022-06-08 16:41:24
...
Neo4j是一个嵌入式,基于磁盘的,支持完整事务的Java持久化引擎,它在图像中而不是表中存储数据。
我已在电脑上安装并启动了neo4j,简单连接测试下


/**
 * 關係枚舉
 * @author zhangk
 *
 */
public enum FirstRelationshipTypes implements RelationshipType {
    FIRST
}


    /**
     * 獲得數據庫管理類
     * @param graphPath
     * @return
     */
    public static GraphDatabaseService getDbService(String graphPath) {
        return new EmbeddedGraphDatabase(graphPath);
    }

    public static void createData(String graphPath) {
        GraphDatabaseService db = getDbService(graphPath);
        registerShutdownHook(db);  
        Transaction tx = db.beginTx();  
        try {
            Node firstNode = db.createNode();
            Node secondNode = db.createNode();
            firstNode.setProperty("name", "zhang");
            secondNode.setProperty("name", "kai");
            // 連接2個節點
            firstNode.createRelationshipTo(secondNode, FirstRelationshipTypes.FIRST);
            String zhangkai = firstNode.getProperty("name") + " " + secondNode.getProperty("name");
            System.out.println(zhangkai);
            //Relationship relationship = firstNode.getSingleRelationship(FirstRelationshipTypes.FIRST, Direction.OUTGOING);
            Iterable<Relationship> rls = firstNode.getRelationships();
            for (Relationship relationship : rls) {
                System.out.println(relationship.getId());  
                System.out.println(relationship.getEndNode().getProperty("name"));  
                System.out.println(relationship.getStartNode().getProperty("name"));  
                relationship.delete(); 
            }
             
//            firstNode.delete();  
//            secondNode.delete();  
            tx.success();  
        } catch(Exception e) {
            tx.finish();
        }
        System.out.println("Shutting down database ...");  
        db.shutdown();
    }


    /**
     *  实时监测服务状态
     *  Registers a shutdown hook for the Neo4j instance so that it  
     *  shuts down nicely when the VM exits (even if you "Ctrl-C" the  
     *  running example before it's completed)  
     *  @param graphDb
     */
    private static void registerShutdownHook(final GraphDatabaseService graphDb) {  

        Runtime.getRuntime().addShutdownHook(new Thread() {  
            @Override  
            public void run() {  
                graphDb.shutdown();  
            }  
        });  
    }  


    private static final String GPATH = "graph.db"; // 數據庫地址

    public static void main(String[] args) {
        createData(GPATH);
    }