正经学徒,佛系记录,不搞事情
官网结合java的使用方式:https://neo4j.com/developer/java/
这里使用springboot
第一步:引入pom
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.4.4</version>
</dependency>
第二步:配置yml
neo4j:
url: bolt://127.0.0.1:7687
username: neo4j
password: 123456
第三步:获取neo4j驱动
更多详细的初始化配置参考api:https://neo4j.com/docs/api/java-driver/current/org/neo4j/driver/v1/GraphDatabase.html
@Configuration
public class Neo4jConf {
//从yml文件获取配置信息
@Value("${neo4j.url}")
private String url;
@Value("${neo4j.username}")
private String username;
@Value("${neo4j.password}")
private String password;
@Bean(name = "driver")
public Driver initDriver() {
Driver driver;
try {
//neo4j地址 账号 密码
driver = GraphDatabase.driver(url, AuthTokens.basic(username, password));
} catch (Exception e) {
throw new RuntimeException(e);
}
return driver;
}
}
第四步:创建工具类
@Component
public class Neo4jUtil {
private static Driver driver;
@Autowired
public Neo4jUtil(Driver driver) {
Neo4jUtil.driver = driver;
}
/**
* cql的return返回多种节点match (n)-[edge]-(n) return n,m,edge:限定返回关系时,关系的别名必须“包含”edge
* @param cql 查询语句
* @param lists 和cql的return返回节点顺序对应
* @return List<Map<String,Object>>
*/
public static <T> void getList(String cql, Set<T>... lists) {
//用于给每个Set list赋值
int listIndex = 0;
try {
Session session = driver.session();
StatementResult result = session.run(cql);
List<Record> list = result.list();
for (Record r : list) {
if (r.size() != lists.length) {
System.out.println("节点数和lists数不匹配");
return;
}
}
for (Record r : list) {
for (String index : r.keys()) {
//对于关系的封装
if (index.indexOf("edge") != -1) {
Map<String, Object> map = new HashMap<>();
//关系上设置的属性
map.putAll(r.get(index).asMap());
//外加三个固定属性
map.put("edgeId", r.get(index).asRelationship().id());
map.put("edgeFrom", r.get(index).asRelationship().startNodeId());
map.put("edgeTo", r.get(index).asRelationship().endNodeId());
lists[listIndex++].add((T) map);
}
//对于节点的封装
else {
Map<String, Object> map = new HashMap<>();
//节点上设置的属性
map.putAll(r.get(index).asMap());
//外加一个固定属性
map.put("nodeId", r.get(index).asNode().id());
lists[listIndex++].add((T) map);
}
}
listIndex = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
第五步:调用
@RestController
public class TestController {
@Autowired
private Neo4jUtil neo4jUtil;
@GetMapping("get")
public Map<String, Object> get2(){
Map<String, Object> retMap = new HashMap<>();
//cql语句
String cql = "match (m)-[edge1]-(n) return m,edge1,n";
//待返回的值,与cql return后的值顺序对应
Set<Map<String ,Object>> m = new HashSet<>();
Set<Map<String ,Object>> edge = new HashSet<>();
Set<Map<String ,Object>> n = new HashSet<>();
neo4jUtil.getList(cql,m,edge,n);
retMap.put("m",m);
retMap.put("edge",edge);
retMap.put("n",n);
return retMap;
}
}
该方法支持cql语句后返回多个节点,注:如果需要返回的是关系,必须使用带有edge的别名,可以是edge1、edgePerson......
第六步:结果
粗制滥造,不放git
项目地址:
https://pan.baidu.com/s/1KC8VAQJhPjD_8dzz9-zTHg 提取码: hrb3