Neo4j 常见功能详解及 Spring Cloud 集成代码展示
Neo4j 是领先的图数据库,特别适合处理高度互联的数据。以下是核心功能详解及 Spring Cloud 集成方案:
一、Neo4j 核心功能详解
1. 图数据模型
- 节点(Nodes):表示实体(如用户、产品)
- 关系(Relationships):连接节点(如 FRIEND_OF、PURCHASED)
- 属性(Properties):节点和关系的键值对
- 标签(Labels):节点分类(如
:Person
、:Product
)
2. Cypher 查询语言
// 创建节点和关系
CREATE (alice:Person {name: 'Alice', age: 30})
CREATE (bob:Person {name: 'Bob', age: 28})
CREATE (alice)-[:FRIEND {since: '2020'}]->(bob)
// 复杂查询:查找Alice的朋友的朋友
MATCH (alice:Person {name: 'Alice'})-[:FRIEND]->(friend)-[:FRIEND]->(fof)
RETURN fof.name
3. 索引与约束
// 创建索引
CREATE INDEX FOR (p:Person) ON (p.email)
// 唯一约束
CREATE CONSTRAINT ON (p:Person) ASSERT p.id IS UNIQUE
4. 路径查询
// 查找最短路径
MATCH path = shortestPath(
(a:Person {name: 'Alice'})-[*..6]-(b:Person {name: 'David'})
)
RETURN path
5. 图算法
算法类型 | 用途 | 调用示例 |
---|---|---|
PageRank | 影响力分析 | CALL gds.pageRank.stream() |
Louvain | 社区检测 | CALL gds.louvain.stream() |
最短路径 | 路径优化 | CALL gds.shortestPath.dijkstra() |
6. ACID 事务
- 完全支持 ACID 事务
- 写操作自动包装在事务中
- 支持显式事务管理
二、Spring Cloud 集成 Neo4j
1. 依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
2. 配置连接
application.yml
:
spring:
data:
neo4j:
uri: bolt://localhost:7687
authentication:
username: neo4j
password: yourpassword
database: neo4j # 多数据库支持(Neo4j 4.0+)
3. 实体类映射
@Node("Person")
public class Person {
@Id @GeneratedValue
private Long id;
@Property("full_name")
private String name;
private Integer age;
@Relationship(type = "FRIEND", direction = Direction.OUTGOING)
private List<Person> friends = new ArrayList<>();
@Relationship(type = "PURCHASED")
private List<Purchase> purchases;
// Getters/Setters
}
@RelationshipProperties
public class Purchase {
@Id @GeneratedValue
private Long id;
@TargetNode
private Product product;
@Property("purchase_date")
private LocalDate date;
}
4. Repository 接口
public interface PersonRepository extends Neo4jRepository<Person, Long> {
// 派生查询
List<Person> findByName(String name);
// @Query 注解查询
@Query("MATCH (p:Person)-[:FRIEND]->(friend) WHERE p.name = $name RETURN friend")
List<Person> findFriendsByName(String name);
// 分页查询
@Query("MATCH (p:Person) RETURN p")
Page<Person> findAllPeople(Pageable pageable);
}
5. 复杂查询 - Neo4jTemplate
@Autowired
private Neo4jTemplate neo4jTemplate;
public List<Person> findMutualFriends(String person1, String person2) {
String cypher = "MATCH (p1:Person {name: $name1})-[:FRIEND]->(mutual)<-[:FRIEND]-(p2:Person {name: $name2}) "
+ "RETURN mutual";
Map<String, Object> parameters = Map.of("name1", person1, "name2", person2);
return neo4jTemplate.findAll(cypher, parameters, Person.class);
}
6. 事务管理
@Service
public class SocialNetworkService {
@Autowired
private Neo4jTemplate neo4jTemplate;
@Transactional
public void createFriendship(Long personId1, Long personId2) {
String cypher = "MATCH (p1), (p2) WHERE id(p1) = $id1 AND id(p2) = $id2 "
+ "CREATE (p1)-[:FRIEND {since: date()}]->(p2)";
Map<String, Object> params = Map.of("id1", personId1, "id2", personId2);
neo4jTemplate.execute(cypher, params);
}
}
7. 图算法集成
public List<Map<String, Object>> recommendProducts(Long userId) {
String cypher = "CALL gds.pageRank.stream({ "
+ " nodeQuery: 'MATCH (p:Person) RETURN id(p) AS id', "
+ " relationshipQuery: 'MATCH (p1:Person)-[:PURCHASED]->()<-[:PURCHASED]-(p2:Person) "
+ " RETURN id(p1) AS source, id(p2) AS target', "
+ " maxIterations: 20 "
+ "}) "
+ "YIELD nodeId, score "
+ "WHERE nodeId = $userId "
+ "RETURN score";
return neo4jTemplate.findAll(cypher, Map.of("userId", userId), Map.class);
}
8. 事件监听
@Component
public class PersonEventListener {
@EventListener
public void handleBeforeSave(BeforeSaveEvent<Person> event) {
Person person = event.getEntity();
if (person.getAge() == null) {
person.setAge(18); // 设置默认年龄
}
}
}
9. 分页与排序
public Page<Person> getPeopleByCity(String city, int page, int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by("name"));
return personRepository.findByAddressCity(city, pageable);
}
三、性能优化策略
-
索引优化
@Node("Person") @CompositeProperty(names = {"firstName", "lastName"}) public class Person { // 自动创建复合索引 }
-
查询优化
- 使用
PROFILE
分析查询性能 - 避免笛卡尔积操作
- 限制路径长度
[*..5]
- 使用
-
连接池配置
spring: data: neo4j: connection: pool: max-connection-pool-size: 100 max-connection-lifetime: 1h
-
批量操作
@Transactional public void batchInsert(List<Person> persons) { persons.forEach(neo4jTemplate::save); }
四、集群与高可用
1. 因果集群(Causal Clustering)
spring:
data:
neo4j:
uri: bolt+routing://core1:7687
routing-policy: read
2. 多数据中心
@Configuration
public class Neo4jConfig {
@Bean
public Driver driver() {
return GraphDatabase.driver(
"neo4j://core1:7687",
AuthTokens.basic("neo4j", "password"),
Config.builder()
.withResolver(address ->
List.of(
new BoltServerAddress("dc1-core1", 7687),
new BoltServerAddress("dc2-core1", 7687)
))
.build()
);
}
}
五、安全实践
-
RBAC 控制
CREATE ROLE analyst GRANT MATCH {*} ON GRAPH * TO analyst
-
属性加密
@Node("User") public class User { @Encrypted private String ssn; // 自动加密存储 }
-
审计日志
@Node("Person") public class Person extends Auditable<String> { // 自动添加创建时间/修改时间 }
六、监控与运维
-
健康检查
management: endpoints: web: exposure: include: health,info,metrics health: neo4j: enabled: true
-
性能监控
@Autowired private Driver driver; public void monitor() { try (Session session = driver.session()) { Result result = session.run("CALL dbms.listQueries()"); result.stream().forEach(record -> { System.out.println("Query: " + record.get("query")); }); } }
-
备份恢复
# 在线备份 neo4j-admin backup --backup-dir=/backups --name=graphdb # 恢复 neo4j-admin restore --from=/backups/graphdb
生产建议:
- 使用因果集群实现高可用
- 定期执行数据库一致性检查
- 启用查询日志监控慢查询
- 使用 APOC 扩展库增强功能
- 实施滚动升级策略
七、常见问题解决
-
连接泄漏
@Bean(destroyMethod = "close") public Driver neo4jDriver() { return GraphDatabase.driver(uri, auth); }
-
内存溢出
# 增加JVM堆内存 JAVA_OPTS: "-Xmx4G -Xms1G"
-
长路径查询优化
MATCH path = (start)-[:LINK*1..10]->(end) UNWIND nodes(path) AS node WITH DISTINCT node RETURN node
-
版本兼容性
Spring Boot Neo4j Driver Neo4j 版本 2.7.x 4.4.x 4.4.x 3.0.x 5.x 5.x
以上内容涵盖了 Neo4j 的核心功能、Spring Cloud 集成方案、性能优化策略和生产实践,为构建高效图应用提供全面指导。