JAVA操作neo4j

发布于 2019-06-02  42 次阅读


主要有两种方式

Embedded

采用此种方式,需要关闭运行着的neo4j服务

maven配置

    <dependency>
      <groupId>org.neo4j</groupId>
      <artifactId>neo4j</artifactId>
      <version>3.5.6</version>
    </dependency>

样例

工具类

package preprocess.utils;

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

import java.io.File;

public class NeoUtils {


    private static GraphDatabaseService graphDb;

    public enum NodeTypes implements Label {
        AUTHOR,ARTICLE,COUPLING_CENTER,CO_CITATION_CENTER,COUPLING_FIELD,CO_CITATION_FIELD,COUPLING,CO_CITATION,COOPERATE_CENTER
    }

    public enum RelTypes implements RelationshipType {
        COOPERATE,COOPERATE_FIELD
    }


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

    public static GraphDatabaseService db() {
        if (graphDb == null) {
            graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(new File("db/databases/graph.db"));
            setHook(graphDb);
        }
        return graphDb;
    }
    
}

原生java api方式

    public void processNodes() {
        List<Author> authors = DbUtils.getDao().query(Author.class, null);
        try (Transaction tx = NeoUtils.db().beginTx()) {
            for (Author author : authors) {
                Node s = NeoUtils.db().createNode(NeoUtils.NodeTypes.AUTHOR);
                s.setProperty("name", author.getAuthorFullName());
                s.setProperty("shortName", author.getAuthorShortName());
                s.setProperty("nums", author.getArticleNumbers());
                s.setProperty("year", author.getFirstYear());
                Node to=NeoUtils.db().createNode(NeoUtils.NodeTypes.COOPERATE_CENTER);
                to.setProperty("name", author.getAuthorFullName());
                to.setProperty("shortName", author.getAuthorShortName());
                to.setProperty("nums", author.getArticleNumbers());
                to.setProperty("year", author.getFirstYear());
                s.createRelationshipTo(to,NeoUtils.RelTypes.COOPERATE_FIELD);
            }
            tx.success();
        }
    }

通过CQL语句

    /**
     * 作者合作网络
     */
    public void processRelationships2() {
        List<Article> articles = DbUtils.getDao().query(Article.class, null);
        try (Transaction tx = NeoUtils.db().beginTx()) {
            for (Article article : articles) {
                List<String> authors = (List<String>) Json.fromJson(article.getAuthorFullname());
                if (authors == null || authors.size() <= 1) {
                    continue;
                }
                for (int i = 0; i < authors.size(); i++) {
                    for (int j = 0; j < authors.size(); j++) {
                        if(i==j){
                            continue;
                        }
                        Map<String, Object> params = new HashMap<>();
                        params.put("a", authors.get(i));
                        params.put("b", authors.get(j));
                        params.put("c", article.getTitle());
                        NeoUtils.db().execute("MATCH (a:AUTHOR{name:$a}),(b:AUTHOR{name:$b}) MERGE (a)-[r:COOPERATE{article:$c}]->(b)", params);
                        NeoUtils.db().execute("MATCH (:AUTHOR{name:$a})-[:COOPERATE_FIELD]->(a),(b:AUTHOR{name:$b})" +
                                "MERGE (a)-[r:COOPERATE]->(b) " +
                                "on match set r.num=r.num+1 " +
                                "on create set r.num=1", params);
                    }
                }
            }
            tx.success();
        }
    }

通过java driver

该方式需要启动neo4j服务器

maven配置

    <dependency>
      <groupId>org.neo4j.driver</groupId>
      <artifactId>neo4j-java-driver</artifactId>
      <version>1.7.2</version>
    </dependency>

样例

    @At("/cp")
    public Object couping(@Param("wos")String wos){
        List<Article> coupings=new ArrayList<>();
        Driver driver = GraphDatabase.driver("bolt://localhost:7687",
                AuthTokens.basic("neo4j","密码"));
        try(Session session = driver.session()){
            StatementResult result = session.run("match (:ARTICLE{wos:{WOS}})-[:COUPING_FIELD]->(a)-[r]->(b) return b.wos as wos,b.title as title",
                    parameters("WOS",wos));
            while (result.hasNext()){
                Record record=result.next();
                Article article=new Article();
                article.setWos(record.get("wos").asString());
                article.setTitle(record.get("title").asString());
                coupings.add(article);
            }
        }
        driver.close();
        return new NutMap().setv("code",0).setv("coupings",coupings);
    }