入門Neo4j,在官網案例的基礎上添加了兩個方法,下文程序的功能分別是:獲取圖數據庫連接驅動、往標籤添加節點、打印節點信息、獲取所有節點數據、獲取節點和關係、關閉連接。
執行以下程序需要的lib,分別是Neo4j安裝包下的lib,以及neo4j-java-driver-x.x.x.jar
import org.neo4j.driver.v1.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;
import java.util.Iterator;
import java.util.List;
import static org.neo4j.driver.v1.Values.parameters;
public class SmallExample {
// Driver objects are thread-safe and are typically made available application-wide.
Driver driver;
public SmallExample(String uri, String user, String password)
{
// 圖數據庫驅動
driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
}
/**
* 添加節點
* @param name
*/
private void addPerson(String name)
{
// Sessions are lightweight and disposable connection wrappers.
try (Session session = driver.session())
{
// Wrapping Cypher in an explicit transaction provides atomicity
// and makes handling errors much easier.
// 寫庫操作需要事務
try (Transaction tx = session.beginTransaction())
{
// x 表示一個佔位符
tx.run("Merge (a:People {name: {x}})", parameters("x", name));
tx.success(); // Mark this write as successful.
}
}
}
/**
* 打印節點信息
* @param initial
*/
private void printPeople(String initial)
{
Session session = driver.session();
// Auto-commit transactions are a quick and easy way to wrap a read.
// 查詢name 屬性以initial 參數開頭的節點數據
StatementResult result = session.run(
"MATCH (a:People) WHERE a.name STARTS WITH {x} RETURN a.name as PeopleName ",
parameters("x", initial));
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
// Record 是一行記錄,內容是什麼取決於你return 的東西
Record record = result.next();
System.out.println("record = " + record);
// Values can be extracted from a record by index or name.
// get 的是一個別名,上面的cyther 沒有as 別名話,查詢不出來
System.out.println(record.get("PeopleName").asString());
}
}
/**
* 獲取label 中的所有節點數據
*/
private void getPeoples()
{
Session session = driver.session();
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run("MATCH (b:People) RETURN b");
// Each Cypher execution returns a stream of records.
while (result.hasNext())
{
Record record = result.next();
System.out.println("record = " + record); // Record<{b: node<250>}>,key 是b,value 是node<250>,250 代表內置id
List<Value> list = record.values();
for(Value v : list)
{
Node n = v.asNode(); // 已知value 是一個node(如,node<250>),故將其轉爲Node
// n.labels() 是一個Iterable
// n.labels().iterator().next() 獲取的是label,也就是表名的意思
System.out.println(n.labels().iterator().next() + "--" + n.id());
// 獲取節點的屬性
for(String k : n.keys())
{
System.out.println(k + "---" + n.get(k)); // 獲取屬性名和屬性值
}
System.out.println("==========================");
}
}
}
/**
* 獲取節點和關係
* 往庫裏添加關係:match (a:People),(b:People) where a.name='Ada' and b.name='Bob' merge (a)-[:Friend]-(b) return a,b
*/
private void getPeoplesAndRelation()
{
Session session = driver.session();
// Auto-commit transactions are a quick and easy way to wrap a read.
StatementResult result = session.run(
"MATCH p=(b:People)-[]-(c) RETURN p"); // return p,p 代表關係,返回的結果是一個path
// "MATCH (b:People)-[]-(c) RETURN b,c"); // 如果用這句查詢,返回的則是node,可以使用上面getPeople 進行遍歷打印
while (result.hasNext())
{
// Record 是一行記錄,內容是什麼取決於你return的東西;同樣,record.values() 也取決於查詢的是什麼類型
Record record = result.next();
System.out.println("record: " + record);
List<Value> list = record.values();
for(Value v : list)
{
Path p = v.asPath(); // 把獲取的每個value 轉爲path
Node start = p.start();
for(String k : start.keys())
{
System.out.println("Start Node's property keys: " + k + "---" + start.get(k) );
}
Iterator i = p.relationships().iterator();
while(i.hasNext())
{
Relationship r = (Relationship)i.next() ;
System.out.println("Relation Type: " + r.type());
System.out.println("Print id; start node to end node: " + r.startNodeId() + "->"+r.endNodeId());
System.out.println("Relation Id: " + r.id());
}
Node end = p.end();
for(String k : end.keys())
{
System.out.println("End Node's property keys: " + k + "---" + end.get(k) );
}
System.out.println("==========================");
}
}
}
public void close()
{
// Closing a driver immediately shuts down all open connections.
driver.close();
}
public static void main(String... args)
{
SmallExample example = new SmallExample("bolt://oda.com:7687", "neo4j", "123456");
// example.addPerson("Ada");
// example.addPerson("Alice");
// example.addPerson("Bob");
// example.printPeople("A");
// example.getPeoples();
example.getPeoplesAndRelation();
example.close();
}
}