Neo4j Cypher 复杂查询详解在之Unwind

1 拆解collect

UNWIND[1,2,3] AS x
RETURN x

代码块解释:

Result
x
1
2
3

2. collect去重

类似hive里面的distinct关键字

WITH [1,1,2,2] AS coll UNWIND coll AS x
WITH DISTINCT x
RETURN collect(x) AS SET

代码块解释:返回的是一个set:[1,2]

3. 利用collection的参数创建nodes

collection的参数示例如下,其实就是个json:

{
  "events" : [ {
    "year" : 2014,
    "id" : 1
  }, {
    "year" : 2014,
    "id" : 2
  } ]
}

查询语句:

UNWIND { events } AS event
MERGE (y:Year { year:event.year })
MERGE (y)<-[:IN]-(e:Event { id:event.id })
RETURN e.id AS x
ORDER BY x

代码块解释:在Neo4J Cypher里面需要用到参数化输入(参见neo4j Parameters),上面语句在cypher里面应该输入如下:

:POST /db/data/transaction/commit
{
  "statements": [
    {
      "statement": "UNWIND { events } AS event MERGE (y:Year { year:event.year }) MERGE (y)<-[:IN]-(e:Event { id:event.id }) RETURN e.id AS x ORDER BY x",
      "parameters":{
                   "events" : [ {
                        "year" : 2014,
                        "id" : 1
                      }, {
                        "year" : 2014,
                        "id" : 2
                      } ]
                    }
            }
      ]
}

最后结果返回如下:

{
  "results": [
    {
      "columns": [
        "x"
      ],
      "data": [
        {
          "row": [
            1
          ]
        },
        {
          "row": [
            2
          ]
        }
      ]
    }
  ],
  "errors": []
}

你可能感兴趣的:(Neo4J专题)