这是我的图表
我正在尝试获取节点的详细信息及其在 java 代码中的关系,下面是我的代码。我能够获取节点的详细信息,但不能获取关系。并且 java 文档没有允许暴露关系的信息和方法。
我的代码
import java.util.List;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Record;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.neo4j.driver.Value;
import org.neo4j.driver.internal.InternalResult;
public class Neo4jTest {
private Driver driver;
public Neo4jTest() {
loadDriver();
}
private void loadDriver() {
driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "Test"));
}
public Result createNodes(String query) {
try (Session session = driver.session())
{
InternalResult result = (InternalResult) session.writeTransaction(tx -> tx.run(query));
return result;
}
}
public List<Record> execute(String query) {
try (Session session = driver.session())
{
Result result = session.run(query);
return result.list();
}
}
public void cleanUp(String object) {
String cleanUpQuery = "match(n:" + object +") detach delete n";
execute(cleanUpQuery);
}
public void printResults(List<Record> results) {
for (Record record : results) {
Value rec = record.get("n");
System.out.print("Record --> [");
for (String key : rec.keys()) {
System.out.print(key + " : " + rec.get(key) + ", ");
}
System.out.println("]");
//TODO: Need to get all Relationship of this particular node
}
}
public static void main(String[] args) {
String createQuery = "create \n" +
"(a:People {name : \"Vivek\", age : 20}), \n" +
"(b:People {name : \"Abdul\", age : 25}), \n" +
"(c:People {name : \"John\", age : 22}),\n" +
"" +
"(a)-[:KNOWS]->(b),\n" +
"(b)-[:FRIEND_OF]->(c),\n" +
"(c)-[:KNOWS]->(a)";
String fetchQuery = "match(n:People) return n";
Neo4jTest obj = new Neo4jTest();
obj.cleanUp("People");
// Create Nodes
obj.createNodes(createQuery);
// Fetch Nodes
List<Record> results = obj.execute(fetchQuery);
// Process Results
obj.printResults(results);
}
}
输出
Record --> [name : "Vivek", age : 20, ]
Record --> [name : "Abdul", age : 25, ]
Record --> [name : "John", age : 22, ]
JavaDoc 链接-> https://neo4j.com/docs/api/java-driver/current/
相关结果对象
org.neo4j.driver.Record;
org.neo4j.driver.Value;
其他详情
Neo4j 社区版 - 3.5.14
Neo4j Java 驱动程序版本 - 4.0.0
更新
(对于cybersam的回答)
neo4j 浏览器中的结果和代码是一样的。
查询输出
MATCH (n:People) WITH COLLECT(n) AS 节点 MATCH (:People)-[r]->(:People) WITH 节点,COLLECT(TYPE(r)) AS rels 返回节点,rels
谢谢你的帮助!