Neo4j访问的两种方式

嵌入式数据库
服务器模式(通过REST的访问)
它是由应用程序的性质(neo4j是独立服务器 还是和程序在一起),性能,监控和数据安全性来决定架构选择。

An embedded database(嵌入式数据库)

嵌入式Neo4j数据库是性能的最佳选择。 通过指定数据存储的路径以编程方式访问嵌入式数据库。
我们选择嵌入式数据库出于以下原因:

  • 使用Java作为我们项目的编程语言时
  • 应用程序是独立的
  • 程序追求很高的性能

    Neo4j Server(服务器模式)

    Neo4j Server是相互操作性,安全性和监控的最佳选择。 实际上,REST接口允许所有现代平台和编程语言与它进行互操作。 此外,作为独立应用程序,它比嵌入式配置更安全(客户端中的潜在故障不会影响服务器),并且更易于监控。 如果我们选择使用这种模式,我们的应用程序将充当Neo4j服务器的客户端。要连接到Neo4j服务器,可以使用任何编程语言的REST 访问数据库。

    Java客户端操作Neo4j

    嵌入式模式

    org.neo4j neo4j 3.5.5


package com.lagou; import org.neo4j.graphdb.*; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import java.io.File; import java.util.HashMap; import java.util.Map; public class EmbeddedNeo4jAdd { private static final File databaseDirectory = new File( “target/graph.db” ); public static void main(String[] args) { GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(databaseDirectory); System.out.println(“Database Load!”);

Transaction tx = graphDb.beginTx();

Node n1 = graphDb.createNode();

n1.setProperty(“name”, “张三”);

n1.setProperty(“character”, “A”);

n1.setProperty(“gender”,1);

n1.setProperty(“money”, 1101);

n1.addLabel(new Label() {

@Override

public String name() {

return “Person”;

}

});

String cql = “CREATE (p:Person{name:’李

四’,character:’B’,gender:1,money:21000})”;

graphDb.execute(cql);

tx.success();

tx.close();

System.out.println(“Database Shutdown!”);

graphDb.shutdown();

}

}

package com.lagou;

import org.neo4j.graphdb.*;

import org.neo4j.graphdb.factory.GraphDatabaseFactory;

import java.io.File;

import java.util.HashMap;

import java.util.Map;

public class EmbeddedNeo4jQueryAll { private static final File databaseDirectory = new File( “target/graph.db” );

public static void main(String[] args) {

GraphDatabaseService graphDb = new

GraphDatabaseFactory().newEmbeddedDatabase(databaseDirectory);

System.out.println(“Database Load!”);

String cql = “MATCH (a:Person) where a.money < $money return a”;

Map paramerters = new HashMap();

paramerters.put(“money”, 25000);

Transaction tx = graphDb.beginTx();

Result result = graphDb.execute(cql,paramerters);

while (result.hasNext()) {

Map row = result.next();

for (String key : result.columns()) {

Node nd = (Node) row.get(key);

System.out.printf(“%s = %s:%s%n”, key,

nd.getProperty(“name”),nd.getProperty(“money”));

}

}

tx.success();

tx.close();

System.out.println(“Database Shutdown!”);

graphDb.shutdown();

}

}

服务器模式

org.neo4j neo4j-ogm-bolt-driver 3.2.10


package com.lagou;

import org.neo4j.driver.*;

import static org.neo4j.driver.Values.parameters;

public class Neo4jServerMain {

public static void main(String[] args) {

Driver driver = GraphDatabase.driver( “bolt://127.0.0.1:7687”,

AuthTokens.basic( “neo4j”, “123456” ) );

Session session = driver.session();

String cql = “MATCH (a:Person) WHERE a.money > $money “ +

“RETURN a.name AS name, a.money AS money order by a.money “;

Result result = session.run( cql,parameters( “money”, 1000 ) );

while ( result.hasNext() )

{

Record record = result.next();

System.out.println( record.get( “name” ).asString() + “ “ +

record.get( “money” ).asDouble() );

}

session.close();

driver.close();

}

}


package com.lagou;

import org.neo4j.driver.*;

import static org.neo4j.driver.Values.parameters;

public class Neo4jServerMain2 {

public static void main(String[] args) {

Driver driver = GraphDatabase.driver( “bolt://127.0.0.1:7687”,

AuthTokens.basic( “neo4j”, “123456” ) );

Session session = driver.session();

String cql = “MATCH p=shortestPath((person:Person {name:$startName})-

[*]-(person2:Person {name:$endName} )) RETURN p”;

Result result = session.run( cql,parameters(“startName”,”王启

年”,”endName”,”九品射手燕小乙”) );

while ( result.hasNext() )

{

Record record = result.next();

System.out.println(record);

}

session.close();

driver.close();

}

}

SpringBoot 整合Neo4j

pom.xml配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.lagou</groupId>
  7. <artifactId>springboot_neo4j_demo</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <parent>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-parent</artifactId>
  12. <version>2.0.5.RELEASE</version>
  13. </parent>
  14. <dependencies>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-data-neo4j</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.neo4j</groupId>
  21. <artifactId>neo4j-ogm-bolt-driver</artifactId>
  22. </dependency>
  23. </dependencies>
  24. </project>

