Neo4j图数据库

01. 图数据库

图数据库是专门存储和检索大量信息网络的存储引擎。它可以有效地将数据存储为节点和关系,并允许高性能检索和查询这些结构。属性可以添加到节点和关系。节点可以用零个或多个标签标注,关系总是定向和命名。

1. Neo4j

Neo4j是一个开源的NOSQL图形数据库。它将数据转换成化为节点、关系和属性。使用图查询语言Cypher,支持集群,支持ACID事务,并发控制、事务恢复、高可用性。

介绍(第一章):
https://neo4j.com/docs/developer-manual/3.2/introduction/

基础入门:https://neo4j.com/developer/java/

Java开发手册:http://neo4j.com/docs/java-reference/current/

Java API: https://neo4j.com/docs/java-reference/current/javadocs/

2. 图查询语言Cypher

1. 查询语言文档(第三章)

https://neo4j.com/docs/developer-manual/3.2/cypher/clauses/

2. 创建节点

CREATE (Keanu:Person {name:'Keanu Reeves', born:1964})
CREATE (Carrie:Person {name:'Carrie-Anne Moss', born:1967})	

前面的Keanu实际没有作用,

3. 建立联系

CREATE
(Keanu)-[:ACTED_IN {roles:['Neo']}]->(TheMatrix),
(Carrie)-[:ACTED_IN {roles:['Trinity']}]->(TheMatrix)	

:['Neo']指的是关系上的属性。

4. 删除

删除所有节点和关系 :

MATCH (n) DETACH DELETE n

删除CLASS标签所有节点和关系:

MATCH (n:CLASS) DETACH DELETE n

MATCH (n:CLASS) where n.title='A Few Good Men' DETACH DELETE n

5. match(查找)

1. 返回数据库中所有类型的节点
MATCH (n) RETURN n

返回独立节点:

MATCH (tom {name: "Tom Hanks"}) RETURN tom
MATCH (people:Person) RETURN people.name LIMIT 10
2. 标签类型的所有节点
MATCH (movie:Movie) RETURN movie.title
3. 不带联系指向的match
MATCH (director { name: 'Nora Ephron' })--(movie)
RETURN movie.title

返回所有'Nora Ephron'导演的电影。符号‘--’指的是不考虑联系的类型和方向。

4. 带联系指向的match
MATCH (:Person { name: 'Nora Ephron' })-->(movie)
RETURN movie.title

这个只知道有联系,但是不清楚联系的类型。

5. 带联系指向和类型的match
MATCH (wallstreet:Movie { title: 'The Matrix Reloaded' })<-[:ACTED_IN]-(actor)
RETURN actor.name

返回所有acted in 'The Matrix Reloaded'演员。
带了联系指向和类型。

MATCH (director:Person)-[:DIRECTED]->(movie)
WHERE director.name = "Vincent Ward"
RETURN movie.title

箭头的指向实际上就是关系的指向。
等价于:

MATCH (movie)<-[:DIRECTED]-(director)
WHERE director.name = "Vincent Ward"
RETURN movie.title
6. 多类型匹配
MATCH (movie { title: 'The Matrix Reloaded' })<-[:ACTED_IN|:DIRECTED]-(person)
RETURN person.name

返回和'The Matrix Reloaded'是演员或者导演关系的人

7. 查询这个节点类和其相关调用
MATCH (c:CLASS{ name: 'PreFetchServiceImpl' })--(class)RETURN c,class

3. Java API

1. 创建节点

CREATE (n:CLASS {id : {id}, name: {name}, type: {type}, appCode : {appCode}, pack : {pack}, urls : {urls}})

2. 建立联系

MATCH (a:CLASS),(b:CLASS) WHERE a.id = {aId} AND b.id = {bId} CREATE (a)-[r:IMPLEMENT]->(b)

a指向b,联系的名称是“IMPLEMENT”

Demo:

Driver driver = GraphDatabase.driver("bolt://127.0.0.1:7687", AuthTokens.basic("neo4j", "1234"));
	Session session = driver.session();

	session.run("CREATE (a:Person {name: {name}, title: {title}})",
			parameters("name", "Arthur", "title", "King"));

	StatementResult result = session.run("MATCH (a:Person) WHERE a.name = {name} " +
					"RETURN a.name AS name, a.title AS title",
			parameters("name", "Arthur"));
	while (result.hasNext()) {
		Record record = result.next();
		System.out.println(record.get("title").asString() + " " + record.get("name").asString());
	}

	session.close();
	driver.close();
posted @ 2017-08-04 11:26  神话小小哥  阅读(884)  评论(0编辑  收藏  举报