From SQL to Cypher

package cn.dh.neo;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.cypher.javacompat.ExecutionResult;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.index.Index;
import org.neo4j.kernel.impl.util.FileUtils;

/**
 *
 * <p>User: 裴东辉
 * <p>Date: 2014-8-6  上午10:43:10
 * <p>Version: 1.0
 */
public class Neosql {

    public static enum RelationshipTypes implements RelationshipType {
        FLLOW, //用户链          歌手出版专辑
        EMAIL//用户-邮箱         专辑包含很多歌曲
      } 

    public final String USERPK="name";
    public final String EMAILPK="email";

    /**
     * 数据初始化
     * @author 裴东辉
     * @since 2014-8-6  上午10:46:18
     */
    public void initdata(){
        try {FileUtils.deleteRecursively(new File("db/user.db"));} catch (IOException e) {e.printStackTrace();} //删除数据库
        GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( "db/user.db" );
        try(Transaction tx = graphDb.beginTx()){
            //节点索引
            Index<Node> usersIndex = graphDb.index().forNodes("usersIndex");
            //-----------------第1个用户,第1个用户的2个邮箱
            Node node1 = graphDb.createNode();
            node1.setProperty(USERPK, "admin");
            usersIndex.add(node1, USERPK, node1.getProperty(USERPK));

            Node node1_1=graphDb.createNode();
            node1_1.setProperty(EMAILPK, "[email protected]");
            node1_1.setProperty("comment", "work");
            usersIndex.add(node1_1, EMAILPK, node1_1.getProperty(EMAILPK));

            Node node1_2=graphDb.createNode();
            node1_2.setProperty(EMAILPK, "[email protected]");
            node1_2.setProperty("comment", "home");
            usersIndex.add(node1_2, EMAILPK, node1_2.getProperty(EMAILPK));

            node1.createRelationshipTo(node1_1, RelationshipTypes.EMAIL);
            node1.createRelationshipTo(node1_2, RelationshipTypes.EMAIL);

            //-----------------第2个用户,第2个用户的2个邮箱
            Node node2 = graphDb.createNode();
            node2.setProperty(USERPK, "user");
            usersIndex.add(node2, USERPK, node2.getProperty(USERPK));

            Node node2_1=graphDb.createNode();
            node2_1.setProperty(EMAILPK, "[email protected]");
            node2_1.setProperty("comment", "work");
            usersIndex.add(node2_1, EMAILPK, node2_1.getProperty(EMAILPK));

            Node node2_2=graphDb.createNode();
            node2_2.setProperty(EMAILPK, "[email protected]");
            node2_2.setProperty("comment", "home");
            usersIndex.add(node2_2, EMAILPK, node2_2.getProperty(EMAILPK));

            node2.createRelationshipTo(node2_1, RelationshipTypes.EMAIL);
            node2.createRelationshipTo(node2_2, RelationshipTypes.EMAIL);

            //----两个用户之间的关联关系
            node1.createRelationshipTo(node2, RelationshipTypes.FLLOW);

            tx.success();
        }finally{
            graphDb.shutdown();
        }
    }

    /**
     * select * from t_user  where name = ‘admin‘
     * start user=node:usersIndex(name = {name} ) return user ,其中的{name}通过一个Map的参数传递过去params
     * 1、SQL starts with the result you want — we SELECT what we want and then declare how to source it. In
            Cypher, the START clause is quite a different concept which specifies starting points in the graph from
            which the query will execute.
        2、From a SQL point of view, the identifiers in START are like table names that point to a set of nodes or
            relationships. The set can be listed literally, come via parameters, or as I show in the following example,
            be defined by an index look-up.
        3、So in fact rather than being SELECT-like,
            the START clause is somewhere between the FROM and the WHERE clause in SQL.
     * @author 裴东辉
     * @since 2014-8-6  上午11:08:44
     */
    public void findUserByName(String name){
        GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( "db/user.db" );
        try(Transaction tx = graphDb.beginTx()){
            ExecutionEngine engine = new ExecutionEngine(graphDb);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("name",name);
            ExecutionResult result = engine.execute( "start user=node:usersIndex(name = {name} ) return user",params);
            Iterator<Node> nodeIta=result.columnAs("user");
            Node node=null;
            while(nodeIta.hasNext()){
                node=nodeIta.next();
                infoln(node+"-"+node.getProperty(USERPK));
            }
            tx.success();
        }finally{
            graphDb.shutdown();
        }
    }