创建实体类

  1. package com.lagou.bean;
  2. import org.neo4j.ogm.annotation.*;
  3. import java.util.Set;
  4. @NodeEntity
  5. public class Person {
  6. @Id
  7. @GeneratedValue
  8. private Long id;
  9. @Property("cid")
  10. private int pid;
  11. private String name;
  12. private String character;
  13. private double money;
  14. private int age;
  15. private String description;
  16. @Relationship(type = "Friends",direction = Relationship.OUTGOING)
  17. private Set<Person> friendsPerson;
  18. public Set<Person> getFriendsPerson() {
  19. return friendsPerson;
  20. }
  21. public void setFriendsPerson(Set<Person> friendsPerson) {
  22. this.friendsPerson = friendsPerson;
  23. }
  24. public Person(Long id, int pid, String name, String character, double money, int age, String description) {
  25. this.id = id;
  26. this.pid = pid;
  27. this.name = name;
  28. this.character = character;
  29. this.money = money;
  30. this.age = age;
  31. this.description = description;
  32. }
  33. public Person() {
  34. }
  35. public Long getId() {
  36. return id;
  37. }
  38. @Override
  39. public String toString() {
  40. return "Person{" +
  41. "id=" + id +
  42. ", pid=" + pid +
  43. ", name='" + name + '\'' +
  44. ", character='" + character + '\'' +
  45. ", money=" + money +
  46. ", age=" + age +
  47. ", description='" + description + '\'' +
  48. ", friendsPerson=" + friendsPerson +
  49. '}';
  50. }
  51. public void setId(Long id) {
  52. this.id = id;
  53. }
  54. public int getPid() {
  55. return pid;
  56. }
  57. public void setPid(int pid) {
  58. this.pid = pid;
  59. }
  60. public String getName() {
  61. return name;
  62. }
  63. public void setName(String name) {
  64. this.name = name;
  65. }
  66. public String getCharacter() {
  67. return character;
  68. }
  69. public void setCharacter(String character) {
  70. this.character = character;
  71. }
  72. public double getMoney() {
  73. return money;
  74. }
  75. public void setMoney(double money) {
  76. this.money = money;
  77. }
  78. public int getAge() {
  79. return age;
  80. }
  81. public void setAge(int age) {
  82. this.age = age;
  83. }
  84. public String getDescription() {
  85. return description;
  86. }
  87. public void setDescription(String description) {
  88. this.description = description;
  89. }
  90. }

数据持久化类

  1. package com.lagou.repository;
  2. import com.lagou.bean.Person;
  3. import org.springframework.data.neo4j.annotation.Query;
  4. import org.springframework.data.neo4j.repository.Neo4jRepository;
  5. import org.springframework.data.repository.query.Param;
  6. import org.springframework.stereotype.Repository;
  7. import java.util.List;
  8. @Repository
  9. public interface PersonRepository extends Neo4jRepository<Person,Long> {
  10. /** 查看money 大于指定值的Person 列表 */
  11. //@Query("match(p:Person) where p.money>{0} return p")
  12. @Query("match(p:Person) where p.money>{money} return p")
  13. List<Person> personList(@Param("money") double money);
  14. /** 指定开始的名字 和 结束的名字 查询最短路径 限定深度为4以层包含4*/
  15. @Query("match p=shortestPath((person:Person{name:{startName}})-[*1..4]-(person2:Person {name:{endName}})) return p")
  16. List<Person> shortestPath(@Param("startName") String startName,@Param("endName") String endName);
  17. @Query("match p =(person:Person {name:{name}})-[*1..2]-(:Person) return p")
  18. List<Person> personListDept(@Param("name") String name);
  19. }

配置文件 application.yml

  1. spring:
  2. data:
  3. neo4j:
  4. username: neo4j
  5. password: 123456
  6. uri: bolt://192.168.211.133:7687

编写服务类

  1. package com.lagou.service;
  2. import com.lagou.bean.Person;
  3. import com.lagou.repository.PersonRepository;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. @Service("personService")
  9. public class Neo4jPersonService {
  10. @Autowired
  11. private PersonRepository personRepository;
  12. public List<Person> getAll(){
  13. List<Person> datas = new ArrayList<>();
  14. personRepository.findAll().forEach(person -> datas.add(person));
  15. return datas;
  16. }
  17. public Person save(Person person){
  18. return personRepository.save(person);
  19. }
  20. public List<Person> personList(double money){
  21. return personRepository.personList(money);
  22. }
  23. public List<Person> shortestPath(String startName,String endName){
  24. return personRepository.shortestPath(startName,endName);
  25. }
  26. public List<Person> personListDept(String name){
  27. return personRepository.personListDept(name);
  28. }
  29. }

编写测试类

  1. package com.lagou;
  2. import com.lagou.bean.Person;
  3. import com.lagou.service.Neo4jPersonService;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.context.ApplicationContext;
  7. import java.util.List;
  8. @SpringBootApplication
  9. public class Neo4jBootAppMain {
  10. public static void main(String[] args) {
  11. ApplicationContext applicationContext = SpringApplication.run(Neo4jBootAppMain.class,args);
  12. Neo4jPersonService personService = applicationContext.getBean("personService",Neo4jPersonService.class);
  13. Person person = new Person();
  14. person.setName("testboot");
  15. person.setMoney(12345.45);
  16. person.setCharacter("A");
  17. person.setAge(11);
  18. Person p1 = personService.save(person);
  19. System.out.println(p1);
  20. System.out.println(personService.getAll());
  21. List<Person> personList = personService.personList(1000);
  22. System.out.println(personList);
  23. List<Person> personList2 = personService.shortestPath("王启年","九品射手燕小乙");
  24. System.out.println(personList2);
  25. List<Person> personList3 = personService.personListDept("范闲");
  26. for (Person pe:personList3){
  27. System.out.println(pe);
  28. }
  29. }
  30. }