Neo4j学习笔记-Embedded嵌入模式简单示例

Java版本:jdk1.8.0_121

Neo4j版本:neo4j-community-3.5.22

相关依赖如下:

<neo4j.version>3.5.22</neo4j.version>
<neo4j.graph.version>3.5.22</neo4j.graph.version>
<neo4j.driver.version>4.1.1</neo4j.driver.version>

<!-- Neo4j依赖包 -->
<dependency>
	<groupId>org.neo4j</groupId>
	<artifactId>neo4j</artifactId>
    <version>${neo4j.version}</version>
</dependency>

<!-- Neo4jGraph依赖包 -->
<dependency>
	<groupId>org.neo4j</groupId>
	<artifactId>neo4j-graph-algo</artifactId>
	<version>${neo4j.graph.version}</version>
</dependency>

<!-- Neo4jDriver依赖包 -->
<dependency>
	<groupId>org.neo4j.driver</groupId>
	<artifactId>neo4j-java-driver</artifactId>
	<version>${neo4j.driver.version}</version>
</dependency>

相关配置如下

@Configuration
public class Neo4jConfiguration {

    @Value("${spring.data.neo4j.storedir}")
    private String neo4jStoreDir = null;

    @Bean("graphDatabaseService")
    public GraphDatabaseService graphDatabaseService() {
        return new GraphDatabaseFactory().newEmbeddedDatabase(new File(neo4jStoreDir));
    }

}

相关示例代码如下:

import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseBuilder;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;

import java.io.File;
import java.net.URL;
import java.util.Map;
import java.util.function.Consumer;

public class GraphUtils {

    public static GraphDatabaseService createGraphDatabaseService(String neo4jStoreDir) throws RuntimeException {
        return new GraphDatabaseFactory().newEmbeddedDatabase(new File(neo4jStoreDir));
    }