    /**
     * 1、select t_email.*
            from t_user join t_email on t_user.id = t_email.user_id
            where t_user.name = ‘admin‘
        2、start user=node:usersIndex(name = {name})
             match user-[:EMAIL]->email
             return email
        3、Unlike SQL which operates on sets, Cypher predominantly works on sub-graphs.
            The relational equivalent is the current set of tuples being evaluated during a SELECT query.
        4、The shape of the sub-graph is specified in the MATCH clause.
            The MATCH clause is analogous to the JOIN in SQL.
            A normal a→b relationship is an inner join between nodes a and b
            both sides have to have at least one match, or nothing is returned.
        5、We’ll start with a simple example,
            where we find all email addresses that are connected to the person “admin”.
            This is an ordinary one-to-many relationship.
        6、There is no join table here, but if one is necessary the next example will show how to do that,
            writing the pattern relationship like so: -[r:belongs_to]-> will introduce (the equivalent of) join table available asthe variable r.
            In reality this is a named relationship in Cypher, so we’re saying “join Person to Group viabelongs_to.”
            To illustrate this, consider this image, comparing the SQL model and Neo4j/Cypher.
     * @author 裴东辉
     * @since 2014-8-6  上午11:40:10
     */
    public void findEmailByUserName(String name){
        GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( "db/user.db" );
        try(Transaction tx = graphDb.beginTx()){
            ExecutionEngine engine = new ExecutionEngine(graphDb);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("name", name);

            ExecutionResult result = engine.execute( "start user=node:usersIndex(name = {name})  match user-[:EMAIL]->email  return email",params);
            Iterator<Node> nodeIta=result.columnAs("email");
            Node node=null;
            while(nodeIta.hasNext()){
                node=nodeIta.next();
                infoln(node+"-"+node.getProperty(EMAILPK));
            }
            tx.success();
        }finally{
            graphDb.shutdown();
        }
    }

    public void info(Object j){System.out.print(j.toString());}
    public void infoln(Object j){System.out.println(j.toString());}
    /**
     * @author 裴东辉
     * @since 2014-8-6  上午10:42:54
     * @param args
     */
    public static void main(String[] args) {
        new Neosql().initdata();
        new Neosql().findUserByName("user");
        new Neosql().findEmailByUserName("admin");
    }

}

From SQL to Cypher

时间: 2024-10-15 21:12:22

From SQL to Cypher的相关文章

图数据库:AgensGraph

文章目录 AgensGraph简介 官网及下载 安装AgensGraph 上传并解压 添加agens用户 配置.bashrc 初始化并启动 初始化数据库 启动数据库 执行交互式终端 图数据库基础概念 配置服务器参数 AgensGraph数据模型 AgensGraph中的数据对象 数据定义语言 创建label AgensGraph查询 介绍 创建一个示例图 创建标签 Creating the Vertices and Edges 查询图表 Querying the Graph 可变长度边缘 Var

初探Neo4J中的Cypher

由于RDF数据库需要,需要调研图形数据库,选择了Neo4J进行尝试,发现它包含了一个名为"Cypher"的操作语言,使用了一下感觉非常不错,所有有写点东西的必要. 从官网上盗个图: 其实,这个图也就标识了cypher语言的基本功能,节点a到节点b,关系是LIKES,其操作的方法与sql的select一样选择符合某种条件的实体,由此强烈建议大家使用网页版进行熟悉操作,比较直观,可以直接得到图形. 闲话少说,我们姑且成上面的为万能公式,该万能公式大体上分为两个部分()与[],其中()表示某

