Neo4j database entry notes

1. Introduction

1. Case summary
       Although mysql is called a relational database, it is incapable of dealing with many relationships between data. The reason is that the relational database is searched between the main watch and clock through foreign keys. This matching operation is "computationally intensive". As the number of records in the table increases, it will consume more system resources, so relational databases cannot cope with Facebook, Maimai friend recommendation, operation and maintenance server-cluster-computer room-cabinet - physical - cloud storage host and so achieve
Second, what is a graphical database
       mysql database is a new graphics nosql implementation based on graph theory database, its database storage structures and data query are based on graph theory-based, The basic elements of graph theory clock graphs are nodes and edges. In the graph database, they correspond to nodes and relations
a, node
b, and relation
graph theory: it is a branch of mathematics. It uses graphs as the research object. The graph in graph theory is A graphic composed of a number of given points and a line connecting two points. This graphic is usually used to describe a certain specific relationship between a certain transaction. A point is used to represent things, and a line connecting two points is used to represent two There is such a relationship between things.
Insert picture description here
3. Graphical database application scenario
1. Resource pool ~~~ server association relationship map
2. Tianyancha's stock set to company structure relationship map
3. Business enterprise map
4. Social network

Two, neo4j installation and entry examples

#1、安装检测jdk环境1.8
#2、下载程序包 http://neo4j.com/download/other-releases/#releases
#下载社区版
wget http://neo4j.com/artifact.php?name=neo4j-community-3.2.10-unix.tar.gz
#解压
tar -zxvf neo4j-community-3.2.10-unix.tar.gz
#修改配置文件
vim conf/neo4j.conf
#放开访问权限
dbms.connectors.default.listen_address=0.0.0.0
#3、启动
#启动
./bin/neo4j start
#停止
./bin/neo4j stop
#4、访问WEB管理页
http://ip:7474/browser/

3. Basic elements and concepts in neo4j graph database

1. A node (node)
       identifies an entity record, just like a record in relational data. A node contains multiple attributes and labels.
2.
       Relationships are used to associate nodes to form a graph. The relationship also becomes a graph theory. Edge
3. Property
       nodes and relationships can have multiple properties, properties are composed of key-value pairs, just like hash
4 in JAVA , label (Label)
       label indicates a group of the same property Nodes, but it is not mandatory to be the same. A node can have multiple labels.
5.
       Any two nodes in the path graph have a path composed of relations, and the path can be long or short.

Four, Cypher query language

1. Concept: Cypher is a declarative graph database query language, similar to SQL in relational databases. Cypher's design draws on the useful practices of other languages ​​such as SQL and Python. It is easy for beginners to use
       MATCH: matching graph mode
       WHERE: filter condition
       RETURN: definition Returned result
2. Basic syntax:
       add (CREATE)
       delete (DELETE)
       modify (SET)
       query (MATCH)
       function
       witch
       aggregation
3. Peppa pig example

create(:pig{
    
    name:"猪爷爷",age:15});
create(:pig{
    
    name:"猪奶奶",age:13});
match(a:pig(name:"猪爷爷",age:15)) match(b:pig{
    
    name:"猪奶奶",age:13}) create (a)-[r:fuqi]
->(b) return r;
#也可以一次性创建节点和关系(还可以给关系加属性)
create(:pig{
    
    name:"猪爸爸",age:10})-[:fuqi{
    
    age:5}]->(:pig{
    
    name:"猪妈妈",age:8});
create(:pig{
    
    name:"佩奇",age:5})-[:jiedi]->(:pig{
    
    name:"乔治",age:3});
match(a:pig(name:"猪爸爸")) match(b:pig{
    
    name:"猪爷爷"}) create (b)-[r:fuzi]
->(a) return r;
match(a:pig(name:"猪爸爸")) match(b:pig{
    
    name:"猪爷爷"}) create (b)-[r:fuzi]
->(a) return r;
match(a:pig(name:"猪爷爷")) match(b:pig{
    
    name:"佩奇"}) create (a)-[r:sunnv]
->(b) return r;
#还可以创建多标签
create(:die:pig{
    
    name:"猪祖父",age:15});
#修改属性
match(a:pig(name:"猪爷爷",age:15)) set a.age=5
#删除节点 删除die标签下的所有节点
match (n:die) delete n;

4. Get the shortest node between two nodes 5 specifies the largest path

match p=shortestpath((a:Star(name:"a1")-[*..5]->(b:Star(name:"a2")))) return p
match p=allshortestpath((a:Star(name:"a1")-[*..5]->(b:Star(name:"a2")))) return p

5. Query everyone related to Faye Wong

return (:Star(name:"王菲"))-->() limit 50;

Five, neo4j program development

1. The java embedded development model
neo4j is developed based on the java language. At the beginning of the first release, it was specifically aimed at the java field, etc., so it can be naturally combined with java development, and the java program can be directly integrated into the neo4j library into the application
Insert picture description here
2 , Restful interface call
http://192.168.0.147:7474/db/data/ #Return information about the database
Insert picture description here
3. java call

#yml文件配置
spring:
  data:
    neo4j:
      uri: http://localhost:7474
      username: neo4j
      password: 123456
<!-- 添加依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>

@NodeEntity, mark the class as a node, and the node name is BaseNode

