Neo4j學習筆記(1)——使用Java API實現簡單的增刪改查


項目的創建及配置

因為Neo4j依賴的jar包比較多,所以推薦使用Maven來管理。

首先創建一個Maven Project,添加依賴:

復制代碼
<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j</artifactId>
    <version>3.2.6</version>
</dependency>
復制代碼

使用的是3.2.6版本,對應版本的Neo4j安裝地址摸我

使用嵌入式數據庫

配置好之后,就可以開始了,第一步是學習開啟和關閉數據庫。

無論是創建一個新的數據庫,還是打開一個已有的數據庫,首先都需要創建一個GraphDatabaseService實例。

graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );

GraphDatabaseService實例可以被多個線程共享,但是一個數據庫只允許有一個Service實例。

關閉數據庫可以調用shutdown()方法。

為了確保數據庫正確地關閉,可以添加一個ShutdownHook來實現關閉數據庫的動作。

復制代碼
private static void registerShutdownHook(final GraphDatabaseService graphDb) {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                graphDb.shutdown();
            }
        });
    }
復制代碼

還可以通過API對數據庫的一些配置進行設置。

一種方法是加載.conf配置文件。

GraphDatabaseService graphDb = new GraphDatabaseFactory()
    .newEmbeddedDatabaseBuilder( testDirectory.graphDbDir() )
    .loadPropertiesFromFile( pathToConfig + "neo4j.conf" )
    .newGraphDatabase();

另一種方法就是通過方法來添加。

復制代碼
GraphDatabaseService graphDb = new GraphDatabaseFactory()
    .newEmbeddedDatabaseBuilder( testDirectory.graphDbDir() )
    .setConfig( GraphDatabaseSettings.pagecache_memory, "512M" )
    .setConfig( GraphDatabaseSettings.string_block_size, "60" )
    .setConfig( GraphDatabaseSettings.array_block_size, "300" )
    .newGraphDatabase();
復制代碼

創建一個只讀的數據庫,數據庫必須已經存在。

graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( dir )
        .setConfig( GraphDatabaseSettings.read_only, "true" )
        .newGraphDatabase(); 

更多配置信息可以看GraphDatabaseSettings類的文檔

創建節點和關系

圖數據庫是一個有向圖,由通過關系Relationships連接的節點Nodes構成,節點和關系可以有自己的屬性Properties。 

關系的類型可以通過枚舉enum創建(Label也可以):

private static enum RelTypes implements RelationshipType
{
    RELEASED;
}

 在Neo4j中,對於數據庫的操作需要在一個事務transaction中執行。

復制代碼
try ( Transaction tx = graphDb.beginTx() )
{
    // 數據庫操作寫在事務提交之前
    tx.success();
}
復制代碼

下面是一個簡單的實例,實現了節點和關系的創建。

復制代碼
try (Transaction tx = graphDb.beginTx()) {
            // 創建標簽
            label1 = Label.label("Musician");
            label2 = Label.label("Album");
            // 創建節點
            node1 = graphDb.createNode(label1);
            node1.setProperty("name", "Jay Chou");
            node2 = graphDb.createNode(label2);
            node2.setProperty("name", "Fantasy");
            // 創建關系及屬性
            relationship = node1.createRelationshipTo(node2, RelTypes.RELEASED);
            relationship.setProperty("date", "2001-09-14");
            // 結果輸出
            System.out.println("created node name is" + node1.getProperty("name"));
            System.out.println(relationship.getProperty("date"));
            System.out.println("created node name is" + node2.getProperty("name"));
            // 提交事務
            tx.success();
        }
復制代碼

 對於節點,除了設置屬性,還可以添加標簽Labels。添加標簽之后就相當於對節點進行了分組,使節點的查詢和管理更加清晰和方便,並且提高了查詢的性能。標簽是一個可選項,沒有標簽也是可以的。

與關系數據庫相比,標簽相當於表名。一個節點相當於表中的一行數據,節點的屬性就是字段。區別是,一個節點可以有多個標簽

可以看到我們創建了兩個節點,名字是“周傑倫”和“《范特西》”,對應的標簽分別是音樂家和專輯。

他們之間通過“發行”這個關系連接,其中發行的屬性為發行日期。

打開Neo4j數據庫,輸入查詢語句match (n) return n,可以看到數據被寫入了進來。

查詢及更新

知道了節點的標簽和一條屬性,就可以通過findNode()方法查詢節點。

然后使用setProperty()方法來更新和添加屬性。 

復制代碼
try (Transaction tx = graphDb.beginTx()) {
            // 查詢節點
            Label label = Label.label("Musician");
            Node node = graphDb.findNode(label, "name", "Jay Chou");
            System.out.println("query node name is " + node.getProperty("name"));
            // 更新節點
            node.setProperty("birthday", "1979-01-18");
            System.out.println(node.getProperty("name") + "'s birthday is " + node.getProperty("birthday", new String()));
            // 提交事務
            tx.success();
        }
復制代碼

