发布于2026-07-27 阅读(0)
扫一扫,手机访问
处理复杂关系数据时,传统关系型数据库往往力不从心,而图数据库正好能填补这个空白。在众多图数据库产品中,百度开源的 HugeGraph 凭借高性能、可扩展和易用性,在国内开发者圈子里逐渐站稳了脚跟。

下面就来完整梳理一下,如何在 Spring Boot 应用中集成 HugeGraph,实现从数据模型设计到图谱分析的全链路功能,并客观分析这套方案的优缺点。
使用 Spring Initializr 创建项目,添加以下依赖:
org.springframework.boot spring-boot-starter-web org.projectlombok lombok true com.baidu.hugegraph hugegraph-client 0.12.0 org.apache.tinkerpop gremlin-driver 3.5.0
在 application.yml 中配置 HugeGraph 连接信息:
spring:
application:
name: hugegraph-analysis
server:
port: 8080
hugegraph:
url: http://localhost:8080
graph: hugegraph
timeout: 30
retry:
count: 3
delay: 1000
import com.baidu.hugegraph.driver.HugeClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HugeGraphConfig {
@Value("${hugegraph.url}")
private String url;
@Value("${hugegraph.graph}")
private String graph;
@Value("${hugegraph.timeout}")
private int timeout;
@Bean
public HugeClient hugeClient() {
return new HugeClient(url, graph, timeout);
}
}
import com.baidu.hugegraph.driver.HugeClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ja vax.annotation.PreDestroy;
@Component
public class HugeGraphConnectionManager {
@Autowired
private HugeClient hugeClient;
public HugeClient getClient() {
return hugeClient;
}
@PreDestroy
public void close() {
try {
if (hugeClient != null) {
hugeClient.close();
}
} catch (Exception e) {
// 忽略关闭异常
}
}
}
import com.baidu.hugegraph.driver.HugeClient;
import com.baidu.hugegraph.structure.constant.T;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class HugeGraphSchemaService {
@Autowired
private HugeGraphConnectionManager connectionManager;
public void createSchema() {
HugeClient client = connectionManager.getClient();
try {
// 创建标签(节点)
createTags(client);
// 创建边类型
createEdges(client);
// 创建索引
createIndexes(client);
} catch (Exception e) {
throw new RuntimeException("Failed to create schema", e);
}
}
private void createTags(HugeClient client) {
// 人员标签
client.schema().createPropertyKey("name").dataType(T.STRING).ifNotExist().execute();
client.schema().createPropertyKey("age").dataType(T.INT).ifNotExist().execute();
client.schema().createPropertyKey("occupation").dataType(T.STRING).ifNotExist().execute();
client.schema().createPropertyKey("location").dataType(T.STRING).ifNotExist().execute();
client.schema().createVertexLabel("Person").properties(
"name", "age", "occupation", "location")
.primaryKeys("name")
.ifNotExist().execute();
// 公司标签
client.schema().createPropertyKey("industry").dataType(T.STRING).ifNotExist().execute();
client.schema().createPropertyKey("foundedYear").dataType(T.INT).ifNotExist().execute();
client.schema().createVertexLabel("Company").properties(
"name", "industry", "foundedYear")
.primaryKeys("name")
.ifNotExist().execute();
// 大学标签
client.schema().createPropertyKey("country").dataType(T.STRING).ifNotExist().execute();
client.schema().createVertexLabel("University").properties(
"name", "country", "foundedYear")
.primaryKeys("name")
.ifNotExist().execute();
}
private void createEdges(HugeClient client) {
// 朋友关系
client.schema().createEdgeLabel("KNOWS").sourceLabel("Person")
.targetLabel("Person").ifNotExist().execute();
// 工作关系
client.schema().createEdgeLabel("WORKS_AT").sourceLabel("Person")
.targetLabel("Company").ifNotExist().execute();
// 学习关系
client.schema().createEdgeLabel("STUDIED_AT").sourceLabel("Person")
.targetLabel("University").ifNotExist().execute();
// 合作关系
client.schema().createEdgeLabel("PARTNERS_WITH").sourceLabel("Company")
.targetLabel("Company").ifNotExist().execute();
}
private void createIndexes(HugeClient client) {
// 为 Person 标签创建索引
client.schema().createIndexLabel("personByName").onVLabel("Person")
.by("name").secondary().ifNotExist().execute();
// 为 Company 标签创建索引
client.schema().createIndexLabel("companyByName").onVLabel("Company")
.by("name").secondary().ifNotExist().execute();
// 为 University 标签创建索引
client.schema().createIndexLabel("universityByName").onVLabel("University")
.by("name").secondary().ifNotExist().execute();
}
}
import lombok.Data;
@Data
public class Person {
private String name;
private int age;
private String occupation;
private String location;
}
@Data
public class Company {
private String name;
private String industry;
private int foundedYear;
}
@Data
public class University {
private String name;
private String country;
private int foundedYear;
}
@Data
public class Edge {
private String source;
private String target;
private String type;
}
import com.baidu.hugegraph.driver.HugeClient;
import com.baidu.hugegraph.structure.graph.Edge;
import com.baidu.hugegraph.structure.graph.Vertex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ja va.util.Map;
@Service
public class HugeGraphBaseService {
@Autowired
private HugeGraphConnectionManager connectionManager;
public HugeClient getClient() {
return connectionManager.getClient();
}
/**
* 添加顶点
*/
public Vertex addVertex(String label, Map properties) {
Vertex vertex = new Vertex(label);
properties.forEach(vertex::property);
return getClient().graph().addVertex(vertex);
}
/**
* 添加边
*/
public Edge addEdge(String label, String sourceVertexId, String targetVertexId) {
Edge edge = new Edge(label)
.source(sourceVertexId)
.target(targetVertexId);
return getClient().graph().addEdge(edge);
}
/**
* 执行 Gremlin 查询
*/
public Object executeGremlin(String gremlin) {
return getClient().gremlin().execute(gremlin);
}
/**
* 按属性查询顶点
*/
public Iterable queryVertices(String label, String propertyKey, Object value) {
return getClient().graph().queryVertices()
.withLabel(label)
.withCondition(propertyKey, value)
.execute();
}
}
import com.baidu.hugegraph.structure.graph.Vertex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ja va.util.HashMap;
import ja va.util.Map;
@Service
public class DataInitializationService {
@Autowired
private HugeGraphBaseService hugeGraphBaseService;
public void initializeData() {
// 添加人员
Map aliceProps = new HashMap<>();
aliceProps.put("name", "Alice");
aliceProps.put("age", 30);
aliceProps.put("occupation", "Software Engineer");
aliceProps.put("location", "San Francisco");
Vertex alice = hugeGraphBaseService.addVertex("Person", aliceProps);
Map bobProps = new HashMap<>();
bobProps.put("name", "Bob");
bobProps.put("age", 28);
bobProps.put("occupation", "Product Manager");
bobProps.put("location", "Seattle");
Vertex bob = hugeGraphBaseService.addVertex("Person", bobProps);
Map charlieProps = new HashMap<>();
charlieProps.put("name", "Charlie");
charlieProps.put("age", 32);
charlieProps.put("occupation", "Data Scientist");
charlieProps.put("location", "Boston");
Vertex charlie = hugeGraphBaseService.addVertex("Person", charlieProps);
// 添加公司
Map googleProps = new HashMap<>();
googleProps.put("name", "Google");
googleProps.put("industry", "Technology");
googleProps.put("foundedYear", 1998);
Vertex google = hugeGraphBaseService.addVertex("Company", googleProps);
Map microsoftProps = new HashMap<>();
microsoftProps.put("name", "Microsoft");
microsoftProps.put("industry", "Technology");
microsoftProps.put("foundedYear", 1975);
Vertex microsoft = hugeGraphBaseService.addVertex("Company", microsoftProps);
// 添加大学
Map harvardProps = new HashMap<>();
harvardProps.put("name", "Harvard University");
harvardProps.put("country", "USA");
harvardProps.put("foundedYear", 1636);
Vertex harvard = hugeGraphBaseService.addVertex("University", harvardProps);
Map stanfordProps = new HashMap<>();
stanfordProps.put("name", "Stanford University");
stanfordProps.put("country", "USA");
stanfordProps.put("foundedYear", 1885);
Vertex stanford = hugeGraphBaseService.addVertex("University", stanfordProps);
// 添加关系
// 朋友关系
hugeGraphBaseService.addEdge("KNOWS", alice.id(), bob.id());
hugeGraphBaseService.addEdge("KNOWS", alice.id(), charlie.id());
hugeGraphBaseService.addEdge("KNOWS", bob.id(), alice.id());
hugeGraphBaseService.addEdge("KNOWS", charlie.id(), alice.id());
// 工作关系
hugeGraphBaseService.addEdge("WORKS_AT", alice.id(), google.id());
hugeGraphBaseService.addEdge("WORKS_AT", bob.id(), microsoft.id());
hugeGraphBaseService.addEdge("WORKS_AT", charlie.id(), google.id());
// 学习关系
hugeGraphBaseService.addEdge("STUDIED_AT", alice.id(), harvard.id());
hugeGraphBaseService.addEdge("STUDIED_AT", bob.id(), stanford.id());
hugeGraphBaseService.addEdge("STUDIED_AT", charlie.id(), harvard.id());
// 合作关系
hugeGraphBaseService.addEdge("PARTNERS_WITH", google.id(), microsoft.id());
}
}
import com.baidu.hugegraph.driver.HugeClient;
import com.baidu.hugegraph.structure.graph.Vertex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ja va.util.ArrayList;
import ja va.util.HashMap;
import ja va.util.List;
import ja va.util.Map;
@Service
public class GraphAnalysisService {
@Autowired
private HugeGraphBaseService hugeGraphBaseService;
/**
* 查找人与人之间的最短路径
*/
public Map findShortestPath(String name1, String name2) {
String gremlin = String.format(
"g.V().has('Person', 'name', '%s').repeat(out().simplePath()).until(has('Person', 'name', '%s')).limit(1).path()",
name1, name2
);
Object result = hugeGraphBaseService.executeGremlin(gremlin);
if (result == null || !(result instanceof List)) {
return Map.of("connected", false, "message", "No path found");
}
List> paths = (List>) result;
if (paths.isEmpty()) {
return Map.of("connected", false, "message", "No path found");
}
List pathNames = new ArrayList<>();
// 解析路径结果
// 注意:实际解析需要根据 HugeGraph 返回的具体格式调整
return Map.of(
"connected", true,
"path", pathNames,
"pathLength", pathNames.size() - 1
);
}
/**
* 查找共同朋友
*/
public List findCommonFriends(String name1, String name2) {
String gremlin = String.format(
"g.V().has('Person', 'name', '%s').out('KNOWS').where(
__.in('KNOWS').has('Person', 'name', '%s')
).values('name')",
name1, name2
);
Object result = hugeGraphBaseService.executeGremlin(gremlin);
if (result == null || !(result instanceof List)) {
return new ArrayList<>();
}
List> friends = (List>) result;
List commonFriends = new ArrayList<>();
for (Object friend : friends) {
if (friend instanceof String) {
commonFriends.add((String) friend);
}
}
return commonFriends;
}
/**
* 分析公司网络
*/
public Map analyzeCompanyNetwork(String companyName) {
// 查找直接合作伙伴
String partnersGremlin = String.format(
"g.V().has('Company', 'name', '%s').out('PARTNERS_WITH').values('name')",
companyName
);
Object partnersResult = hugeGraphBaseService.executeGremlin(partnersGremlin);
List partners = new ArrayList<>();
if (partnersResult instanceof List) {
for (Object partner : (List>) partnersResult) {
if (partner instanceof String) {
partners.add((String) partner);
}
}
}
// 查找员工
String employeesGremlin = String.format(
"g.V().has('Company', 'name', '%s').in('WORKS_AT').values('name')",
companyName
);
Object employeesResult = hugeGraphBaseService.executeGremlin(employeesGremlin);
List employees = new ArrayList<>();
if (employeesResult instanceof List) {
for (Object employee : (List>) employeesResult) {
if (employee instanceof String) {
employees.add((String) employee);
}
}
}
return Map.of(
"company", companyName,
"partners", partners,
"employees", employees
);
}
/**
* 分析大学人才流向
*/
public Map analyzeUniversityTalentFlow(String universityName) {
String gremlin = String.format(
"g.V().has('University', 'name', '%s').in('STUDIED_AT').out('WORKS_AT').groupCount().by('name')",
universityName
);
Object result = hugeGraphBaseService.executeGremlin(gremlin);
Map companyEmployeeCount = new HashMap<>();
if (result instanceof Map) {
((Map, ?>) result).forEach((key, value) -> {
if (key instanceof String && value instanceof Number) {
companyEmployeeCount.put((String) key, ((Number) value).longValue());
}
});
}
return Map.of(
"university", universityName,
"talentFlow", companyEmployeeCount
);
}
/**
* 分析个人社交网络影响力
*/
public Map analyzePersonInfluence(String name) {
// 查找直接朋友
String directFriendsGremlin = String.format(
"g.V().has('Person', 'name', '%s').out('KNOWS').values('name')",
name
);
Object directFriendsResult = hugeGraphBaseService.executeGremlin(directFriendsGremlin);
List directFriends = new ArrayList<>();
if (directFriendsResult instanceof List) {
for (Object friend : (List>) directFriendsResult) {
if (friend instanceof String) {
directFriends.add((String) friend);
}
}
}
// 查找二度朋友
String friendsOfFriendsGremlin = String.format(
"g.V().has('Person', 'name', '%s').out('KNOWS').out('KNOWS').dedup().values('name')",
name
);
Object friendsOfFriendsResult = hugeGraphBaseService.executeGremlin(friendsOfFriendsGremlin);
List friendsOfFriends = new ArrayList<>();
if (friendsOfFriendsResult instanceof List) {
for (Object friend : (List>) friendsOfFriendsResult) {
if (friend instanceof String) {
friendsOfFriends.add((String) friend);
}
}
}
// 计算网络中心度
int networkCentrality = directFriends.size() + friendsOfFriends.size();
return Map.of(
"person", name,
"directFriendsCount", directFriends.size(),
"totalNetworkSize", networkCentrality,
"friends", directFriends
);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ja va.util.Map;
@RestController
@RequestMapping("/api/graph")
public class GraphAnalysisController {
@Autowired
private HugeGraphSchemaService schemaService;
@Autowired
private DataInitializationService dataInitializationService;
@Autowired
private GraphAnalysisService graphAnalysisService;
@PostMapping("/init/schema")
public ResponseEntity initializeSchema() {
schemaService.createSchema();
return ResponseEntity.ok("Schema created successfully");
}
@PostMapping("/init/data")
public ResponseEntity initializeData() {
dataInitializationService.initializeData();
return ResponseEntity.ok("Data initialized successfully");
}
@GetMapping("/persons/connection")
public ResponseEntity
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ja va.util.ArrayList;
import ja va.util.List;
import ja va.util.Map;
@Service
public class PathAnalysisService {
@Autowired
private HugeGraphBaseService hugeGraphBaseService;
/**
* 查找所有路径
*/
public List> findAllPaths(String startName, String endName, int maxDepth) {
String gremlin = String.format(
"g.V().has('Person', 'name', '%s').repeat(out().simplePath()).times(%d).until(has('Person', 'name', '%s')).path()",
startName, maxDepth, endName
);
Object result = hugeGraphBaseService.executeGremlin(gremlin);
List> paths = new ArrayList<>();
if (result instanceof List) {
for (Object pathObj : (List>) result) {
// 解析路径结果
// 注意:实际解析需要根据 HugeGraph 返回的具体格式调整
Map pathInfo = new ja va.util.HashMap<>();
pathInfo.put("nodes", new ArrayList<>());
pathInfo.put("length", 0);
paths.add(pathInfo);
}
}
return paths;
}
/**
* 查找最短路径
*/
public Map findShortestPath(String startName, String endName) {
String gremlin = String.format(
"g.V().has('Person', 'name', '%s').repeat(out().simplePath()).until(has('Person', 'name', '%s')).path().order(local).by(count(local)).limit(1)",
startName, endName
);
Object result = hugeGraphBaseService.executeGremlin(gremlin);
if (result == null || !(result instanceof List)) {
return Map.of("found", false, "message", "No path found");
}
List> paths = (List>) result;
if (paths.isEmpty()) {
return Map.of("found", false, "message", "No path found");
}
// 解析路径结果
// 注意:实际解析需要根据 HugeGraph 返回的具体格式调整
return Map.of(
"found", true,
"path", new ArrayList<>(),
"length", 0
);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ja va.util.ArrayList;
import ja va.util.HashMap;
import ja va.util.List;
import ja va.util.Map;
@Service
public class CommunityDetectionService {
@Autowired
private HugeGraphBaseService hugeGraphBaseService;
/**
* 使用 Louvain 算法检测社区
*/
public Map> detectCommunities() {
// 运行 Louvain 算法
String gremlin = "g.V().hasLabel('Person').as('p').group().by('community').by('p.name')";
// 注意:实际的 Louvain 算法调用需要根据 HugeGraph 的具体实现调整
Object result = hugeGraphBaseService.executeGremlin(gremlin);
Map> communities = new HashMap<>();
if (result instanceof Map) {
((Map, ?>) result).forEach((key, value) -> {
if (key instanceof Number && value instanceof List) {
int communityId = ((Number) key).intValue();
List members = new ArrayList<>();
for (Object member : (List>) value) {
if (member instanceof String) {
members.add((String) member);
}
}
communities.put(communityId, members);
}
});
}
return communities;
}
/**
* 分析社区结构
*/
public Map analyzeCommunityStructure() {
Map> communities = detectCommunities();
int totalCommunities = communities.size();
int totalMembers = communities.values().stream().mapToInt(List::size).sum();
return Map.of(
"totalCommunities", totalCommunities,
"totalMembers", totalMembers,
"communities", communities
);
}
}
Docker Compose 配置:
version: '3'
services:
hugegraph-server:
image: hugegraph/hugegraph-server:0.12.0
container_name: hugegraph-server
ports:
- "8080:8080"
- "18080:18080"
environment:
- JA VA_OPTS=-Xms2G -Xmx4G
volumes:
- ./hugegraph/data:/var/lib/hugegraph/data
- ./hugegraph/conf:/etc/hugegraph
spring-app:
build: .
container_name: spring-app
ports:
- "8081:8080"
environment:
- HUGEGRAPH_URL=http://hugegraph-server:8080
- HUGEGRAPH_GRAPH=hugegraph
depends_on:
- hugegraph-server
HugeGraph 提供了 JMX 指标,可以使用 Prometheus 和 Grafana 进行监控:
数据模型设计:
查询优化:
存储后端选择:
性能监控:
安全考虑:
从环境搭建到数据模型,再到业务服务的实现,这套方案覆盖了 Spring Boot 集成 HugeGraph 的完整链路。具体包括:
HugeGraph 作为百度开源的国产图数据库,在处理中等规模图数据时表现相当不错,尤其适合国内企业。虽然生态和工具方面还有提升空间,但开源免费、多存储后端支持和国产化优势,让它成为图数据库选型中一个值得认真考虑的选项。
基于上述方案,开发者可以快速上手构建基于 HugeGraph 的图谱分析应用,为复杂关系数据的处理提供一条切实可行的技术路径。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8