Hello World of Spring Boot call graph database Neo4j


   
   
  1. 明日歌
  2. [清]钱鹤滩
  3. 明日复明日,明日何其多!
  4. 我生待明日,万事成蹉跎

1. The  map database Neo4j loved the first experience ---- and the king of Chu Xiangshi, You Si owned by the enemy

In today's large data (Big the Data ) era of rampant, traditional relational databases such as oracle, mysql in large amounts of data, high concurrency scenarios appeared to be inadequate. Ever since, NoSQL turned out, such as column-based database of cassandra, document-based of MongoDB, also introduced today a small minority of the chart data graph-based database Neo4j.

The origin of the name is in fact its map database in the underlying storage related map database does not mean that stores graphics, pictures and so on. Neo4j bottom of the Figure will be user-defined nodes (Nodes) and the relation (Relationships) stored, Nodes and Relationships comprising key / value attribute form. Nodes are connected together by Relationships defined relationship, relationship network structure is formed. In this way, but the efficient implementation from the beginning of a node, node by node and the relationship between, find out the connection between two nodes.

2. Neo4j then judge of love ---- I'm Born with

Mr. Jin Yong's "evil" for example, there's a very complex character relationship chart, Yang Guo Shen Diao heroes have a lot of fans, his fans have their fans (second degree contacts), fans of the fans there his fans ...... .. assume YangDaXia from the Southern Song Dynasty opened a blog, but now must circle countless powder, if you want to find Yang Guo and his fans six times seven is treasure vein, the use of traditional relational database, you need to many relationship table storing relational data into the billions, 10 billion one hundred billion or even more. Regardless of the sub-library with relational database technology or other sub-table optimization means, in terms of complexity and performance are likely to encounter a problem.

The map database neo4j use of traversal algorithm design, that is starting from a node, according to the relationship which it is connected, you can quickly and easily find its neighboring nodes, thus having a simple storage and high query performance.

About neo4j more details and neo4j server installation and to create nodes, relations with the cypher language and other content can refer to the online information (such as: https://blog.csdn.net/victory0508/article/details/78414798 ), this paper focus on Spring boot 2.0 how to call neo4j simple.

3. Neo4j enforcement Spring boot hand ---- My Fair Lady, Spring boot Haoqiu

In my first blog in the Boot 2.0 introduces the Spring . This article Spring boot combined with Spring Data, with very little code, the basic zero-configuration, without writing any queries (queries) statement (here cypher) implements the additions and deletions to change search Neo4j.

3.1 Neo4j connection configuration

Spring boot configuration files by default in src / main / resources below, support the traditional application.properties and application.yml

application.properties version:


   
   
  1. spring.data.neo4j.username=neo4j
  2. spring.data.neo4j.password=helloworld

application.yml 版:      


   
   
  1. spring:
  2. data:
  3. neo4j:
  4. username: neo4j
  5. password: helloworld

3.2 Entity Class (Model ) 


   
   
  1. @NodeEntity
  2. public class Legend {
  3. @Id @GeneratedValue private Long id;
  4. private String name;
  5. private Legend() {
  6. // Empty constructor required as of Neo4j API 2.0.5
  7. };
  8. public Legend(String name) {
  9. this.name = name;
  10. }
  11. /**
  12. * Neo4j doesn't REALLY have bi-directional relationships. It just means when querying
  13. * to ignore the direction of the relationship.
  14. * https://dzone.com/articles/modelling-data-neo4j
  15. */
  16. @Relationship(type = "FANS", direction = Relationship.UNDIRECTED)
  17. public Set<Legend> fans;
  18. public void fansWith(Legend legend) {
  19. if (fans == null) {
  20. fans = new HashSet<>();
  21. }
  22. fans.add(legend);
  23. }
  24. public String toString() {
  25. //java 8 stream and optional
  26. return this.name + "'s fans => "
  27. + Optional.ofNullable( this.fans).orElse(
  28. Collections.emptySet()).stream()
  29. .map(Legend::getName)
  30. .collect(Collectors.toList());
  31. }
  32. public String getName() {
  33. return name;
  34. }
  35. public void setName(String name) {
  36. this.name = name;
  37. }
  38. }

Entity class annotated by annotation @NodeEntity, so when calling to save this entity (save method), it will be saved to the database neo4j.

Another important part is

        @Relationship(type = "FANS", direction = Relationship.UNDIRECTED)
  
  

To build relationships, UNDIRECTED represent ignore directional relationship.

FansWith application by calling the method can be Shendiao characters are linked.

3.3 Spring data neo4j

        Spring Data  belongs to the Spring community, to simplify access to the database, in many cases, do not even have to write any queries you can adapt the operation of the database. 


   
   
  1. import org.springframework.data.repository.CrudRepository;
  2. public interface LegendRepo extends CrudRepository<Legend, Long> {
  3. Legend findByName(String name);
  4. }

 CrudRepository is key, it is commonly used as the package stored update operations.

FindByName represented by the above method name to query. The name must be a property of the entity classes. In a relational database, spring data will be converted to his own will select * from table where name =? . The neo4j use cypher language, transformed into a similar query


   
   
  1. MATCH (n:`Legend`) WHERE n.`name` = { `name_0` } WITH n RETURN n,
  2. [ [ (n)-[r_f1:`FANS`]-(l1:`Legend`) | [ r_f1, l1 ] ] ], ID(n) with params {name_0=杨过}

And if you want to express Or or relationship (assuming that legend has attributes level), will be the method name

findByNameAndLevel(String name,String level)

If you want to page, you need to inherit PagingAndSortingRepository , rather than CrudRepository. For more details about springdata, I will explain in detail in a future blog.

3.4 Spring boot startup class 


   
   
  1. @SpringBootApplication
  2. @EnableNeo4jRepositories
  3. public class SpringBootNeo4jApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringBootNeo4jApplication.class, args);
  6. }
  7. }

