Neo4j 是一个图数据库,主要包括节点和关系。节点和关系都可以包含属性。
下载Neo4j:https://neo4j.com/artifact.php?name=neo4j-community-3.3.5-windows.zip
解压后运行:
D:\Tools\neo4j-community-3.3.5\bin>neo4j.bat console
2018-04-13 06:03:08.826+0000 INFO ======== Neo4j 3.3.5 ========
2018-04-13 06:03:08.853+0000 INFO Starting...
2018-04-13 06:03:09.879+0000 INFO Bolt enabled on 127.0.0.1:7687.
2018-04-13 06:03:14.553+0000 INFO Started.
2018-04-13 06:03:15.612+0000 INFO Remote interface available at http://localhost:7474/
访问Neoj Browser: http://127.0.0.1:7474/browser/,第一次访问会提示修改密码。
点击左边栏的Database,
Node Labels 表示存在的节点
Relationship Types表示存在的关系
Property Keys 表示节点或者关系的属性
在中间部分的上面可以输入要执行的命令。
接下来通过命令创建一个节点,节点的名字是Message,有两个属性title和text。
CREATE (:Message { title:'Welcome',text:'Hello world!' });
可以看到左边栏的Node Labels下面出现了 Message 节点。
现在可以通过下面的命令查询刚才创建的节点:
MATCH (n:Message) RETURN n LIMIT 25;
CREATE (:Language { name:'Java',version:'1.8' });
有了Message节点和Language节点后,可以添加两个节点之间的关系了。
MATCH (m:Message),(c:Language)
WHERE m.title = 'Welcome' AND c.name = 'Java'
CREATE (m)-[:ACCESSED_FROM]->(c);
现在在左边栏Relationship Types下面可以看到刚才创建的关系,名字是ACCESSED_FROM。点击ACCESSED_FROM,可以图形化查看两个节点之间的关系。
下面查询刚才创建的关系:
MATCH (m:Message)-[:ACCESSED_FROM]->(l:Language)
RETURN m.title,l.name;
新建项目添加maven依赖:
<dependency>
<groupId>org.neo4j.drivergroupId>
<artifactId>neo4j-java-driverartifactId>
<version>1.2.1version>
dependency>
下面是Java测试代码:
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Values;
public class Neo4jTest {
public static void main(String[] args) {
Driver driver = GraphDatabase.driver("bolt://127.0.0.1:7687", AuthTokens.basic("neo4j", "000000"));
Session session = driver.session();
session.run("CREATE (:Message {title: 'Hello', text: 'hello world'})");
session.run("CREATE (:Language {name: 'Java8', version: '1.8'})");
String createRelationship = "MATCH (m:Message),(l:Language) WHERE m.title = 'Hello' AND l.name='Java8'"
+ " CREATE (m)-[:HelloJava8]->(l);";
session.run(createRelationship);
String queryRelationship = "MATCH (m:Message)-[:HelloJava8]->" + "(l:Language {name:{language}}) "
+ "RETURN m.title,l.name;";
StatementResult resultSet = session.run(queryRelationship, Values.parameters("language", "Java8"));
while (resultSet.hasNext()) {
Record result = resultSet.next();
System.out.println(result.get("m.title") + " from " + result.get("l.name"));
}
session.close();
}
}
运行结果:
“Hello” from “Java8”