Rubin's Blog

  • 首页
  • 关于作者
  • 隐私政策
享受恬静与美好~~~
分享生活的点点滴滴~~~
  1. 首页
  2. Neo4j
  3. 正文

Neo4j之程序访问

2021年 11月 10日 705点热度 0人点赞 0条评论

Neo4j数据库访问

Neo4j的访问的两种方式:

  • 嵌入式数据库
  • 服务器模式(通过REST的访问)

它是由应用程序的性质(Neo4j是独立服务器还是和程序在一起)、性能、监控和数据安全性来决定架构选择。

嵌入式数据库

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

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

服务器模式

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

Java客户端操作Neo4j

嵌入式模式

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j</artifactId>
  <version>3.5.5</version>
</dependency>
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();
 }
}
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<String, Object> paramerters = new HashMap<String, Object>();
    paramerters.put("money", 25000);
    Transaction tx = graphDb.beginTx();
    Result result = graphDb.execute(cql, paramerters);
    while (result.hasNext()) {
      Map<String, Object> 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();
 }
}

服务器模式

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j-ogm-bolt-driver</artifactId>
  <version>3.2.10</version>
</dependency>
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();
   }
}
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

1.导入jar包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-neo4j</artifactId>
</dependency>
<dependency>
   <groupId>org.neo4j</groupId>
   <artifactId>neo4j-ogm-bolt-driver</artifactId>
</dependency>

2.建立实体类

@NodeEntity
public class Person {
  @Id
  @GeneratedValue
  private Long id;
  @Property("cid")
  private int pid;
  @Property
  private String name;
  private String character;
  private double money;
    private int gender;
  private int age;
  private String description;
  @Relationship(type = "Friends", direction = Relationship.INCOMING)
  private Set<Person> relationPersons;
  @Override
  public String toString() {
    return "Person{" +
        "id=" + id +
        ", pid=" + pid +
        ", name='" + name + '\'' +
        ", character='" + character + '\'' +
        ", money=" + money +
        ", gender=" + gender +
        ", age=" + age +
        ", description='" + description + '\'' +
        ", relationPersons=" + relationPersons +
       '}';
   }
  public Person() {
   }
  public Person(Long id, String name, String character, double money, int
 gender, int age, String description) {
    this.id = id;
    this.name = name;
    this.character = character;
    this.money = money;
    this.gender = gender;
    this.age = age;
    this.description = description;
   }
 
  public Set<Person> getRelationPersons() {
    return relationPersons;
   }
  public void setRelationPersons(Set<Person> relationPersons) {
    this.relationPersons = relationPersons;
   }
  public Long getId() {
    return id;
   }
  public void setId(Long id) {
    this.id = id;
   }
  public String getName() {
    return name;
   }
  public void setName(String name) {
    this.name = name;
    }
  public String getCharacter() {
    return character;
   }
  public void setCharacter(String character) {
    this.character = character;
   }
  public double getMoney() {
    return money;
   }
  public void setMoney(double money) {
    this.money = money;
   }
  public int isGender() {
    return gender;
   }
  public void setGender(int gender) {
    this.gender = gender;
   }
  public int getAge() {
    return age;
   }
  public void setAge(int age) {
    this.age = age;
   }
  public String getDescription() {
    return description;
   }
  public void setDescription(String description) {
    this.description = description;
   }
}
  

3.数据持久化类

@Repository
public interface PersonRepository extends Neo4jRepository<Person,Long> {
   @Query("MATCH (p:Person) WHERE p.money > {0} RETURN p")
   List<Person> personList(double money);
   @Query("MATCH p=shortestPath((person:Person {name:{0}})-[*1..4]-
(person2:Person {name:{1}}) ) RETURN p")
   List<Person> shortestPath(String startName, String endName);
}

或者使用

  @Query("MATCH (p:Person) WHERE p.money>{money} return p")
  List<Person> personList(@Param("money") double money);
  @Query("MATCH p=shortestPath((person:Person{name:{startName}})-[*1..4]-
(person2:Person {name:{endName}})) RETURN p")
  List<Person> shortestPath(@Param("startName") String
 startName,@Param("endName") String endName);

4.配置文件 application.yml

spring:
data:
 neo4j:
  username: neo4j
  password: 123456
  uri: bolt://192.168.211.133:7687
   #uri: http://192.168.211.133:7474
   #uri: file:///target/graph.db 

5.编写服务类

@Service
public class Neo4jPersonService {
  @Autowired
  private PersonRepository personRepository;
  public List<Person> personList(){
    return personRepository.personList();
   }
  public Person save(Person  person){
    return personRepository.save(person);
   }
    public List<Person> shortestPath(String startName, String endName){
    return personRepository.shortestPath(startName,endName);
   }
}

6.编写测试类

@SpringBootApplication
public class TestNeo4jBootApp {
  public static void main(String[] args) {
    ApplicationContext app =
 SpringApplication.run(TestNeo4jBootApp.class,args);
    Neo4jPersonService personService =
 app.getBean(Neo4jPersonService.class);
    System.out.println(personService);
    List<Person> datas = personService.personListAll();
    System.out.println(datas);
    System.out.println(personService. shortestPath("王启年", "九品射手燕小
乙"));
   }
}

以上就是本文的全部内容。欢迎各位小伙伴积极留言交流~~~

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: Neo4j
最后更新:2022年 6月 9日

RubinChu

一个快乐的小逗比~~~

打赏 点赞
< 上一篇

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复
文章目录
  • Neo4j数据库访问
    • 嵌入式数据库
    • 服务器模式
  • Java客户端操作Neo4j
    • 嵌入式模式
    • 服务器模式
  • SpringBoot整合Neo4j
最新 热点 随机
最新 热点 随机
问题记录之Chrome设置屏蔽Https禁止调用Http行为 问题记录之Mac设置软链接 问题记录之JDK8连接MySQL数据库失败 面试系列之自我介绍 面试总结 算法思维
SpringCloud Alibaba之Sentinel Redis之扩展功能 ZooKeeper之深入进阶 Docker之创建镜像 MongoDB之架构设计 Kafka之集群与运维

COPYRIGHT © 2021 rubinchu.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

京ICP备19039146号-1