1.Java 操作neo4j
1. 引入pom
<!-- neo4j 相關的API --> <dependency> <groupId>org.neo4j.driver</groupId> <artifactId>neo4j-java-driver</artifactId> <version>1.5.0</version> </dependency> <dependency> <groupId>org.neo4j</groupId> <artifactId>neo4j</artifactId> <version>3.3.4</version> </dependency>
2. 測試查詢
其他創建、建立關系類似
package com.xm.ggn.test.neo4j; import org.neo4j.driver.v1.*; public class Neo4jTest { public static void main(String[] args) { Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "neo4j.")); Session session = driver.session(); // 查詢 StatementResult result = session.run("MATCH (a:Student) WHERE a.name = \"佩奇\" RETURN a.name as name, a.sex as sex"); while (result.hasNext()) { Record record = result.next(); String name = record.get("name").asString(); String sex = record.get("sex").asString(); System.out.println(name + "\t" + sex); } session.close(); driver.close(); } }
結果:
佩奇 男
2. Springboot 整合neo4j
1. pom引入如下:
<!-- neo4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-neo4j</artifactId> </dependency>
2. 增加配置:
spring.data.neo4j.uri=bolt://localhost:11003 spring.data.neo4j.username=neo4j spring.data.neo4j.password=neo4j.
3. 增加配置類:
package com.xm.ggn.config; import org.neo4j.ogm.session.SessionFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories; import org.springframework.data.neo4j.transaction.Neo4jTransactionManager; @Configuration @EnableNeo4jRepositories("com.xm") // 聲明neo4j repository存放地址 public class Neo4jConfig { @Value("${spring.data.neo4j.uri}") private String uri; @Value("${spring.data.neo4j.username}") private String userName; @Value("${spring.data.neo4j.password}") private String password; @Bean public org.neo4j.ogm.config.Configuration getConfiguration() { org.neo4j.ogm.config.Configuration configuration = new org.neo4j.ogm.config.Configuration.Builder().uri(uri).connectionPoolSize(100).credentials(userName, password).withBasePackages("com.xm").build(); return configuration; } @Bean public SessionFactory sessionFactory() { return new SessionFactory(getConfiguration()); } @Bean("neo4jTransaction") public Neo4jTransactionManager neo4jTransactionManager(SessionFactory sessionFactory) { return new Neo4jTransactionManager(sessionFactory); } }
4. 增加相關類
(1) bean 實體類
Group 班級標簽:
package com.xm.ggn.test.neo4j.neo4j.springdata.entity; import org.neo4j.ogm.annotation.*; import java.util.HashSet; import java.util.Set; /** * 有點類似於Mysql中的table 映射的對象類,mysql中叫做ORM,neo4j中叫做OGM [object graph mapping] */ @NodeEntity("group") // 指定label是 group public class GroupNode { @Id @GeneratedValue private Long id; /** * 班級名稱 */ @Property(name = "name") private String name; /** * 編號 */ private String num; @Relationship(type = "RelationEdge") private Set<RelationEdge> sets = new HashSet<>(); 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 getNum() { return num; } public void setNum(String num) { this.num = num; } public Set<RelationEdge> getSets() { return sets; } public void setSets(Set<RelationEdge> sets) { this.sets = sets; } public void addRelation(StudentNode sonNode, String name) { RelationEdge relationNode = new RelationEdge(this, sonNode, name); sets.add(relationNode); sonNode.getSets().add(relationNode); } }
Student 學生標簽:
package com.xm.ggn.test.neo4j.neo4j.springdata.entity; import org.neo4j.ogm.annotation.GeneratedValue; import org.neo4j.ogm.annotation.Id; import org.neo4j.ogm.annotation.NodeEntity; import org.neo4j.ogm.annotation.Relationship; import java.util.HashSet; import java.util.Set; /** * 有點類似於Mysql中的table 映射的對象類,mysql中叫做ORM,neo4j中叫做OGM [object graph mapping] */ @NodeEntity("student") // 指定label是 student public class StudentNode { @Id @GeneratedValue private Long id; /** * 學生名稱 */ private String name; /** * 性別 */ private String sex; @Relationship(type = "RelationEdge", direction = "INCOMING") private Set<RelationEdge> sets = new HashSet<>(); 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Set<RelationEdge> getSets() { return sets; } public void setSets(Set<RelationEdge> sets) { this.sets = sets; } }
RelationEdge 關系邊:
package com.xm.ggn.test.neo4j.neo4j.springdata.entity; import lombok.Data; import org.neo4j.ogm.annotation.*; @RelationshipEntity(type = "RelationEdge") @Data public class RelationEdge { @Id @GeneratedValue private Long id; // 關系名 private String name; @StartNode private GroupNode groupNode; @EndNode private StudentNode studentNode; public RelationEdge(GroupNode parentNode, StudentNode sonNode, String name) { this.groupNode = parentNode; this.studentNode = sonNode; this.name = name; } }
GroupDao:
package com.xm.ggn.test.neo4j.neo4j.springdata.dao; import com.xm.ggn.test.neo4j.neo4j.springdata.entity.GroupNode; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface GroupDao extends Neo4jRepository<GroupNode, Long> { }
StudentDao:
package com.xm.ggn.test.neo4j.neo4j.springdata.dao; import com.xm.ggn.test.neo4j.neo4j.springdata.entity.StudentNode; import org.springframework.data.neo4j.repository.Neo4jRepository; public interface StudentDao extends Neo4jRepository<StudentNode, Long> { }
Neo4jController:
package com.xm.ggn.test.neo4j.neo4j.springdata.controller; import com.xm.ggn.test.neo4j.neo4j.springdata.dao.GroupDao; import com.xm.ggn.test.neo4j.neo4j.springdata.dao.StudentDao; import com.xm.ggn.test.neo4j.neo4j.springdata.entity.GroupNode; import com.xm.ggn.test.neo4j.neo4j.springdata.entity.RelationEdge; import com.xm.ggn.test.neo4j.neo4j.springdata.entity.StudentNode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Set; @RestController @RequestMapping("/node") public class Neo4jController { @Autowired private GroupDao groupDap; @Autowired private StudentDao studentDap; @GetMapping(value = "/create") public void createNodeRelation() { StudentNode studentNode1 = new StudentNode(); studentNode1.setName("佩奇"); studentNode1.setSex("男"); StudentNode studentNode2 = new StudentNode(); studentNode2.setName("神經"); studentNode2.setSex("女"); studentDap.save(studentNode1); studentDap.save(studentNode2); GroupNode groupNode = new GroupNode(); groupNode.setName("宏哥班"); groupNode.setNum("298"); // 增加關系 groupNode.addRelation(studentNode1, "includes"); groupNode.addRelation(studentNode2, "includes"); groupDap.save(groupNode); } @GetMapping(value = "/find") public void findNodes() { Iterable<GroupNode> parentNodes = groupDap.findAll(); for (GroupNode parentNode : parentNodes) { Set<RelationEdge> relationNodeSet = parentNode.getSets(); for (RelationEdge relationNode : relationNodeSet) { System.out.println("id:" + parentNode.getId() + " name:" + parentNode.getName() + " 關系:" + relationNode.getName() + "子節點:" + relationNode.getStudentNode().getName()); } } } }
結果:
(1) 測試創建
$ curl http://localhost:8088/node/create % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 59 0 59 0 0 6 0 --:--:-- 0:00:09 --:--:-- 17{ "success":true,"data":null,"msg":"成功","errorCode":"0"}
到neo4j查看:
MATCH (n) RETURN n LIMIT 25
結果:
(2) 測試查詢
$ curl http://localhost:8088/node/find % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 59 0 59 0 0 236 0 --:--:-- --:--:-- --:--:-- 252{"success":true,"data":null,"msg":"成功","errorCode":"0"}
控制台日志:
id:3 name:宏哥班 關系:includes子節點:神經 id:3 name:宏哥班 關系:includes子節點:佩奇
補充: 還可以自己手動寫CQL
@Autowired private Session session; @GetMapping(value = "/create2") public void createNodeRelation2() { String cypherSQL = "create (n:student{name: '瓜哥', sex: '男'})"; session.query(cypherSQL, new HashMap<>()); String mergeSQL = "match (a:student{name: '瓜哥'}), (b:group{num: '298'}) merge(a)-[:belongsto]->(b)"; session.query(mergeSQL, new HashMap<>()); }
補充:Neo4j 自動配置原理
其自動配置是在類org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration里面的,其默認的配置屬性是在:Neo4jProperties