java连接neo4j查询,基于driver
public class Neo4jDrivertest {// 驱动程序对象是线程安全的,通常是在应用程序范围内提供的。Driver driver;public Neo4jDrivertest(String uri, String user, String password) {driver = GraphDatabase.driver(uri, AuthTokens.basic(user, p
public class Neo4jDrivertest {
// 驱动程序对象是线程安全的,通常是在应用程序范围内提供的。
Driver driver;
public Neo4jDrivertest(String uri, String user, String password) {
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
/**
* 根据cql语句进行查询节点,关系线等数据
*
* @param cql
* @return
*/
public Map<String, HashSet<Map<String, Object>>> printJSON(String cql) {
Map<String, HashSet<Map<String, Object>>> retuMap = new HashMap<String, HashSet<Map<String, Object>>>();
try {
Session session = driver.session();
StatementResult result = session.run(cql);
HashSet<Map<String, Object>> nodedatas = new HashSet<Map<String, Object>>();// 存放所有的节点数据
HashSet<Map<String, Object>> allrelationships = new HashSet<Map<String, Object>>();// 存放所有的节点数据
while (result.hasNext()) {
Record record = result.next();
Map<String, Object> date = record.asMap();// 这里面存的是这个关系的键值对,其实就是起始节点,关系,结束节点
for (String key : date.keySet()) {
Object object = date.get(key);
InternalPath data = (InternalPath) object;// 强制转换
Iterable<Node> allnodes = data.nodes();
for (Node node : allnodes) {
long nodeid = node.id();
Map<String, Object> nodedatamap = new HashMap<String, Object>();
Map<String, Object> data1 = node.asMap();// 添加节点的属性
for (String key1 : data1.keySet()) {
nodedatamap.put(key1, data1.get(key1));
}
nodedatamap.put("name", nodeid);
nodedatas.add(nodedatamap);
}
Iterable<Relationship> relationships = data.relationships();
Map<String, Object> shipdata = new HashMap<String, Object>();
for (Relationship relationship : relationships) {
Map<String, Object> data1 = relationship.asMap();// 添加关系的属性
for (String key1 : data1.keySet()) {
shipdata.put(key1, data1.get(key1));
}
long source = relationship.startNodeId();// 起始节点id
long target = relationship.endNodeId();// 结束节点Id
shipdata.put("source", source);// 添加起始节点id
shipdata.put("target", target);
}
allrelationships.add(shipdata);
}
}
retuMap.put("nodes", nodedatas);
retuMap.put("relation", allrelationships);
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
} finally {
close();
}
return retuMap;
}
public void close() {
// Closing a driver immediately shuts down all open connections.
driver.close();
}
更多推荐
所有评论(0)