知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Java SpringBoot 操作 Neo4j

发布时间 2023-08-22 14:37:29作者: VipSoft

上一篇使用了 CQL 实现了太极拳传承谱,这次使用JAVA SpringBoot 实现,只演示获取信息,源码连接在文章最后

三要素
在知识图谱中,通过三元组 <实体 × 关系 × 属性> 集合的形式来描述事物之间的关系:

  • 实体:又叫作本体,指客观存在并可相互区别的事物,可以是具体的人、事、物,也可以是抽象的概念或联系,实体是知识图谱中最基本的元素
  • 关系:在知识图谱中,边表示知识图谱中的关系,用来表示不同实体间的某种联系
  • 属性:知识图谱中的实体和关系都可以有各自的属性

image

image

#输入查看数据库连接
neo4j$ :server status

Spring-Data-Neo4j 和 jpa 非常类似,另外:Neo4jClient 的用法见:https://github.com/neo4j-examples/movies-java-spring-data-neo4j

添加POM引用

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.0</version>
    <relativePath/>
</parent>


<!-- This is everything needed to work with Spring Data Neo4j 6.0. -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>

配置 Neo4j 连接信息:
application.yml

server:
  port: 8080

spring:
  profiles:
    active: dev

  neo4j:
    uri: neo4j://172.16.3.64:7687
    authentication:
      username: neo4j
      password: password
  data:
    neo4j:
      database: neo4j

logging:
  level:
    org.springframework.data.neo4j: DEBUG

实体 PersonNode.java

package com.vipsoft.web.entity;

import org.springframework.data.neo4j.core.schema.Id;
import org.springframework.data.neo4j.core.schema.Node;
import org.springframework.data.neo4j.core.schema.Property;

@Node("Person")
public class PersonNode {

    @Id
    private String name;


    @Property("generation")     //可以 Neo4j 属性映射
    private String generation;

    public PersonNode(String name, String generation) {
        this.name = name;
        this.generation = generation;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGeneration() {
        return generation;
    }

    public void setGeneration(String generation) {
        this.generation = generation;
    }
}

PersonRepository.java

package com.vipsoft.web.repository;

import com.vipsoft.web.entity.PersonNode;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * This repository is indirectly used in the {@code movies.spring.data.neo4j.api.MovieController} via a dedicated movie service.
 * It is not a public interface to indicate that access is either through the rest resources or through the service.
 *
 * @author Michael Hunger
 * @author Mark Angrish
 * @author Michael J. Simons
 */ 
public interface PersonRepository extends Repository<PersonNode, String> {

	@Query("MATCH (p:Person) WHERE p.name CONTAINS $name RETURN p")
    List<PersonNode> findSearchResults(@Param("name") String name);
}

http://localhost:2356/demo/person/陈长兴
image

源码地址:https://gitee.com/VipSoft/VipNeo4j/tree/master/Java