打開Neo4j查看結果:

刪除關系和節點

刪除數據時,只需要執行相關實體對應的delete()方法即可。

執行刪除操作時,需要遵守如下規則:刪除節點時,如果該節點存在關系,則必須先刪除關系。這么做的目的是保證一條關系永遠有起始和結束節點。

復制代碼
try (Transaction tx = graphDb.beginTx()) {
            // 獲得節點
            Label label = Label.label("Album");
            Node node = graphDb.findNode(label, "name", "Fantasy");
            // 獲得關系
            Relationship relationship = node.getSingleRelationship(RelTypes.Released, Direction.INCOMING);
            // 刪除關系和節點
            relationship.delete();
            relationship.getStartNode().delete();
            node.delete();
            tx.success();
        }
復制代碼

完整代碼

復制代碼
  1 package edu.heu.kg.graphdb;
  2 
  3 import java.io.File;
  4 
  5 import org.neo4j.graphdb.Direction;
  6 import org.neo4j.graphdb.GraphDatabaseService;
  7 import org.neo4j.graphdb.Label;
  8 import org.neo4j.graphdb.Node;
  9 import org.neo4j.graphdb.Relationship;
 10 import org.neo4j.graphdb.RelationshipType;
 11 import org.neo4j.graphdb.Transaction;
 12 import org.neo4j.graphdb.factory.GraphDatabaseFactory;
 13 
 14 /**
 15  * @ClassName: GraphDatabaseHelloWorld
 16  * @Description: TODO
 17  * @author LJH
 18  * @date 2017年12月22日 下午4:09:33
 19  */
 20 public class GraphDatabaseHelloWorld {
 21 
 22     private static final File DB_PATH = new File("D:\\Neo4jDb");
 23     private static GraphDatabaseService graphDb;
 24 
 25     private static void registerShutdownHook(final GraphDatabaseService graphDb) {
 26         Runtime.getRuntime().addShutdownHook(new Thread() {
 27             @Override
 28             public void run() {
 29                 graphDb.shutdown();
 30             }
 31         });
 32     }
 33 
 34     private static enum RelTypes implements RelationshipType {
 35         RELEASED;
 36     }
 37 
 38     @SuppressWarnings("unused")
 39     private static void addData() {
 40         Node node1;
 41         Node node2;
 42         Label label1;
 43         Label label2;
 44         Relationship relationship;
 45 
 46         try (Transaction tx = graphDb.beginTx()) {
 47             // 創建標簽
 48             label1 = Label.label("Musician");
 49             label2 = Label.label("Album");
 50             // 創建節點
 51             node1 = graphDb.createNode(label1);
 52             node1.setProperty("name", "Jay Chou");
 53             node2 = graphDb.createNode(label2);
 54             node2.setProperty("name", "Fantasy");
 55             // 創建關系及屬性
 56             relationship = node1.createRelationshipTo(node2, RelTypes.Released);
 57             relationship.setProperty("date", "2001-09-14");
 58             // 結果輸出
 59             System.out.println("created node name is " + node1.getProperty("name"));
 60             System.out.println(relationship.getProperty("date"));
 61             System.out.println("created node name is " + node2.getProperty("name"));
 62             // 提交事務
 63             tx.success();
 64         }
 65         graphDb.shutdown();
 66     }
 67 
 68     @SuppressWarnings("unused")
 69     private static void queryAndUpdate() {
 70         try (Transaction tx = graphDb.beginTx()) {
 71             // 查詢節點
 72             Label label = Label.label("Musician");
 73             Node node = graphDb.findNode(label, "name", "Jay Chou");
 74             System.out.println("query node name is " + node.getProperty("name"));
 75             // 更新節點
 76             node.setProperty("birthday", "1979-01-18");
 77             System.out
 78                     .println(node.getProperty("name") + "'s birthday is " + node.getProperty("birthday", new String()));
 79             // 提交事務
 80             tx.success();
 81         }
 82         graphDb.shutdown();
 83     }
 84 
 85     @SuppressWarnings("unused")
 86     private static void delete() {
 87         try (Transaction tx = graphDb.beginTx()) {
 88             // 獲得節點
 89             Label label = Label.label("Album");
 90             Node node = graphDb.findNode(label, "name", "Fantasy");
 91             // 獲得關系
 92             Relationship relationship = node.getSingleRelationship(RelTypes.RELEASED, Direction.INCOMING);
 93             // 刪除關系和節點
 94             relationship.delete();
 95             relationship.getStartNode().delete();
 96             node.delete();
 97             tx.success();
 98         }
 99         graphDb.shutdown();
100     }
101 
102     public static void main(String[] args) {
103         graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
104         registerShutdownHook(graphDb);
105         addData();
106         // queryAndUpdate();
107         // delete();
108 
109     }
110 
111 }
復制代碼

轉載請注明原文鏈接:http://www.cnblogs.com/justcooooode/p/8179202.html

參考資料

 https://neo4j.com/docs/java-reference/3.2

《Neo4j 實戰》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM