Neo4j 1.9.4 java社区版持久化

时间:2013-11-13 02:44:14

标签: java neo4j persistence

对于我的生活,我无法理解为什么我无法阅读我在neo4j 1.9.4社区版中创建的图表。在eclipse中,我运行以下代码:

public class neo4jtest {

    private GraphDatabaseService graphDb;
    private static final String neo4j_db = "c:/tmp/db/neo4j-new-db";
    private UniqueFactory<Node> nodefactory;
    private static enum RelTypes implements RelationshipType
    {
        FRIEND, FOLLOWER
    }

    public neo4jtest() {

        graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(neo4j_db).
                setConfig( GraphDatabaseSettings.node_keys_indexable, "ScreenName,ID" ).
                setConfig( GraphDatabaseSettings.relationship_keys_indexable, (RelTypes.FRIEND).name()+","+(RelTypes.FOLLOWER).name()).
                setConfig( GraphDatabaseSettings.node_auto_indexing, "true" ).
                setConfig( GraphDatabaseSettings.relationship_auto_indexing, "true" ).
                newGraphDatabase();
        //graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(neo4j_db);
        registerShutdownHook( graphDb );
        nodefactory = new UniqueFactory.UniqueNodeFactory( graphDb, "users" )
        {
            @Override
            protected void initialize( Node created, Map<String, Object> properties )
            {
                created.setProperty( "ScreenName", properties.get( "ScreenName" ) );
            }
        };
    }

    public void exit() {
        graphDb.shutdown();
    }

    public static void main(String[] args) {

        neo4jtest n4 = new neo4jtest();
        String u1 = "Moe";
        //Node unode = n4.createNeo4jGraph(u1);
        n4.exploreNeo4jGraph(u1);
        n4.exit();
    }

    public Node createNeo4jGraph(String uname) {

        Node firstNode;
        Relationship relationship;  
        // build a graph
        try {
            Transaction tx = graphDb.beginTx();
            firstNode = nodefactory.getOrCreate("ScreenName", uname);
            firstNode.setProperty( "ScreenName", uname );
            firstNode.setProperty("ID", 1);
            Node followerNode = nodefactory.getOrCreate("ScreenName", "Larry");
            followerNode.setProperty("ID", 2);  
            relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
            relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
            followerNode = nodefactory.getOrCreate("ScreenName", "Curly");
            followerNode.setProperty("ID", 3);
            relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
            relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
            tx.success();
            return firstNode;
        } catch(Exception ex) {}
        return null;
    }

    private void exploreNeo4jGraph(String scname) {
        // use the auto indexer to lookup node with string name
        // Get the Node auto index
        ReadableIndex<Node> autoNodeIndex = graphDb.index()
                .getNodeAutoIndexer()
                .getAutoIndex();

        Node mainUser = autoNodeIndex.get( "ScreenName", scname ).getSingle();

        if (mainUser==null) {
            // why not use nodefactory to get it?
            System.out.println("Auto indexer did not work");
            mainUser = nodefactory.getOrCreate("ScreenName", scname);
        }
        exploreNeo4jGraph(mainUser);                
    }

    private void exploreNeo4jGraph(Node unode) {
        // explore the nodes and edges in the graph
        if (unode==null) {
            System.err.println("Cannot explore from null node!");
            return;
        }
        long currRels = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllRelationships());
        long currNodes = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllNodes());

        System.out.println("Number of nodes in graph is " + currNodes);
        System.out.println("Number of edges in graph is " + currRels);

        int numberOfFollowers = 0;
        String output = unode.getProperty( "ScreenName" ) + "'s friends:\n";
        Traverser friendsTraverser = getFriends( unode );
        for ( Path friendPath : friendsTraverser )
        {
            output += "At depth " + friendPath.length() + " <= "
                    + friendPath.endNode().getProperty( "ScreenName" ) + "\n";
            numberOfFollowers++;
        }
        output += "Number of friends found: " + numberOfFollowers + "\n";
        System.out.println(output);
}

    private Traverser getFriends(final Node person )
    {
        TraversalDescription td = Traversal.description()
                .breadthFirst()
                .relationships( RelTypes.FRIEND, Direction.INCOMING )
                .evaluator( Evaluators.excludeStartPosition() );
        return td.traverse( person );
    }

    private static void registerShutdownHook( final GraphDatabaseService graphDb )
    {
        // 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 application).
        Runtime.getRuntime().addShutdownHook( new Thread()
        {
            @Override
            public void run()
            {
                graphDb.shutdown();
            }
        } );
    }
}

基本上,我取消注释行

Node unode = n4.createNeo4jGraph(u1);

创建图表。

然后再次使用该行进行评论,以便探索已创建的图表。当我再次运行它时,它不会报告创建的图形。我做错了什么?

谢谢, d

1 个答案:

答案 0 :(得分:0)

我猜你需要关闭交易。来自javadoc: finish()(1.9) 提交或标记此事务以进行回滚,具体取决于先前是否已调用success()failure()