Here annotation @ EnableNeo4jRepositories tell spring boot program uses neo4j repository.

3.5 Spring boot test class 

 Spring tool suites development tools automatically generate test classes, add your own logic code, saved three nodes: Yang Guo, Maid and Guo Xiang.

Then establish a relationship between them, and Maid Yang Guo Guo Xiang is a fan of both. Finally, check out the John Steinbeck fans.


   
   
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class SpringBootNeo4jApplicationTests {
  4. @Autowired
  5. LegendRepo legendRepo;
  6. private final static Logger log = LoggerFactory.getLogger(SpringBootNeo4jApplicationTests.class);
  7. @Test
  8. public void contextLoads() {
  9. legendRepo.deleteAll();
  10. Legend yangguo = new Legend( "杨过");
  11. Legend dragonGirl = new Legend( "小龙女");
  12. Legend guoxiang = new Legend( "郭襄");
  13. List<Legend> team = Arrays.asList(yangguo, dragonGirl, guoxiang);
  14. log.info( "Before linking up with Neo4j...");
  15. //java 8 stream
  16. team.stream().forEach(legend -> log.info( "\t" + legend.toString()));
  17. legendRepo.save(yangguo);
  18. legendRepo.save(dragonGirl);
  19. legendRepo.save(guoxiang);
  20. yangguo = legendRepo.findByName(yangguo.getName());
  21. yangguo.fansWith(dragonGirl);
  22. yangguo.fansWith(guoxiang);
  23. legendRepo.save(yangguo);
  24. dragonGirl = legendRepo.findByName(dragonGirl.getName());
  25. dragonGirl.fansWith(guoxiang);
  26. // We already know that dragonGirl is a fan of yangguo
  27. legendRepo.save(dragonGirl);
  28. // We already know guoxiang fans with yangguo and dragongirl
  29. log.info( "Look up yangguo's fans ...");
  30. log.info(legendRepo.findByName( "杨过").toString());
  31. }
  32. }

Run the code view the log:

Look up yangguo's fans ...
Request: MATCH (n:`Legend`) WHERE n.`name` = { `name_0` } WITH n RETURN n,[ [ (n)-[r_f1:`FANS`]-(l1:`Legend`) | [ r_f1, l1 ] ] ], ID(n) with params {name_0=杨过}
 杨过's fans => [郭襄, 小龙女]
4. Neo4j and the Boot the Spring ---- generation one pair of human life

Neo4j in some cases be able to play to their strengths, but with spring boot a way that is very simple to use neo4j since everyone has a spring boot, life has become at ease.

Watch spring boot, please continue to focus on my blog.


Original Address: https: //blog.csdn.net/weixin_41897365/article/details/79835319

Guess you like

Origin www.cnblogs.com/jpfss/p/11231415.html