@Getter
@Setter
@ToString
@NodeEntity
public class BaseNode {
    
    
    /**
     * neo4j 生成的id
     */
    @Id
    @GeneratedValue
    private Long id;
    /**
     * 属性,name
     */
    private String name;
    /**
     *
     */
    private Integer age;
    /**
     * 关系,定义为友谊
     */
    @Relationship(type = "BASERELATIONSHIP_RELATION")
    private List<BaseRelationship> BaseRelationshipList;
}

@RelationshipEntity, mark it as a relationship, the relationship name is BASERELATIONSHIP_RELATION, and StartNode and EndNode are defined inside

@Getter
@Setter
@Component
@RelationshipEntity(type = "BASERELATIONSHIP_RELATION")
public class BaseRelationship{
    
    
    @Id
    @GeneratedValue
    private Long id;

    @StartNode
    private BaseNode from;

    @EndNode
    private BaseNode to;
//Node节点操作
@Repository
public interface BaseNodeRepository extends Neo4jRepository<BaseNode, String> {
    
    
	//可以使用spring data风格使用默认的方法名查询
	List<BaseNode> findByCode(String code);
	List<BaseNode> findById(String Id);
	//根据年龄查找所有的节点
	@Query(value="MATCH (n:BaseNode) where n.age={age} return n")
	List<BaseNode> getlistByAge(int age);
|
//关联关系操作
@Repository
public interface BaseRelationshipRepository extends Neo4jRepository<BaseRelationship, String> {
    
    
	//根据节点的名字查找对应的关联关系
	 @Query("MATCH (a:BaseNode)-[r:Ref]->(b:BaseNode) WHERE a.name={startName} and b.name={endName} RETURN a,p,b")
    List<BaseRelationship> findStartToEndRelationship(String startName, String endName);
}

In Neo4jServiceImpl to define the add relationship and delete relationship, you need to save the node relationship on the from side.
When deleting the node, the find and save methods are used, and the @Transactional annotation needs to be added

@Service("neo4jServiceImpl")
public class Neo4jServiceImpl implements Neo4jService {
    
    

    @Autowired
    private BaseNodeRepository baseNodeRepository;

    @Override
    public void saveBaseRelationship(String fromName, String toName) {
    
    
        BaseNode from = baseNodeRepository.findByName(fromName);
        BaseNode to = baseNodeRepository.findByName(toName);

        BaseRelationship baseRelationship  = new BaseRelationship();
        baseRelationship.setFrom(from);
        baseRelationship.setTo(to);

        //只需要在from节点保存关系即可
        from.addRelation(baseRelationship);
        baseNodeRepository.save(from);
    }

    //删除节点时,使用find,save 需要@Transactional注解
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBaseRelationship(String fromName, String toName) {
    
    
        BaseNode fromBaseNode = baseNodeRepository.findByName(fromName);
        List<BaseRelationship> baseRelationshipList = fromStudentNode.findStartToEndRelationship();
        for (Iterator<BaseRelationship> iterator = baseRelationshipList.iterator(); iterator.hasNext();) {
    
    
            BaseRelationship relation = iterator.next();
            BaseNode fromNode = relation.getFrom();
            BaseNode toNode = relation.getTo();

            String fromNodeName = fromNode.getName();
            String toNodeName = toNode.getName();
            //判断 fromName 和 toName 需要删除的关系是否相等
            if(fromNodeName.equals(fromName) && toNodeName.equals(toName)){
    
    
                iterator.remove();
            }
        }
        //只需要在from节点保存关系即可
        baseNodeRepository.save(fromStudentNode);
    }
}

test

@RunWith(SpringRunner.class)
@SpringBootTest
public class Neo4jTest {
    
    
    @Autowired
    private BaseNodeRepository baseNodeRepository;

    @Autowired
    private Neo4jService neo4jService;

    /**
     * 保存单个节点
     */
    @Test
    public void saveBaseNode(){
    
    
        BaseNode BaseNode = new BaseNode();
        BaseNode.setName("张0");
        baseNodeRepository.save(BaseNode);
    }

    /**
     * 通过name查询学生节点
     */
    @Test
    public void findBaseNodeByName(){
    
    
        BaseNode BaseNode = baseNodeRepository.findByName("张0");
        System.out.println("");
    }

    /**
     * 保存批量节点
     */
    @Test
    public void saveAllBaseNode(){
    
    
        List<BaseNode> BaseNodeList = new ArrayList<>();
        BaseNode BaseNode;
        for(int i = 1; i <= 10; i++){
    
    
            BaseNode = new BaseNode();
            BaseNode.setName("张" + i);
            BaseNodeList.add(BaseNode);
        }
        baseNodeRepository.saveAll(BaseNodeList);
    }

    /**
     * 查询全部
     */
    @Test
    public void findAll(){
    
    
        //iterable to list
        List<BaseNode> BaseNodeList = Lists.newArrayList(baseNodeRepository.findAll());
        System.out.println("");
    }

    /**
     * 分页查询
     */
    @Test
    public void pageFindAll(){
    
    
        Pageable pageable = PageRequest.of(0,2);
        Page<BaseNode> BaseNodePage = baseNodeRepository.findAll(pageable);
        System.out.println("");
    }

    /**
     * 保存如下友谊关系

     */
    @Test
    public void saveBaseRelationship(){
    
    
        neo4jService.saveBaseRelationship("张1","张2");
 
    }

    /**
     * 删除 1 -> 3 友谊关系
     */
    @Test
    public void deleteFriendship(){
    
    
        neo4jService.deleteFriendship("张1","张3");
    }
}

Guess you like

Origin blog.csdn.net/qdboi/article/details/109291893