Neo4j 以原生圖儲存著稱,擅長遍歷與關聯查詢。本文示範在 Java 專案中以嵌入模式與REST 客戶端模式兩種方式接入 Neo4j。
org.neo4j neo4j 1.9.4
neo4j.properties# 記憶體映射、自動索引、線上備份、HA 叢集等設定... keep_logical_logs=true online_backup_enabled=true # ha.server_id=1 # ha.coordinators=localhost:2181
public class Learn1 {
private static final String DB_PATH = "target/neo4j-hello-db";
private GraphDatabaseService graphDb;
private Node firstNode, secondNode;
private Relationship relationship;
private enum RelTypes implements RelationshipType { KNOWS }
public static void main(String[] args) {
Learn1 app = new Learn1();
app.createDb();
app.removeData();
app.shutDown();
}
void createDb() {
clearDb();
graphDb = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder("target/database/learn1")
.loadPropertiesFromFile(getClass().getResource("/").getPath() + "neo4j.properties")
.newGraphDatabase();
registerShutdownHook(graphDb);
try (Transaction tx = graphDb.beginTx()) {
firstNode = graphDb.createNode();
firstNode.setProperty("message", "Hello, ");
secondNode = graphDb.createNode();
secondNode.setProperty("message", "World!");
relationship = firstNode.createRelationshipTo(secondNode, RelTypes.KNOWS);
relationship.setProperty("message", "brave Neo4j ");
System.out.print(firstNode.getProperty("message"));
System.out.print(relationship.getProperty("message"));
System.out.print(secondNode.getProperty("message"));
tx.success();
}
}
void removeData() {
try (Transaction tx = graphDb.beginTx()) {
firstNode.getSingleRelationship(RelTypes.KNOWS, Direction.OUTGOING).delete();
firstNode.delete(); secondNode.delete();
tx.success();
}
}
void shutDown() { graphDb.shutdown(); }
private void clearDb() {
try { FileUtils.deleteRecursively(new File(DB_PATH)); }
catch (IOException e) { throw new RuntimeException(e); }
}
private static void registerShutdownHook(GraphDatabaseService db) {
Runtime.getRuntime().addShutdownHook(new Thread(db::shutdown));
}
}
下載 Neo4j 社群版,解壓後 bin/neo4j start,管理介面 https://localhost:7474。
com.sun.jersey jersey-client 1.17 com.sun.jersey jersey-json 1.17
public class Learn1Rest {
private static final String ROOT = "https://localhost:7474/db/data/";
public static void main(String[] args) {
Learn1Rest client = new Learn1Rest();
URI n1 = client.createNode();
client.addProperty(n1, "name", "Joe Strummer");
URI n2 = client.createNode();
client.addProperty(n2, "band", "The Clash");
}
URI createNode() {
WebResource r = Client.create().resource(ROOT + "node");
ClientResponse resp = r.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON).entity("{}").post(ClientResponse.class);
System.out.printf("POST [%s] status %d location %s%n", ROOT + "node", resp.getStatus(), resp.getLocation());
resp.close();
return resp.getLocation();
}
void addProperty(URI nodeUri, String key, String val) {
WebResource r = Client.create().resource(nodeUri + "/properties/" + key);
ClientResponse resp = r.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON).entity("\"" + val + "\"").put(ClientResponse.class);
System.out.printf("PUT [%s] status %d%n", nodeUri + "/properties/" + key, resp.getStatus());
resp.close();
}
}
| 維度 | 嵌入模式 | REST 模式 |
|---|---|---|
| 部署 | 應用內進程 | 獨立 Server 進程 |
| 效能 | 極高(無網路開銷) | 有網路延遲 |
| 擴展性 | 受限於單機記憶體 | 支援叢集與水平擴展 |
| 適用場景 | 單體應用、測試、資料量中小 | 微服務、多語言、生產叢集 |