下面介绍一下如何在java中使用neo4j图形数据库。
这里是neo4j中文的官方教程
http://docs.neo4j.org.cn/tutorials-java-embedded.html
这里是neo4j的api文档
http://components.neo4j.org/neo4j/1.8/apidocs/
第一步
首先在eclipse项目中引入neo4j的全部jar包,在项目上右键Property--> Java Build Path-->Libraries-->Add External Jars-->OK neo4j的jar包在根目录下的lib。
第二步
代码部分
为了创建或者使用一个已存在的数据库,我们要实例化一个EmbeddedGraphDatabase对象。
private static final String DB_PATH = "/Users/yangfan/Downloads/neo4j-community-2.0.2/data/graph.db";
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
registerShutdownHook(graphDb);
下面是对neo4j数据库中添加数据,因为之前的数据我全部都存在mysql数据库中,我要从mysql数据库中读取,然后转存到neo4j数据库中。这里对mysql的连接和获取不做过多介绍,直接不如正题。
在存储数据的时候,基本会用到这几个参数
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
Transaction tx;
Transaction tx = graphDb.beginTx();
try
{
// Updating operations go here
tx.success();
}
finally
{
tx.finish();
}
private static enum RelTypes implements RelationshipType {
KNOWS };
Node firstNode = graphDb.createNode();
Node secondNode = graphDb.createNode();
firstNode.setProperty("message", proA);
secondNode.setProperty("message", proB);
Relationship relationship = firstNode.createRelationshipTo(
secondNode, RelTypes.KNOWS);
relationship.setProperty("message", property);
可以先用枚举类型定义节点间的关系,然后对节点和关系添加属性和属性值。
一般情况下,我们都需要在数据库中添加索引这样可以加快下一次查询的速度,neo4j中也继承了索引功能。
nodeIndex = graphDb.index().forNodes("nodes");
nodeIndex.add(firstNode, "message",proA);
nodeIndex.add(secondNode, "message",proB);
同时也可以对节点添加标记(label),label的作用是当需要对图添加约束并且对属性加索引时。当某些节点被label时,这些节点就被映射到一个集合当中,当你下次查询某个特定的label,将返回被标记的所有节点,可以批量查询和修改。
Label label = DynamicLabel.label("node");
firstNode.addLabel(label);
secondNode.addLabel(label);
Index<Node> indexService = indexManager.forNodes("nodes");
IndexHits<Node> hit =indexService.get( "message",proA);
Node node = hit.getSingle();
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
Label label = DynamicLabel.label("node");
graphDb.findNodesByLabelAndProperty(label, "message", proA);
graphDb.getNodeById(1000);
graphDb.getRelationshipById(1000);
graphDb.getRelationshipTypes();
之后会和大家分享neo4j中对图的遍历和封装的一些图算法。