使用java从neo4j数据库查询两个节点

时间:2015-03-24 10:25:24

标签: java neo4j

我是Neo4j的新手,我想查询一个只包含节点的Neo4j数据库,以便根据我已有的2个列表在它们之间创建链接。

例如,我希望将List A中名称的节点与名称来自List B的节点连接起来。

这是我写的代码:

public class Main {

    public static void main(String[] args) {

        GraphDatabaseFactory graphDbFactory = new GraphDatabaseFactory();
        GraphDatabaseService graphDb = graphDbFactory.newEmbeddedDatabase("C:\\Zakaria\\NeoTests\\Tetralecture");

        ExecutionEngine execEngine = new ExecutionEngine(graphDb);

/* Here is a loop to read from listA and listB so no need to worry about them */

        try (Transaction ignored = graphDb.beginTx()) {
            String query = "MATCH (auteur1:AUTEUR{Name:'" + listA.get(i) + "'}), (auteur2:AUTEUR{Name:'" + listB.get(j) + "'}) return auteur1, auteur2";
            ExecutionResult execResult = execEngine.execute(query);
            Iterator<Node> aut_column = execResult.columnAs("auteur1");
            for(Node node : IteratorUtil.asIterable(aut_column)) {
                String nodeResult = node + " : " + node.getProperty("Name");
                System.out.println(nodeResult);
            }
        }

    }

}

此示例仅显示一个colunm auteur1的一个作者列表,我希望能够显示它们。

如果我能做到这一点,我认为操纵两个列表中的节点并在它们之间创建链接会更容易。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这对你有用吗?

public class Main {

    public static void main(String[] args) {

        GraphDatabaseFactory graphDbFactory = new GraphDatabaseFactory();
        GraphDatabaseService graphDb = graphDbFactory.newEmbeddedDatabase("C:\\Zakaria\\NeoTests\\Tetralecture");

        ExecutionEngine execEngine = new ExecutionEngine(graphDb);

/* Here is a loop to read from listA and listB so no need to worry about them */

        try (Transaction ignored = graphDb.beginTx()) {
            String query = "MATCH (auteur1:AUTEUR{Name:'" + listA.get(i) + "'}), (auteur2:AUTEUR{Name:'" + listB.get(j) + "'}) return auteur1, auteur2";
            ExecutionResult execResult = execEngine.execute(query);
            for(Map<String, Object> row : execResult) {
                final Node node1 = (Node)row.get("auteur1");
                final Node node2 = (Node)row.get("auteur2");
                String nodeResult = node1 + " : " + node1.getProperty("Name") + "; " + node2 + " : " + node2.getProperty("Name");
                System.out.println(nodeResult);
            }
        }

    }

}