Cypher 描述性的图像查询语言

1 /** 2 * 使用cypherParser语言 3 * @author 裴东辉 4 * @since 2014-8-4 下午3:22:25 5 */ 6 public void userCypherParser(){ 7 //执行一个Cypher Query的查询 8 GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( "db/music.db" ); 9 try(Trans

Cypher语言学习笔记

一.简介 Cypher语言是在学习Neo4j时用到数据库操作语言(DML),涵盖对图数据的增删改查,跟SQL有较大不同,本文仅记录一些要点备查 二.详述 1.基本概念 Neo4j中不存在表的概念,只有两类:节点(Node)和关联(Relation),可以简单理解为图里面的点和边,在数据查询中,节点一般用小括号(),关联用中括号[].当然也隐含路径的概念,是用节点和关联表示的,如:(a)-[r]->(b),表示一条从节点a经关联r到节点b的路径 2.创建语句 1)创建节点 create (a) 创

Cypher语法

cypher是neo4j官网提供的声明式查询语言,非常强大,用它可以完成任意的图谱里面的查询过滤,我们知识图谱的一期项目 基本开发完毕,后面会陆续总结学习一下neo4j相关的知识.今天接着上篇文章来看下neo4j的cpyher查询的一些基本概念和语法. 一,Node语法 在cypher里面通过用一对小括号()表示一个节点,它在cypher里面查询形式如下: 1,() 代表匹配任意一个节点 2, (node1) 代表匹配任意一个节点,并给它起了一个别名 3, (:Lable) 代表查询一个类型的数

Neo4j 第三篇:Cypher查询入门

Neo4j使用Cypher查询图形数据,Cypher是描述性的图形查询语言,语法简单,功能强大,由于Neo4j在图形数据库家族中处于绝对领先的地位,拥有众多的用户基数,使得Cypher成为图形查询语言的事实上的标准.本文作为入门级的教程,我不会试图分析Cypher语言的全部内容,本文的目标是循序渐进地使用Cypher语言执行简单的CRUD操作,为了便于演示,本文在Neo4j Browser中执行Cypher示例代码.以下图形包含三个节点和两个关系,本文会一步一步讲解如何利用Cypher语言创建以

SQL查询字段添加括号报错:Operand should contain 1 column(s)

SQL语句:查询连个字段的信息 SELECT (menu_id,menu_captions) FROM bsdb.menulist a WHERE a.menu_id like ('2_'); 然后,因为这是在存储过程中的一个语句所以,在执行存储过程的时候编译不会报错,但是执行的时候却汇报错:Operand should contain 1 column(s):原因不好解释: 下面是官方发解释(MYSQL):https://dev.mysql.com/doc/refman/5.0/en/row-

SQL Server 2008的MSSQLSERVER 请求失败或服务未及时响应

我的是SQL server 2008R2, 以前可以正常的启动SQL server(SQLEXPRESS).SQL server(MSSQLSERVER),有几天没有打开了,就在昨天 开机之后就无法启动MSSQLSERVER了,提示的信息如下图: 快速解决办法如下: 第一步:打开事件查看器,查看windows日志,点击应用程序,查看windows错误日志 http://product.pconline.com.cn/itbk/software/win8/1211/3060037.html 第二步

【Kettle】4、SQL SERVER到SQL SERVER数据转换抽取实例

1.系统版本信息 System:Windows旗舰版 Service Pack1 Kettle版本:6.1.0.1-196 JDK版本:1.8.0_72 2.连接数据库 本次实例连接数据库时使用全局变量. 2.1 创建新转换:spoon启动后,点击Ctrl+N创建新转换 2.2 在新转换界面中,右键点击DB连接,系统会弹出[数据库连接]界面. windows系统环境下,可用${}获取变量的内容. 说明: 连接名称:配置数据源使用名称.(必填) 主机名称:数据库主机IP地址,此处演示使用本地IP(