知識圖譜(Knowledge Graph)- Neo4j 5.10.0 使用

2023-08-22 15:04:08

上一篇使用了 CQL 實現了太極拳傳承譜,這次使用JAVA SpringBoot 實現,只演示獲取資訊,原始碼連線在文章最後

三要素
在知識圖譜中,通過三元組 <實體 × 關係 × 屬性> 集合的形式來描述事物之間的關係:

  • 實體:又叫作本體,指客觀存在並可相互區別的事物,可以是具體的人、事、物,也可以是抽象的概念或聯絡,實體是知識圖譜中最基本的元素
  • 關係:在知識圖譜中,邊表示知識圖譜中的關係,用來表示不同實體間的某種聯絡
  • 屬性:知識圖譜中的實體和關係都可以有各自的屬性

#輸入檢視資料庫連線
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/陳長興

原始碼地址:https://gitee.com/VipSoft/VipNeo4j/tree/master/Java