SpringBoot内嵌neo4j配置

环境说明

MacOS Apple M1 | Jdk17 | Maven 3.8.5 | SpringBoot 2.6.9 | Neo4j 5.10.0

注:neo4j 内嵌最大的坑就是版本兼容性,所以引入前一定检查 neo4j 与 springboot 版本兼容性,其次 neo4j 各版本间配置使用上,区别也挺大的,本文只针对特定版本,因此建议更多参考官网文档,有最新的配置使用方法。

配置

pom.xml

<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>5.10.0</version>
</dependency>

Configuration

import org.neo4j.dbms.api.DatabaseManagementService;
import org.neo4j.dbms.api.DatabaseManagementServiceBuilder;
import org.neo4j.graphdb.GraphDatabaseService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Path;

import static org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME;

@Configuration
public class Neo4jConfig {

  @Bean
  public GraphDatabaseService graphDatabaseService() {
    // graph.db 为自定义 neo4j 库目录位置
    DatabaseManagementService managementService =
        new DatabaseManagementServiceBuilder(Path.of("graph.db")).build();
    GraphDatabaseService graphDb = managementService.database(DEFAULT_DATABASE_NAME);
    registerShutdownHook(managementService);
    return graphDb;
  }

  private static void registerShutdownHook(final DatabaseManagementService managementService) {
    // Registers a shutdown hook for the Neo4j instance so that it
    // shuts down nicely when the VM exits (even if you "Ctrl-C" the
    // running application).
    Runtime.getRuntime().addShutdownHook(new Thread(() -> managementService.shutdown()));
  }
}

自定义节点 实现通用方法

neo4j 可以对每个图节点自动生成一个唯一 id,也支持通过 @Id 自定义 id

// Node
public class ColumnVertex {
    private String name;
}

// Service
public interface EmbeddedGraphService {
    // 添加图节点以及与上游节点之间的关系
    void addColumnVertex(ColumnVertex currentVertex, ColumnVertex upstreamVertex);
    // 寻找上游节点
    List<ColumnVertex> findUpstreamColumnVertex(ColumnVertex currentVertex);
    // 寻找下游节点
    List<ColumnVertex> findDownstreamColumnVertex(ColumnVertex currentVertex);
}

// Impl
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;
import org.springframework.stereotype.Service;

@Service
public class EmbeddedGraphServiceImpl implements EmbeddedGraphService {

  @Resource private GraphDatabaseService graphDb;

  @Override
  public void addColumnVertex(ColumnVertex currentVertex, ColumnVertex upstreamVertex) {
    try (Transaction tx = graphDb.beginTx()) {
      tx.execute(
          "MERGE (c:ColumnVertex {name: $currentName}) MERGE (u:ColumnVertex {name: $upstreamName})"
              + " MERGE (u)-[:UPSTREAM]->(c)",
          Map.of("currentName", currentVertex.getName(), "upstreamName", upstreamVertex.getName()));
      tx.commit();
    }
  }

  @Override
  public List<ColumnVertex> findUpstreamColumnVertex(ColumnVertex currentVertex) {
    List<ColumnVertex> result = new ArrayList<>();
    try (Transaction tx = graphDb.beginTx()) {
      Result queryResult =
          tx.execute(
              "MATCH (u:ColumnVertex)-[:UPSTREAM]->(c:ColumnVertex) WHERE c.name = $name RETURN"
                  + " u.name AS name",
              Map.of("name", currentVertex.getName()));
      while (queryResult.hasNext()) {
        Map<String, Object> row = queryResult.next();
        result.add(new ColumnVertex().setName((String) row.get("name")));
      }
      tx.commit();
    }
    return result;
  }

  @Override
  public List<ColumnVertex> findDownstreamColumnVertex(ColumnVertex currentVertex) {
    List<ColumnVertex> result = new ArrayList<>();
    try (Transaction tx = graphDb.beginTx()) {
      Result queryResult =
          tx.execute(
              "MATCH (c:ColumnVertex)-[:UPSTREAM]->(d:ColumnVertex) WHERE c.name = $name RETURN"
                  + " d.name AS name",
              Map.of("name", currentVertex.getName()));
      while (queryResult.hasNext()) {
        Map<String, Object> row = queryResult.next();
        result.add(new ColumnVertex().setName((String) row.get("name")));
      }
      tx.commit();
    }
    return result;
  }
}

如何创建唯一键

这里使用 name ColumnVertex 的唯一键,在启动服务时检查是否存在唯一键,不存在则创建

@Service
public class EmbeddedGraphServiceImpl implements EmbeddedGraphService {

    @Resource private GraphDatabaseService graphDb;

    @PostConstruct
  public void init() {
    try (Transaction tx = graphDb.beginTx()) {
      Result result = tx.execute("SHOW CONSTRAINTS");
      boolean constraintExists = false;
      while (result.hasNext()) {
        Map<String, Object> row = result.next();
        if (((List<Object>) row.get("labelsOrTypes")).contains("ColumnVertex")
            && ((List<Object>) row.get("properties")).contains("name")
            && "UNIQUENESS".equals(row.get("type"))) {
          constraintExists = true;
          break;
        }
      }
      if (!constraintExists) {
        tx.execute("CREATE CONSTRAINT FOR (c:ColumnVertex) REQUIRE c.name IS UNIQUE");
      }
      tx.commit();
    }
  }
}
相关推荐
IT学长编程21 分钟前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
杨哥带你写代码43 分钟前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
A尘埃1 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23071 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
Marst Code1 小时前
(Django)初步使用
后端·python·django
代码之光_19801 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端
编程老船长2 小时前
第26章 Java操作Mongodb实现数据持久化
数据库·后端·mongodb
IT果果日记2 小时前
DataX+Crontab实现多任务顺序定时同步
后端
苹果醋33 小时前
快速玩转 Mixtral 8x7B MOE大模型!阿里云机器学习 PAI 推出最佳实践
spring boot·nginx·毕业设计·layui·课程设计
程序员大金3 小时前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql