neo4j使用笔记

 

#coding:utf-8
__author__ = 'similarface'

# 安装驱动:pip install neo4j-driver
from neo4j.v1 import GraphDatabase

#建立连接
driver=GraphDatabase.driver("bolt://localhost:7687", auth=("***", "***"))

#添加数据
def add_friends(tx, name, friend_name):
    tx.run("MERGE (a:Person {name: $name}) "
           "MERGE (a)-[:KNOWS]->(friend:Person {name: $friend_name})",
           name=name, friend_name=friend_name)
#查询数据
def print_friends(tx, name):
    for record in tx.run("MATCH (a:Person)-[:KNOWS]->(friend) WHERE a.name = $name "
                         "RETURN friend.name ORDER BY friend.name", name=name):
        print(record["friend.name"])

with driver.session() as session:
    session.write_transaction(add_friends, "刘备", "关羽")
    session.write_transaction(add_friends, "刘备", "张飞")
    session.write_transaction(add_friends, "刘备", "孔明")
    session.read_transaction(print_friends, "刘备")

 

 

#导入数据
LOAD CSV WITH HEADERS FROM 'file:/all_samples.csv' AS line
CREATE (:User {barcode:line.barcode, name: line.name, sex: toInteger(line.sex),birthday:toInteger(replace(line.birthday, "-", "")),address:line.address})

#更新数据

LOAD CSV WITH HEADERS FROM 'file:/test.csv' AS line
merge(p:User {barcode:line.barcode})
on match set p.birthday=toInteger(line.birthday) return p.birthday

 
#创建索引
CREATE INDEX ON :User(name)

LOAD CSV WITH HEADERS FROM 'file:/all_shipv.csv' AS line
match(p:User {barcode:line.barcode1})
match(q:User {barcode:line.barcode2})
create (p)-[:s {v:line.shipv,c:line.centimorgan}]->(q)

 

#查询barcode为********* 并且它存在5个朋友

MATCH (n {barcode: '*********'})-[:s]-(friend)
WITH n, count(friend) AS friendsCount
WHERE friendsCount > 5
RETURN n, friendsCount

 

#查找barcode为********* 的朋友的朋友

MATCH (user:User { barcode: '*********' })-[r1:s]-()-[r2:s]-(friend_of_a_friend)
RETURN friend_of_a_friend.name AS fofName

#查找barcode为********* 的朋友的朋友 会返回更多的数据包括自己

MATCH (user:User { barcode: '*********' })-[r1:s]-(friend)
MATCH (friend)-[r2:s]-(friend_of_a_friend)
RETURN friend_of_a_friend.name AS fofName

同上:

MATCH (user:User { barcode: '*********' })-[r1:s]-(friend),(friend)-[r2:s]-(friend_of_a_friend)
RETURN friend_of_a_friend.name AS fofName

 

#如何反应flag字段

MATCH (n:User)
RETURN
CASE n.sex
WHEN 1
THEN '男'
WHEN 0
THEN '女'
ELSE '未知' END AS result ,n.name

#另一种格式的case

MATCH (n)
RETURN
CASE
WHEN n.eyes = 'blue'
THEN 1
WHEN n.age < 40
THEN 2
ELSE 3 END AS result

 

#UNWIND子句是把列表数据展开成一行一行的数据

 

 

 

posted @ 2018-03-12 20:31  similarface  阅读(198)  评论(0编辑  收藏  举报