图数据库 | Neo4j简单的JavaAPI案例

 入门Neo4j,在官网案例的基础上添加了两个方法,下文程序的功能分别是:获取图数据库连接驱动、往标签添加节点、打印节点信息、获取所有节点数据、获取节点和关系、关闭连接。
 执行以下程序需要的lib,分别是Neo4j安装包下的lib,以及neo4j-java-driver-x.x.x.jar

import org.neo4j.driver.v1.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;

import java.util.Iterator;
import java.util.List;

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

public class SmallExample {

    // Driver objects are thread-safe and are typically made available application-wide.
    Driver driver;

    public SmallExample(String uri, String user, String password)
    {
        // 图数据库驱动
        driver = GraphDatabase.driver(uri, AuthTokens.basic(user, password));
    }

    /**
     * 添加节点
     * @param name
     */
    private void addPerson(String name)
    {
        // Sessions are lightweight and disposable connection wrappers.
        try (Session session = driver.session())
        {
            // Wrapping Cypher in an explicit transaction provides atomicity
            // and makes handling errors much easier.
            // 写库操作需要事务
            try (Transaction tx = session.beginTransaction())
            {
                // x 表示一个占位符
                tx.run("Merge (a:People {name: {x}})", parameters("x", name));
                tx.success();  // Mark this write as successful.
            }
        }
    }

    /**
     * 打印节点信息
     * @param initial
     */
    private void printPeople(String initial)
    {
        Session session = driver.session();

        // Auto-commit transactions are a quick and easy way to wrap a read.
        // 查询name 属性以initial 参数开头的节点数据
        StatementResult result = session.run(
                "MATCH (a:People) WHERE a.name STARTS WITH {x} RETURN a.name as PeopleName  ",
                parameters("x", initial));
        // Each Cypher execution returns a stream of records.
        while (result.hasNext())
        {
            // Record 是一行记录,内容是什么取决于你return 的东西
            Record record = result.next();
            System.out.println("record = " + record);
            // Values can be extracted from a record by index or name.
            // get 的是一个别名,上面的cyther 没有as 别名话,查询不出来
            System.out.println(record.get("PeopleName").asString());
        }

    }

    /**
     * 获取label 中的所有节点数据
     */
    private void getPeoples()
    {
        Session session = driver.session();

        // Auto-commit transactions are a quick and easy way to wrap a read.
        StatementResult result = session.run("MATCH (b:People) RETURN b");
        // Each Cypher execution returns a stream of records.
        while (result.hasNext())
        {
            Record record = result.next();
            System.out.println("record = " + record);   // Record<{b: node<250>}>,key 是b,value 是node<250>,250 代表内置id

            List list = record.values();
            for(Value v : list)
            {
                Node n = v.asNode();    // 已知value 是一个node(如,node<250>),故将其转为Node
                // n.labels() 是一个Iterable
                // n.labels().iterator().next() 获取的是label,也就是表名的意思
                System.out.println(n.labels().iterator().next() + "--" + n.id());

                // 获取节点的属性
                for(String k : n.keys())
                {
                    System.out.println(k + "---" + n.get(k));   // 获取属性名和属性值
                }
                System.out.println("==========================");

            }
        }

    }

    /**
     * 获取节点和关系
     * 往库里添加关系:match (a:People),(b:People) where a.name='Ada' and b.name='Bob' merge (a)-[:Friend]-(b) return a,b
     */
    private void getPeoplesAndRelation()
    {
        Session session = driver.session();

        // Auto-commit transactions are a quick and easy way to wrap a read.
        StatementResult result = session.run(
                "MATCH p=(b:People)-[]-(c) RETURN p");  // return p,p 代表关系,返回的结果是一个path
//                "MATCH (b:People)-[]-(c) RETURN b,c");   // 如果用这句查询,返回的则是node,可以使用上面getPeople 进行遍历打印

        while (result.hasNext())
        {
            // Record 是一行记录,内容是什么取决于你return的东西;同样,record.values() 也取决于查询的是什么类型
            Record record = result.next();
            System.out.println("record: " + record);

            List list = record.values();
            for(Value v : list)
            {
                Path p = v.asPath();    // 把获取的每个value 转为path
                Node start = p.start();

                for(String k : start.keys())
                {
                    System.out.println("Start Node's property keys: " + k + "---" + start.get(k) );
                }

                Iterator i = p.relationships().iterator();
                while(i.hasNext())
                {
                    Relationship r = (Relationship)i.next() ;
                    System.out.println("Relation Type: " + r.type());
                    System.out.println("Print id; start node to end node: " + r.startNodeId() + "->"+r.endNodeId());
                    System.out.println("Relation Id: " + r.id());
                }

                Node end = p.end();
                for(String k : end.keys())
                {
                    System.out.println("End Node's property keys: " + k + "---" + end.get(k) );
                }
                System.out.println("==========================");

            }
        }

    }

    public void close()
    {
        // Closing a driver immediately shuts down all open connections.
        driver.close();
    }

    public static void main(String... args)
    {
        SmallExample example = new SmallExample("bolt://oda.com:7687", "neo4j", "123456");
//        example.addPerson("Ada");
//        example.addPerson("Alice");
//        example.addPerson("Bob");
//        example.printPeople("A");
//        example.getPeoples();
        example.getPeoplesAndRelation();
        example.close();
    }

}

你可能感兴趣的:(图数据库,Neo4j)