Java connection of two ways Neo4j

Two ways 1.Neo4j database

Neo4j can be run in two ways:

  • Java applications embedded database
  • Stand-alone server through REST

Either way, the choice does not affect the way access to and use of the database. It is the nature of the application (either stand-alone server or client-server) performance, monitoring, and data-driven security architecture of choice.

1.1Neo4j Server (server database)

Neo4j Server is the best choice for interoperability, security and surveillance. In fact, REST interface allows for all modern platforms and programming languages ​​to interoperate with it. In addition, as a standalone application, it is more than an embedded security configuration (client's potential failure does not affect the server), and easier to monitor. If we choose to use this mode, the application will act as our client Neo4j server.

Previous blog post describes the installation Neo4j, is actually a server database .

Neo4j to connect to the server, you must use the REST API, so you can use any programming language REST library to access the database. Although you can use any HTTP request can send programming language, but you can also use REST calls package written in multiple languages ​​and platforms online libraries, such as Python, .NET, PHP, Ruby, Node.js and so on.

1.2An embedded database (embedded database)

Neo4j is the best choice for embedded database performance. It runs a managed process it and store the data in the same client application in a given path. Thus, you must create an embedded database programmatically. We chose the embedded database for the following reasons:

  • When we use the Java programming language as our project
  • When our application is independent

2. The program code

2.1 configuration files

They are connected in two ways using Maven project, the following configuration file, the configuration file that includes two noted methods require jar package.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.neo4j</groupId>
  <artifactId>conn</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>conn</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
    <!-- 服务器开发需要的jar包 -->
      <groupId>org.neo4j.driver</groupId>
      <artifactId>neo4j-java-driver</artifactId>
      <version>1.5.0</version>
    </dependency>
    <dependency>
    <!-- 嵌入式开发需要的jar包 -->
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j</artifactId>
        <version>3.3.4</version>
    </dependency>
  </dependencies>
   <repositories>
    <repository>
        <id>neo4j</id>
        <url>http://m2.neo4j.org/content/repositories/releases/</url>
        <releases>
            <enabled>true</enabled>
        </releases>
    </repository>
  </repositories> 

</project>

   
   

2.2 server development code

Note that using server development way, Neo4j state must be open

package com.neo4j.conn;

import org.neo4j.driver.v1.*;
import static org.neo4j.driver.v1.Values.parameters;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        Driver driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "" ) );
        Session session = driver.session();
        session.run( "CREATE (a:Person {name: {name}, title: {title}})",
                parameters( "name", "Arthur001", "title", "King001" ) );

        StatementResult result = session.run( "MATCH (a:Person) WHERE a.name = {name} " +
                                              "RETURN a.name AS name, a.title AS title",
                parameters( "name", "Arthur001" ) );
        while ( result.hasNext() )
        {
            Record record = result.next();
            System.out.println( record.get( "title" ).asString() + " " + record.get( "name" ).asString() );
        }
        session.close();
        driver.close();
    }
}

   
   

2.3 Embedded Development

package com.neo4j.conn;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.neo4j.cypher.internal.javacompat.ExecutionEngine;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.*;
public class Test1 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(new File("Data/Test"));
        System.out.println("Database Load!");
        //开启事务
        try (Transaction tx = graphDb.beginTx()) {
            // Perform DB operations
            Node steve = graphDb.createNode(Labels.USER);
            steve.setProperty("name", "Steve");
            Node linda = graphDb.createNode(Labels.USER);
            linda.setProperty("name", "Linda");
            steve.createRelationshipTo( linda, RelationshipTypes.IS_FRIEND_OF );
            System.out.println("created node name is" + steve.getProperty("name"));
            tx.success();
        }
        //查询数据库
        String query ="match (n:USER) return n.name as name";
        Map<String, Object >parameters = new HashMap<String, Object>();
         try ( Result result = graphDb.execute( query, parameters ) )
         {
             while ( result.hasNext() )
             {
                 Map<String, Object> row = result.next();
                 for ( String key : result.columns() )
                 {
                     System.out.printf( "%s = %s%n", key, row.get( key ) );
                 }
             }
         }

         registerShutdownHook(graphDb);
         System.out.println("Database Shutdown!");

    }
    //设置标签,但是必须继承于接口label
    public enum Labels implements Label {
        USER,
        MOVIE;
    }

    public enum RelationshipTypes implements RelationshipType {
        IS_FRIEND_OF,
        HAS_SEEN;
    }


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

}

   
   

2.4 Summary

This is just a quick start, the code is very simple, if you want to know more detail, see my follow-up blog post.

3. References

Learing Cypher

Original Address: https: //blog.csdn.net/endlessseaofcrow/article/details/80015930

Guess you like

Origin www.cnblogs.com/jpfss/p/11248267.html