    public static GraphDatabaseService createGraphDatabaseService(String neo4jStoreDir, String fileName) throws RuntimeException {
        return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File(neo4jStoreDir))
            .loadPropertiesFromFile(fileName).newGraphDatabase();
    }

    public static GraphDatabaseService createGraphDatabaseService(String neo4jStoreDir, URL url) throws RuntimeException {
        return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File(neo4jStoreDir))
            .loadPropertiesFromURL(url).newGraphDatabase();
    }

    /**
     * @param neo4jStoreDir
     * @param configProps
     * dbms.security.procedures.unrestricted=apoc.*
     * @return
     * @throws RuntimeException
     */
    public static GraphDatabaseService createGraphDatabaseService(String neo4jStoreDir, Map<String, String> configProps) throws RuntimeException {
        GraphDatabaseBuilder graphDatabaseBuilder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File(neo4jStoreDir));
        for (Map.Entry<String, String> entry : configProps.entrySet()) {
            graphDatabaseBuilder.setConfig(entry.getKey(), entry.getValue());
        }
        return graphDatabaseBuilder.newGraphDatabase();
    }

    public static Node createNode(GraphDatabaseService graphDatabaseService, Object... properties) throws RuntimeException {
        return setProperties(graphDatabaseService.createNode(), properties);
    }

    public static Node createNode(GraphDatabaseService graphDatabaseService, Label label, Object... properties) throws RuntimeException {
        return setProperties(graphDatabaseService.createNode(label), properties);
    }

    public static <T extends PropertyContainer> T setProperties(T entity, Object[] properties) throws RuntimeException {
        for (int i = 0, len = properties.length; i < len; i++) {
            String key = properties[i++].toString();
            Object value = properties[i];
            entity.setProperty(key, value);
        }
        return entity;
    }

    public static void query(String neo4jStoreDir, String query, Consumer<Result> consumer) {
        GraphDatabaseService graphDatabaseService = createGraphDatabaseService(neo4jStoreDir);
        try (Transaction tx = graphDatabaseService.beginTx()) {
            consumer.accept(graphDatabaseService.execute(query));
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    public static void query(String neo4jStoreDir, String query, Map<String, Object> parameters, Consumer<Result> consumer) {
        GraphDatabaseService graphDatabaseService = createGraphDatabaseService(neo4jStoreDir);
        try (Transaction tx = graphDatabaseService.beginTx()) {
            consumer.accept(graphDatabaseService.execute(query, parameters));
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    public static void query(GraphDatabaseService graphDatabaseService, String query, Consumer<Result> consumer) {
        try (Transaction tx = graphDatabaseService.beginTx()) {
            consumer.accept(graphDatabaseService.execute(query));
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    public static void query(GraphDatabaseService graphDatabaseService, String query, Map<String, Object> parameters, Consumer<Result> consumer) {
        try (Transaction tx = graphDatabaseService.beginTx()) {
            consumer.accept(graphDatabaseService.execute(query, parameters));
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    public static void shutdownGraphDatabaseService(GraphDatabaseService graphDatabaseService) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> graphDatabaseService.shutdown()));
    }

}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.neo4j.graphalgo.GraphAlgoFactory;
import org.neo4j.graphalgo.PathFinder;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.platform.modules.bootstrap.BootstrapApplication;
import org.platform.modules.graph.utils.GraphUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BootstrapApplication.class)
public class Neo4jEmbeddedApplicationTest {

    private Logger LOG = LoggerFactory.getLogger(Neo4jEmbeddedApplicationTest.class);

    @Resource(name = "graphDatabaseService")
    private GraphDatabaseService graphDatabaseService = null;

    @Test
    public void testGraphDatabaseServiceCreateNode1() {
        try (Transaction tx = graphDatabaseService.beginTx()) {
            Node zhangsan001= graphDatabaseService.createNode(CLabel.USER);
            zhangsan001.setProperty("name", "zhangsan001");
            Node zhangsan002= graphDatabaseService.createNode(CLabel.USER);
            zhangsan002.setProperty("name", "zhangsan002");
            zhangsan001.createRelationshipTo(zhangsan002, CRelationshipType.IS_FRIEND_OF);
            LOG.info("create node name is " + zhangsan001.getProperty("name"));
            LOG.info("create node name is " + zhangsan002.getProperty("name"));
            tx.success();
        }
    }

    @Test
    public void testGraphDatabaseServiceCreateNode2() {
        graphDatabaseService = GraphUtils.createGraphDatabaseService("C:/tmp/neo4j/pool1/graph.db");
        try (Transaction tx = graphDatabaseService.beginTx()) {
            Node node001 = graphDatabaseService.createNode(CLabel.USER);
            node001.setProperty("name", "zhang001");
            Node node002 = graphDatabaseService.createNode(CLabel.USER);
            node002.setProperty("name", "zhang002");
            Node node003 = graphDatabaseService.createNode(CLabel.USER);
            node003.setProperty("name", "zhang003");
            Node node004 = graphDatabaseService.createNode(CLabel.USER);
            node004.setProperty("name", "zhang004");
            Node node005 = graphDatabaseService.createNode(CLabel.USER);
            node005.setProperty("name", "zhang005");
            node001.createRelationshipTo(node002, CRelationshipType.IS_FRIEND_OF);
            node001.createRelationshipTo(node004, CRelationshipType.IS_FRIEND_OF);
            node002.createRelationshipTo(node001, CRelationshipType.IS_FRIEND_OF);
            node002.createRelationshipTo(node003, CRelationshipType.IS_FRIEND_OF);
            node003.createRelationshipTo(node001, CRelationshipType.IS_FRIEND_OF);
            node004.createRelationshipTo(node005, CRelationshipType.IS_FRIEND_OF);
            node005.createRelationshipTo(node001, CRelationshipType.IS_FRIEND_OF);
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    @Test
    public void testGraphDatabaseServiceCreateNode3() {
        graphDatabaseService = GraphUtils.createGraphDatabaseService("C:/tmp/neo4j/pool1/graph.db");
        try (Transaction tx = graphDatabaseService.beginTx()) {
            IndexDefinition nameIndexDefinition = graphDatabaseService.schema().getIndexByName("index_1");
            LOG.info("name index constraint {}", nameIndexDefinition.isConstraintIndex());
            Node node = graphDatabaseService.findNode(CLabel.USER, "name", "zhang006");
            if (null == node) {
                node = graphDatabaseService.createNode(CLabel.USER);
                node.setProperty("name", "zhang006");
                LOG.info("node id {}", node.getId());
            } else {
                Long nodeId = node.getId();
                LOG.info("node id {}", nodeId);
            }
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    @Test
    public void testGraphDatabaseServiceIndex1() {
        String cypher1 = "create index on:USER(name)";
        String cypher2 = "drop index on:USER(name)";
        graphDatabaseService = GraphUtils.createGraphDatabaseService("C:/tmp/neo4j/pool1/graph.db");
        try (Transaction tx = graphDatabaseService.beginTx()) {
            graphDatabaseService.execute(cypher2);
            graphDatabaseService.execute(cypher1);
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    @Test
    public void testGraphDatabaseServiceIndex2() {
        String cypher1 = "create constraint on (u:USER) assert u.name is unique";
        String cypher2 = "drop constraint on (u:USER) assert u.name is unique";
        String cypher3 = "drop index on:USER(name)";
        graphDatabaseService = GraphUtils.createGraphDatabaseService("C:/tmp/neo4j/pool1/graph.db");
        try (Transaction tx = graphDatabaseService.beginTx()) {
            //graphDatabaseService.execute(cypher3);
            graphDatabaseService.execute(cypher1);
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    @Test
    public void testGraphDatabaseServiceIndex3() {
        graphDatabaseService = GraphUtils.createGraphDatabaseService("C:/tmp/neo4j/pool1/graph.db");
        try (Transaction tx = graphDatabaseService.beginTx()) {
            Iterator<IndexDefinition> indexDefinitionIterator = graphDatabaseService.schema().getIndexes().iterator();
            while (indexDefinitionIterator.hasNext()) {
                IndexDefinition indexDefinition = indexDefinitionIterator.next();
                LOG.info("index definition labels {}", indexDefinition.getLabels());
                LOG.info("index definition name {}", indexDefinition.getName());
                LOG.info("index definition property keys {}", indexDefinition.getPropertyKeys());
                LOG.info("index definition constraint {}", indexDefinition.isConstraintIndex());
            }
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    @Test
    public void testGraphDatabaseServiceQuery1() {
        String query = "match (n:USER) return n.name as name";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, new HashMap<String, Object>(), result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    LOG.info("{} = {}", column, row.get(column));
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceQuery2() {
        String query = "match (n:USER) return n";
        //String query = "start n = node(*) return n";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, new HashMap<String, Object>(), result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    Object value = row.get(column);
                    if (value instanceof Node) {
                        Node node = (Node) value;
                        LOG.info("node {} = {} = {} = {}", column, node.getId(), node.getLabels(), node.getAllProperties());
                        Iterator<Relationship> iterator = node.getRelationships().iterator();
                        while (iterator.hasNext()) {
                            Relationship relationship = iterator.next();
                            LOG.info("node relation {} = {} = {} = {}", relationship.getId(), relationship.getType(), relationship.getStartNodeId(), relationship.getEndNodeId());
                        }
                    }
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceQuery3() {
        String query = "match(n:USER)-[r]-(m:USER) return n,r,m";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, new HashMap<String, Object>(), result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    Object value = row.get(column);
                    if (value instanceof Node) {
                        Node node = (Node) value;
                        LOG.info("node {} = {} = {} = {}", column, node.getId(), node.getLabels(), node.getAllProperties());
                        Iterator<Relationship> iterator = node.getRelationships().iterator();
                        while (iterator.hasNext()) {
                            Relationship relationship = iterator.next();
                            LOG.info("{} = {} = {} = {}", relationship.getId(), relationship.getType(), relationship.getStartNodeId(), relationship.getEndNodeId());
                        }
                    } else if (value instanceof Relationship) {
                        LOG.info("relation {}", value);
                    }
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceQuery4() {
        String query = "match(n:USER)-[r]-(m:USER) return n,r,m";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, new HashMap<String, Object>(), result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    Object value = row.get(column);
                    if (value instanceof Node) {
                        Node node = (Node) value;
                        LOG.info("node {} = {} = {} = {}", column, node.getId(), node.getLabels(), node.getAllProperties());
                        Iterator<Relationship> iterator = node.getRelationships().iterator();
                        while (iterator.hasNext()) {
                            Relationship relationship = iterator.next();
                            LOG.info("node relation {} = {} = {} = {}", relationship.getId(), relationship.getType(), relationship.getStartNodeId(), relationship.getEndNodeId());
                        }
                    } else if (value instanceof Relationship) {
                        LOG.info("relation {}", value);
                    }
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceQuery5() {
        graphDatabaseService = GraphUtils.createGraphDatabaseService("C:/tmp/neo4j/pool1/graph.db");
        try (Transaction tx = graphDatabaseService.beginTx()) {
            PathFinder<Path> finder = GraphAlgoFactory.allPaths(PathExpanders.allTypesAndDirections(), 10);
            Path path = finder.findSinglePath(graphDatabaseService.createNode(CLabel.USER), graphDatabaseService.createNode(CLabel.USER));
            System.err.println("path length " + path.length());
            Iterator<PropertyContainer> pathIterator = path.iterator();
            while (pathIterator.hasNext()) {
                PropertyContainer propertyContainer = pathIterator.next();
                System.err.println(propertyContainer);
            }
            tx.success();
        }
        GraphUtils.shutdownGraphDatabaseService(graphDatabaseService);
    }

    @Test
    public void testGraphDatabaseServiceQuery6() {
        String query = "match (n:USER) with size((n)-[:IS_FRIEND_OF]->()) as out, size((n)<-[:IS_FRIEND_OF]-()) as in, n where in >= 1 and out >=1 return n,in,out";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, new HashMap<String, Object>(), result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    Object value = row.get(column);
                    if (value instanceof Node) {
                        Node node = (Node) value;
                        LOG.info("node {} = {} = {} = {}", column, node.getId(), node.getLabels(), node.getAllProperties());
                    } else {
                        LOG.info("{} {}", column, value);
                    }
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceQuery7() {
        String query = "match (n:USER{name:{name}}) return n";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name", "zhang001");
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, parameters, result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    Object value = row.get(column);
                    if (value instanceof Node) {
                        Node node = (Node) value;
                        LOG.info("node {} = {} = {} = {}", column, node.getId(), node.getLabels(), node.getAllProperties());
                    } else {
                        LOG.info("{} {}", column, value);
                    }
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceQuery8() {
        String query = "match (n:USER{name:{name1}})-[r:IS_FRIEND_OF*2..]-(m:USER{name:{name2}}) return n,r,m";
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("name1", "zhang001");
        parameters.put("name2", "zhang005");
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, parameters, result -> {
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                for (int i = 0, len = columns.size(); i < len; i++) {
                    String column = columns.get(i);
                    Object value = row.get(column);
                    if (value instanceof Node) {
                        Node node = (Node) value;
                        LOG.info("node {} = {} = {} = {}", column, node.getId(), node.getLabels(), node.getAllProperties());
                    } else {
                        LOG.info("{} {}", column, value);
                    }
                }
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceLoadCsv1() {
        String query = "LOAD CSV FROM 'file:///F:/tmp1.csv' AS line CREATE (:USER{ name:line[1], year:toInteger(line[2])})";
        Map<String, Object> parameters = new HashMap<String, Object>();
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, result -> {
            LOG.info(result.resultAsString());
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                LOG.info("row {}", row);
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceLoadCsv2() {
        String query = "LOAD CSV WITH HEADERS FROM 'file:///F:/tmp2.csv' AS line MERGE (:USER{ name:line.name, year:toInteger(line.age)})";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, result -> {
            LOG.info(result.resultAsString());
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                LOG.info("row {}", row);
            }
        });
    }

    @Test
    public void testGraphDatabaseServiceMerge1() {
        String query = "MATCH (n:USER) WITH TOLOWER(n.name) as name, COLLECT(n) As nodes " +
            "CALL apoc.refactor.mergeNodes(nodes) YIELD node RETURN *";
        GraphUtils.query("C:/tmp/neo4j/pool1/graph.db", query, result -> {
            LOG.info(result.resultAsString());
            List<String> columns = result.columns();
            while (result.hasNext()) {
                Map<String, Object> row = result.next();
                LOG.info("row {}", row);
            }
        });
    }

    public enum CLabel implements Label {
        USER;
    }

    public enum CRelationshipType implements RelationshipType {
        IS_FRIEND_OF;
    }

}

 


版权声明:本文为wulinshishen原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。