💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 用Neo4j访问数据 本指南将引导您完成使用 的过程, [Spring Data Neo4j](https://projects.spring.io/spring-data-neo4j/) 来构建应用程序 该应用程序将数据存储在 中并从中检索 [Neo4j](https://www.neo4j.com/) 基于图形的数据库 数据。 ## 你会建立什么 您将使用Neo4j的 [NoSQL](https://wikipedia.org/wiki/NoSQL) 基于 图的数据存储来构建嵌入式Neo4j服务器,存储实体和关系以及开发查询。 ## 你需要什么 * 约15分钟 * 最喜欢的文本编辑器或IDE * [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本 * [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi) * 您还可以将代码直接导入到IDE中: * [弹簧工具套件(STS)](https://spring.io/guides/gs/sts) * [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) ## 如何完成本指南 像大多数Spring 一样 [入门指南](https://spring.io/guides) ,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。 无论哪种方式,您最终都可以使用代码。 要 **从头开始** ,请继续进行“ [从Spring Initializr开始”](https://spring.io/guides/gs/accessing-data-neo4j/#scratch) 。 要 **跳过基础知识** ,请执行以下操作: * [下载](https://github.com/spring-guides/gs-accessing-data-neo4j/archive/master.zip) 并解压缩本指南的源存储库,或使用 对其进行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-accessing-data-neo4j.git](https://github.com/spring-guides/gs-accessing-data-neo4j.git)` * 光盘进入 `gs-accessing-data-neo4j/initial` * 继续 [定义一个简单实体](https://spring.io/guides/gs/accessing-data-neo4j/#initial) 。 **完成后** ,您可以根据中的代码检查结果 `gs-accessing-data-neo4j/complete`. ## 从Spring Initializr开始 如果使用Maven,请访问 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-neo4j&name=accessing-data-neo4j&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-neo4j&dependencies=data-neo4j) 以生成具有所需依赖项的新项目(Spring Data Neo4j)。 以下清单显示了 `pom.xml` 选择Maven时创建的文件: ~~~ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>accessing-data-neo4j</artifactId> <version>0.0.1-SNAPSHOT</version> <name>accessing-data-neo4j</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-neo4j</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ~~~ 如果使用Gradle,请访问 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=accessing-data-neo4j&name=accessing-data-neo4j&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.accessing-data-neo4j&dependencies=data-neo4j) 以生成具有所需依赖项的新项目(Spring Data Neo4j)。 以下清单显示了 `build.gradle`选择Gradle时创建的文件: ~~~ plugins { id 'org.springframework.boot' version '2.4.3' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'java' } group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = '1.8' repositories { mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-neo4j' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ~~~ 配置该项​​目以适合本教程中的示例。 ### 手动初始化(可选) 如果要手动初始化项目而不是使用前面显示的链接,请按照以下步骤操作: 1. 导航到 [https://start.spring.io](https://start.spring.io) 。 该服务提取应用程序所需的所有依赖关系,并为您完成大部分设置。 2. 选择Gradle或Maven以及您要使用的语言。 本指南假定您选择了Java。 3. 单击 **Dependencies,** 然后选择 **Spring Data Neo4j** 。 4. 点击 **生成** 。 5. 下载生成的ZIP文件,该文件是使用您的选择配置的Web应用程序的存档。 如果您的IDE集成了Spring Initializr,则可以从IDE中完成此过程。 ## Standing up a Neo4j Server Before you can build this application, you need to set up a Neo4j server. Neo4j has an open source server you can install for free. 在安装了Homebrew的Mac上,运行以下命令: ~~~ $ brew install neo4j ~~~ 有关其他选项,请访问 [https://neo4j.com/download/community-edition/](https://neo4j.com/download/community-edition/) 。 安装后,通过运行以下命令以默认设置启动它: ~~~ $ neo4j start ~~~ 您应该看到类似于以下内容的输出: ~~~ Starting Neo4j. Started neo4j (pid 96416). By default, it is available at http://localhost:7474/ There may be a short delay until the server is ready. See /usr/local/Cellar/neo4j/3.0.6/libexec/logs/neo4j.log for current status. ~~~ 默认情况下,Neo4j的用户名和密码为 `neo4j` 和 `neo4j`。 但是,它要求更改新的帐户密码。 为此,请运行以下命令: ~~~ curl -v -u neo4j:neo4j POST localhost:7474/user/neo4j/password -H "Content-type:application/json" -d "{\"password\":\"secret\"}" ~~~ 这会将密码从 `neo4j` 到 `secret`\-生产中不得做的事! 完成该步骤后,您应该准备运行本指南的其余部分。 ## 定义一个简单实体 Neo4j捕获实体及其关系,这两个方面都具有同等重要的意义。 想象一下,您正在对一个系统建模,在该系统中存储每个人的记录。 但是,您还想跟踪某人的同事( `teammates`在此示例中)。 借助Spring Data Neo4j,您可以使用一些简单的注释捕获所有内容,如下面的清单(在 `src/main/java/com/example/accessingdataneo4j/Person.java`)显示: ~~~ package com.example.accessingdataneo4j; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.springframework.data.neo4j.core.schema.Id; import org.springframework.data.neo4j.core.schema.Node; import org.springframework.data.neo4j.core.schema.Property; import org.springframework.data.neo4j.core.schema.Relationship; import org.springframework.data.neo4j.core.schema.GeneratedValue; @Node public class Person { @Id @GeneratedValue private Long id; private String name; private Person() { // Empty constructor required as of Neo4j API 2.0.5 }; public Person(String name) { this.name = name; } /** * Neo4j doesn't REALLY have bi-directional relationships. It just means when querying * to ignore the direction of the relationship. * https://dzone.com/articles/modelling-data-neo4j */ @Relationship(type = "TEAMMATE") public Set<Person> teammates; public void worksWith(Person person) { if (teammates == null) { teammates = new HashSet<>(); } teammates.add(person); } public String toString() { return this.name + "'s teammates => " + Optional.ofNullable(this.teammates).orElse( Collections.emptySet()).stream() .map(Person::getName) .collect(Collectors.toList()); } public String getName() { return name; } public void setName(String name) { this.name = name; } } ~~~ 在这里你有一个 `Person` 仅具有一个属性的类: `name`. The `Person` class is annotated with `@NodeEntity`. When Neo4j stores it, a new node is created. This class also has an `id` marked `@GraphId`. Neo4j uses `@GraphId` internally to track the data. 下一个重要的部分是 `teammates`。 很简单 `Set<Person>` 但被标记为 `@Relationship`。 这意味着该集合的每个成员也应作为单独的成员存在 `Person`节点。 注意方向如何设置为 `UNDIRECTED`。 这意味着当您查询 `TEAMMATE` 关系,Spring Data Neo4j忽略了关系的方向。 随着 `worksWith()` 方法,您可以轻松地将人们联系在一起。 最后,您有一个方便的地方 `toString()` 打印此人的姓名和该人的同事的方法。 ## 创建简单查询 Spring Data Neo4j专注于在Neo4j中存储数据。 但是它继承了Spring Data Commons项目的功能,包括导出查询的功能。 本质上,您无需学习Neo4j的查询语言。 相反,您可以编写一些方法,然后为您编写查询。 要查看其工作原理,请创建一个查询接口 `Person`节点。 以下清单(在 `src/main/java/com/example/accessingdataneo4j/PersonRepository.java`)显示了这样的查询: ~~~ package com.example.accessingdataneo4j; import java.util.List; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface PersonRepository extends Neo4jRepository<Person, Long> { Person findByName(String name); List<Person> findByTeammatesName(String name); } ~~~ `PersonRepository` 扩展 `Neo4jRepository` 接口并插入其操作的类型: `Person`。 此接口包含许多操作,包括标准的CRUD(创建,读取,更新和删除)操作。 但是您可以通过声明其他方法的签名来定义其他查询。 在这种情况下,您添加了 `findByName`,它寻找类型的节点 `Person` 并找到与之匹配的 `name`。 你也有 `findByTeammatesName`,它寻找一个 `Person` 节点,深入到 `teammates` 字段,并根据队友的比赛 `name`. ## 访问Neo4j的权限 Neo4j Community Edition需要凭据才能访问它。 您可以通过设置几个属性(在 `src/main/resources/application.properties`),如以下清单所示: ~~~ spring.neo4j.uri=bolt://localhost:7687 spring.data.neo4j.username=neo4j spring.data.neo4j.password=secret ~~~ 这包括默认的用户名( `neo4j`)以及我们之前选择的新设置的密码( `secret`). 不要在源存储库中存储真实凭证。 而是在您的运行时中使用 配置它们 Spring Boot的属性overrides 。 将其放置到位后,您可以将其连接起来,看看它是什么样子! ## 创建一个应用程序类 Spring Initializr为应用程序创建一个简单的类。 以下清单显示了Initializr为此示例创建的类(在 `src/main/java/com/example/accessingdataneo4j/AccessingDataNeo4jApplication.java`): ~~~ package com.example.accessingdataneo4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AccessingDataNeo4jApplication { public static void main(String[] args) { SpringApplication.run(AccessingDataNeo4jApplication.class, args); } } ~~~ `@SpringBootApplication` 是一个方便注释,它添加了以下所有内容: * `@Configuration`:将类标记为应用程序上下文的Bean定义的源。 * `@EnableAutoConfiguration`:告诉Spring Boot根据类路径设置,其他bean和各种属性设置开始添加bean。 例如,如果 `spring-webmvc` 在类路径上,此注释将应用程序标记为Web应用程序并激活关键行为,例如设置 `DispatcherServlet`. * `@ComponentScan`:告诉Spring在服务器中寻找其他组件,配置和服务 `com/example` 包,让它找到控制器。 这 `main()` 方法使用Spring Boot的 `SpringApplication.run()`启动应用程序的方法。 您是否注意到没有一行XML? 没有 `web.xml`文件。 该Web应用程序是100%纯Java,因此您无需处理任何管道或基础结构。 只要它们包含在您的同一软件包(或子软件包)中,Spring Boot就会自动处理这些存储库 `@SpringBootApplication`班级。 为了更好地控制注册过程,您可以使用 `@EnableNeo4jRepositories` 注解。 默认, @EnableNeo4jRepositories在当前包中扫描任何扩展了Spring Data存储库接口之一的接口。 你可以用它 basePackageClasses=MyRepository.class 如果您的项目布局中有多个项目并且找不到存储库,则可以安全地告诉Spring Data Neo4j按类型扫描其他根包。 显示日志记录输出。 该服务应在几秒钟内启动并运行。 现在自动连线的实例 `PersonRepository`您之前定义的。 Spring Data Neo4j动态地实现该接口,并插入所需的查询代码以满足接口的义务。 这 `main` 方法使用Spring Boot的 `SpringApplication.run()` 启动应用程序并调用 `CommandLineRunner` 建立关系。 在这种情况下,您将创建三个本地 `Person`实例:格雷格(Greg),罗伊(Roy)和克雷格(Craig)。 最初,它们仅存在于内存中。 请注意,还没有人是任何人的队友。 首先,您会找到Greg,指出他与Roy和Craig合作,然后再次坚持下去。 记住,队友关系被标记为 `UNDIRECTED`(即双向)。 这意味着Roy和Craig也已更新。 这就是为什么当您需要更新Roy时的原因。 首先从Neo4j获取该记录非常重要。 在将Craig添加到列表之前,您需要Roy队友的最新状态。 为什么没有代码可以获取Craig并添加任何关系? 因为您已经拥有它! 格雷格(Greg)早些时候将克雷格(Craig)标记为队友,罗伊(Roy)也是如此。 这意味着无需再次更新Craig的关系。 在遍历每个团队成员并将其信息打印到控制台时,您可以看到它。 最后,查看其他查询中您向后看的地方,回答“谁与谁一起工作?”的问题。 以下清单显示了成品 `AccessingDataNeo4jApplication` 类(在 `src/main/java/com/example/accessingdataneo4j/AccessingDataNeo4jApplication.java`): ~~~ package com.example.accessingdataneo4j; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; @SpringBootApplication @EnableNeo4jRepositories public class AccessingDataNeo4jApplication { private final static Logger log = LoggerFactory.getLogger(AccessingDataNeo4jApplication.class); public static void main(String[] args) throws Exception { SpringApplication.run(AccessingDataNeo4jApplication.class, args); System.exit(0); } @Bean CommandLineRunner demo(PersonRepository personRepository) { return args -> { personRepository.deleteAll(); Person greg = new Person("Greg"); Person roy = new Person("Roy"); Person craig = new Person("Craig"); List<Person> team = Arrays.asList(greg, roy, craig); log.info("Before linking up with Neo4j..."); team.stream().forEach(person -> log.info("\t" + person.toString())); personRepository.save(greg); personRepository.save(roy); personRepository.save(craig); greg = personRepository.findByName(greg.getName()); greg.worksWith(roy); greg.worksWith(craig); personRepository.save(greg); roy = personRepository.findByName(roy.getName()); roy.worksWith(craig); // We already know that roy works with greg personRepository.save(roy); // We already know craig works with roy and greg log.info("Lookup each person by name..."); team.stream().forEach(person -> log.info( "\t" + personRepository.findByName(person.getName()).toString())); List<Person> teammates = personRepository.findByTeammatesName(greg.getName()); log.info("The following have Greg as a teammate..."); teammates.stream().forEach(person -> log.info("\t" + person.getName())); }; } } ~~~ ## 建立可执行的JAR 您可以使用Gradle或Maven从命令行运行该应用程序。 您还可以构建一个包含所有必需的依赖项,类和资源的可执行JAR文件,然后运行该文件。 生成可执行jar使得在整个开发生命周期中,跨不同环境等等的情况下,都可以轻松地将服务作为应用程序进行发布,版本控制和部署。 如果您使用Gradle,则可以通过使用以下命令运行该应用程序 `./gradlew bootRun`。 或者,您可以通过使用以下命令构建JAR文件: `./gradlew build` 然后运行JAR文件,如下所示: ~~~ java -jar build/libs/gs-accessing-data-neo4j-0.1.0.jar ~~~ 如果您使用Maven,则可以通过使用以下命令运行该应用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令构建JAR文件: `./mvnw clean package` 然后运行JAR文件,如下所示: ~~~ java -jar target/gs-accessing-data-neo4j-0.1.0.jar ~~~ 此处描述的步骤将创建可运行的JAR。 您还可以 构建经典的WAR文件 。 您应该看到类似于以下清单的内容(以及其他内容,例如查询): ~~~ Before linking up with Neo4j... Greg's teammates => [] Roy's teammates => [] Craig's teammates => [] Lookup each person by name... Greg's teammates => [Roy, Craig] Roy's teammates => [Greg, Craig] Craig's teammates => [Roy, Greg] ~~~ 从输出中可以看到,(最初)没有任何人通过任何关系被连接。 然后,在添加人员后,他们就被绑在一起了。 最后,您可以看到根据队友查找人的便捷查询。 ## 概括 恭喜你! 您只需设置一个嵌入式Neo4j服务器,存储一些简单的相关实体,并开发一些快速查询。 如果要毫不费力地使用基于超媒体的RESTful前端公开Neo4j存储库,请阅读 使用REST访问Neo4j数据 。