Neo4j常用cypher语句

来自ling
跳转至: 导航搜索

http://neo4j.ling2.cn:7474/browser/

neo4j代码清理

常用

create (n:FuVersion{id:'FuVersionWBTB',name:"温病条辩"}) return id(n)
MATCH (n) where n.images is not null  set n.images=replace(n.images, 'https://ling-cloud.oss-cn-beijing.aliyuncs.com', ) 
MATCH (n) where n.urls is not null  set n.urls=replace(n.urls, 'https://ling-cloud.oss-cn-beijing.aliyuncs.com', ) 
MATCH (n) where n.images is not null  set n.images=replace(n.images, '/neo4j/','https://ling2-cloud.oss-cn-zhangjiakou.aliyuncs.com/neo4j/' ) 
MATCH (n) where n.urls is not null  set n.urls=replace(n.urls, '/neo4j/','https://ling2-cloud.oss-cn-zhangjiakou.aliyuncs.com/neo4j/' ) 

改变熟悉

match(n:DBItem) set n.showLabel=n.label remove n.label

修改lable

MATCH (n:OLD_LABEL) REMOVE n:OLD_LABEL SET n:NEW_LABEL

修改属性

match(n)
set n.property2=n.property1
remove n.property1

name 重复

match (m:DBForm)-[r*]->(n) where m.name='ZhongYao' with m.name as name , collect(n) AS nodes RETURN [ n in nodes | n.name] AS names

MATCH (p:ZhongYaoPair)
WITH p.name as name, collect(p) AS nodes 
WHERE size(nodes) >  1
RETURN [ n in nodes | n.name] AS names, size(nodes)
ORDER BY size(nodes) DESC
MATCH p1= (v:Version)-[relaion1*1..3]->(r:Risk)<-[relaion2]-(rule:Rule)-[relation3*]->() where v.id='922f4c02-5e52-48ea-b4aa-32007f20ffaa' and r.code='R01-0002'  return p1
MATCH p1= (v:Version)-[relaion1*1..3]->(r:Risk)-[relaion2*]->() where v.id='922f4c02-5e52-48ea-b4aa-32007f20ffaa' and r.code='R01-0002'  return p1
MATCH   (version:Version)-[r*]->(c)-[r1*]->(risk:Risk)<-[r2*]-(rule:Rule)-[r3*]->(n) where version.id='922f4c02-5e52-48ea-b4aa-32007f20ffaa' and risk.code='R01-0002'  return version,r,c,r1,risk,r2,rule,r3,n
MATCH (version:Version)-[r1*]->(c)-[r2*]->(risk:Risk)-[r3*]->(n) where version.id={versionId} and risk.code contains({riskNo})  return version,r1,c,r2,risk,r3,n
match (n:test)  where id(n)=19513 set n.name="首页2"
match(n)-[r]-(m) where r.sourceId=r.targetId   delete r

修改实体label:

match(n:oldlabel) set n:newlabel remove n:oldlabel

修改id

MATCH (n:`工作`) where 1=1 set n.id = id(n)+ return n
MATCH (n:`工作`) where 1=1 set n.id = id(n)+ return n
match (n:`工作`) remove andres.age return adres

修改关系属性

MATCH p=()-[r:RE]->() where size(r.des)>4 RETURN p LIMIT 25
MATCH p=()-[r:RE]->() where size(r.content)<=4 remove r.content  RETURN r
MATCH p=()-[r:尾部]->() SET r={title:“尾部”} RETURN p
MATCH p=(m)-[r]->(n) where r.id is null set r.id=id(r)+
MATCH p=(m)-[r]->(n) where r.sourceId is null and r.targetId is null return r
MATCH p=(m)-[r]->(n)  set r.sourceId=m.id,r.targetId=n.id return r

MATCH p=(m)-[r]->(n) where r.sourceId is null and r.targetId is null set r.sourceId=id(m)+,r.targetId=id(n)+ return r

修改关系名

MATCH (n:User {name:"foo"})-[r:REL]->(m:User {name:"bar"})
CREATE (n)-[r2:NEWREL]->(m)
// copy properties, if necessary
SET r2 = r
WITH r
DELETE r

修改关系label(将关系subord 修改为 subord_new):

MATCH p=(n:User)-[r:subord]->(e:department) create(n)-[r2:subord_new]->(e)  set r2 = r with r delete r

delete delete 语句用于删除图元素(节点、关系、或路径)。 不能只删除节点而不删除与之相连的关系,要么使用 detach delete。

删除单个节点

match (n : User) delete n 

删除所有的节点和关系 这个查询适用于删除少量的数据,不适用于删除巨量的数据

match (n) detach delete n

删除一个节点及其所有的关系

match (n : {name : "Andres"}) detach delete n

remove remove 语句用于删除图元素的属性和标签。

删除一个属性 neo4j不允许属性存储空值null。如果属性的值不存在,那么节点或者关系中的属性将被删除。这也可以通过remove来删除。

match (andres {name : "Andres"}) remove andres.age return adres

删除节点的一个标签

match (n {name "peter"}) remove n:Chinese return n

删除节点的多个标签

match (n {name "peter"}) remove n:Chinese:Man return n

链接

https://www.cnblogs.com/ljhdo/archive/2017/05/24/5516793.html

https://blog.csdn.net/sinat_26917383/article/details/79883503?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-15.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-15.nonecase

apoc.cypher

https://blog.csdn.net/GraphWay/article/details/106762634 https://blog.csdn.net/GraphWay/article/details/93711152

//传入整个拼接好的cql进来当做参数 @Query("call apoc.cypher.run({cql}, null) yield value return value as value") List<BaseNode> getNodeRelation(@Param("cql") String cql);

neo4j-data

@Component
public interface CustomerRepository extends Neo4jRepository{
	//查询id为65的person节点,和与他有五层关系的person和book节点,且有编写,著作关系
	//	@Query("match (p:Person) where id(p) = 65 with p CALL apoc.path.expand(p,'编写|著作','+Person|+Book',0,5) YIELD path as paths return paths")
	//查询节点和关系
	@Query("match (p:Person) where id(p) = 65 with p CALL apoc.path.expand(p,{str},'+Person|+Book',0,{num}) YIELD path as paths return paths")
    List<BaseNode> getUserNodeList(@Param("num") int num,//关系层数
    								@Param("id") int id,//id
    								@Param("str") String str);//关系类型  编写|著作
	
	//传入整个拼接好的cql进来当做参数
	@Query("call apoc.cypher.run({cql}, null) yield value return value as value")
	List<BaseNode> getNodeRelation(@Param("cql") String cql);
	

public interface PersonRepository extends Neo4jRepository<Person, Long> , CustomizedRepository<Person> {

	Person findByfirstName(@Param("firstName") String firstName);

	Collection<Person> findByfirstNameLike(@Param("firstName") String firstName);

	// returns a Page of Actors that have a ACTS_IN relationship to the movie node with the title equal to movieTitle parameter.
	@Query(value = "MATCH (movie:Movie {title:{0}})<-[:ACTED_IN]-(p:Person) RETURN p",
			countQuery= "MATCH (movie:Movie {title:{0}})<-[:ACTED_IN]-(p:Person) RETURN count(p)")
	Page<Person> getActorsThatActInAmoviesFromTitle(String movieTitle, Pageable pageable );
}

public interface MovieRepository extends Neo4jRepository<Movie, Long> {

    // returns the node with id equal to idOfMovie parameter
    @Query("MATCH (n) WHERE id(n)={0} RETURN n")
    Movie getMovieFromId(Integer idOfMovie);

    // returns the nodes which have a title according to the movieTitle parameter
    @Query("MATCH (movie:Movie {title={0}}) RETURN movie")
    Movie getMovieFromTitle(String movieTitle);

    // same with optional result
    @Query("MATCH (movie:Movie {title={0}}) RETURN movie")
    Optional<Movie> getMovieFromTitle(String movieTitle);

    // returns a Page of Actors that have a ACTS_IN relationship to the movie node with the title equal to movieTitle parameter.
    @Query(value = "MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN actor", countQuery= "MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN count(actor)")
    Page<Actor> getActorsThatActInMovieFromTitle(String movieTitle, PageRequest page);

    // returns a Page of Actors that have a ACTS_IN relationship to the movie node with the title equal to movieTitle parameter with an accurate total count
    @Query(value = "MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN actor", countQuery = "MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN count(*)")
    Page<Actor> getActorsThatActInMovieFromTitle(String movieTitle, Pageable page);

    // returns a Slice of Actors that have a ACTS_IN relationship to the movie node with the title equal to movieTitle parameter.
    @Query("MATCH (movie:Movie {title={0}})<-[:ACTS_IN]-(actor) RETURN actor")
    Slice<Actor> getActorsThatActInMovieFromTitle(String movieTitle, Pageable page);

    // returns users who rated a movie (movie parameter) higher than rating (rating parameter)
    @Query("MATCH (movie:Movie)<-[r:RATED]-(user) " +
           "WHERE id(movie)={movieId} AND r.stars > {rating} " +
           "RETURN user")
    Iterable<User> getUsersWhoRatedMovieFromTitle(@Param("movieId") Movie movie, @Param("rating") Integer rating);

    // returns users who rated a movie based on movie title (movieTitle parameter) higher than rating (rating parameter)
    @Query("MATCH (movie:Movie {title:{0}})<-[r:RATED]-(user) " +
           "WHERE r.stars > {1} " +
           "RETURN user")
    Iterable<User> getUsersWhoRatedMovieFromTitle(String movieTitle, Integer rating);

    @Query(value = "MATCH (movie:Movie) RETURN movie;")
    Stream<Movie> getAllMovies();
}



public interface PersonRepository extends Neo4jRepository<Person, Long> {

    // MATCH (person:Person {name={0}}) RETURN person
    Person findByName(String name);

    // MATCH (person:Person)
    // WHERE person.age = {0} AND person.married = {1}
    // RETURN person
    Iterable<Person> findByAgeAndMarried(int age, boolean married);

    // MATCH (person:Person)
    // WHERE person.age = {0}
    // RETURN person ORDER BY person.name SKIP {skip} LIMIT {limit}
    Page<Person> findByAge(int age, Pageable pageable);

    // MATCH (person:Person)
    // WHERE person.age = {0}
    // RETURN person ORDER BY person.name
    List<Person> findByAge(int age, Sort sort);

    // Allow a custom depth as a parameter
    Person findByName(String name, @Depth int depth);

    // Set a fix depth of 0 for the query
    @Depth(value = 0)
    Person findBySurname(String surname);

}


public interface MovieRepository extends Neo4jRepository<Movie, Long> {

    @Query("MATCH (movie:Movie)-[r:RATING]->(), (movie)<-[:ACTS_IN]-(actor:Actor) " +
           "WHERE movie.id={0} " +
           "RETURN movie as movie, COLLECT(actor) AS cast, AVG(r.stars) AS averageRating")
    MovieData getMovieData(String movieId);
}


@QueryResult
public class MovieData {
    Movie movie;
    Double averageRating;
    Set<Actor> cast;
}


Repository-based paging

Pageable pageable = PageRequest.of(0, 3);
Page<World> page = worldRepository.findAll(pageable, 0);

Repository-based sorting

Sort sort = new Sort(Sort.Direction.ASC, "name");
Iterable<World> worlds = worldRepository.findAll(sort, 0)) {

Repository-based sorting with paging

Pageable pageable = PageRequest.of(0, 3, Sort.Direction.ASC, "name");
Page<World> page = worldRepository.findAll(pageable, 0);
@NodeEntity
public class Cinema {

  private Long id;
  private String name, location;

  @Relationship(type = "VISITED", direction = Relationship.INCOMING)
  private Set<User> visited = new HashSet<>();

  @Relationship(type = "BLOCKBUSTER", direction = Relationship.OUTGOING)
  private Movie blockbusterOfTheWeek;
  …
}

public interface CinemaRepository extends Neo4jRepository<Cinema, Long> {

  Cinema findByName(String name);
}



/***
 *@ClassName Neo4jRelationInfoRepository
 *@desc 八大关系型数据。
 *@Author xxxx
 *@Date 2019/5/17 0017 下午 5:43
 *@version 1.0.1
 **/
@Repository
public interface Neo4jRelationInfoRepository extends GraphRepository<Neo4jRelationInfo> {

    /**
     *  pe - pe 邻居关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:pe) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:邻居{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_LJ(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);

    /**
     *  pe -> pe 同学关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:pe) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:同学{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_TX(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);

    /**
     *  pe -> pe 校友关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:pe) where a.ids={fromId} and b.ids={toId}  merge (a) <- [r:校友{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_XY(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);

    /**
     *  pe -> li 居住关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:li) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:居住{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_JUZ(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);

    /**
     *  pe -> pe 同事关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:pe) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:同事{direction:{direction}}]-(b)")
    Neo4jRelationInfo generateGraphDataRelation_TS(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);



    /**
     *  pe -> wu 就职关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:wu) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:就职{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_JZGX(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);


    /**
     *  pe -> sc 毕业院校关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:sc) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:毕业{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_BYYX(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);


    /**
     *  pe -> pa 论文参与关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:pa) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:参与者{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_PA(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);

    /**
     *  pe -> pa 论文合作关系
     * @param fromId
     * @param toId
     * @return
     */
    @Query(value = "match(a:pe),(b:pe) where a.ids={fromId} and b.ids={toId}  merge (a) - [r:论文合作{direction:{direction}}]->(b)")
    Neo4jRelationInfo generateGraphDataRelation_LWHZ(@Param("fromId") String fromId, @Param("toId") String toId, @Param("direction") String direction);



    /**
     * web查询接口,查询与当前节点为1的数据---根据节点编号,适用于登录第二次节点点击之后的查询
     */
    @Query(value = "match(a)-[r]-(b) where a.ids={qid} return a,r,b")
    List<Map<String,String>> queryRelationDataByIds(@Param("qid") String qid);

    /**
     * web查询接口,查询与当前节点为1的数据
     */
    @Query(value = "match(a:pe)-[r]-(b) where a.cardNo={cardNo} return a,r,b")
    List<Map<String,String>> queryRelationDataByCardNo(@Param("cardNo") String cardNo);

}
/**
     * web查询接口,查询与当前节点为1的数据---根据节点编号,适用于登录第二次节点点击之后的查询。
     */
    @Query(value = "match(a)-[r]-(b) where a.ids={qid} return a,r,b")
    List<Map<String,String>> queryRelationDataByIds(@Param("qid") String qid);

    /**
     * web查询接口,用户登录之后第一次查询,需根据身份证号码查询。第二次查询就直接会调用上一个查询。
     */
    @Query(value = "match(a:pe)-[r]-(b) where a.cardNo={cardNo} return a,r,b")
    List<Map<String,String>> queryRelationDataByCardNo(@Param("cardNo") String cardNo);


https://my.oschina.net/u/4292020/blog/3262268

spring neo4j data

Spring Data JPA: 为所有Repository添加自定义方法

Spring Data JPA: 为单个Repository添加自定义方法

<colgroup> <col style="width: 16.6666%;"> <col style="width: 33.3333%;"> <col style="width: 50.0001%;"> </colgroup> <thead> </thead> <tbody> </tbody>
Table 2. Supported keywords for query methods
Keyword Sample Cypher snippet

After

findByLaunchDateAfter(Date date)

n.launchDate > date

Before

findByLaunchDateBefore(Date date)

n.launchDate < date

Containing (String)

findByNameContaining(String namePart)

n.name CONTAINS namePart

Containing (Collection)

findByEmailAddressesContains(Collection<String> addresses)

findByEmailAddressesContains(String address)

ANY(collectionFields IN [addresses] WHERE collectionFields in n.emailAddresses)

ANY(collectionFields IN address WHERE collectionFields in n.emailAddresses)

In

findByNameIn(Iterable<String> names)

n.name IN names

Between

findByScoreBetween(double min, double max)
findByScoreBetween(Range<Double> range)

n.score >= min AND n.score <= max

Depending on the Range definition n.score >= min AND n.score <= max or

n.score > min AND n.score < max

StartingWith

findByNameStartingWith(String nameStart)

n.name STARTS WITH nameStart

EndingWith

findByNameEndingWith(String nameEnd)

n.name ENDS WITH nameEnd

Exists

findByNameExists()

EXISTS(n.name)

True

findByActivatedIsTrue()

n.activated = true

False

findByActivatedIsFalse()

NOT(n.activated = true)

Is

findByNameIs(String name)

n.name = name

NotNull

findByNameNotNull()

NOT(n.name IS NULL)

Null

findByNameNull()

n.name IS NULL

GreaterThan

findByScoreGreaterThan(double score)

n.score > score

GreaterThanEqual

findByScoreGreaterThanEqual(double score)

n.score >= score

LessThan

findByScoreLessThan(double score)

n.score < score

LessThanEqual

findByScoreLessThanEqual(double score)

n.score <= score

Like

findByNameLike(String name)

n.name =~ name

NotLike

findByNameNotLike(String name)

NOT(n.name =~ name)

Near

findByLocationNear(Distance distance, Point point)

distance( point(n),point({latitude:lat, longitude:lon}) ) < distance

Regex

findByNameRegex(String regex)

n.name =~ regex

And

findByNameAndDescription(String name, String description)

n.name = name AND n.description = description

Or

findByNameOrDescription(String name, String description)

n.name = name OR n.description = description (Cannot be used to OR nested properties)

rule

MATCH (n:`version`) <-[r]->(m) where n.versionId='05dd46d1-6d84-481a-b6d3-d0baec9ffd68' delete r
MATCH (n:`version`) where n.versionId='05dd46d1-6d84-481a-b6d3-d0baec9ffd68' delete n
MATCH (n:`version`) where n.versionId='05dd46d1-6d84-481a-b6d3-d0baec9ffd68' return n

常用

create (n:`SZZY`{entitytype:0,name:"首页"}) return id(n)
MATCH (n:`数字中医`) -[r]-(m) delete r
MATCH (n:`数字中医`) delete n
create (n:`数字中医`{name:'首页'}) return id(n)
match(n) OPTIONAL MATCH (n)-[r]-() DELETE n,r

创建索引

create index on:Student(name)

删除索引

drop index on:Student(name)

创建唯一索引

create constraint on (s:Teacher) assert s.name is unique

删除唯一索引

drop constraint on (s:Teacher) assert s.name is unique

其他

1.删除带有关系的节点

 a、先删除关系 match (n:Node)-[r:关系名称]-() where (n...条件) delete r	
 b、删除节点 match (n:Node) where (n...条件)  delete n 

2.批量更新

 :param batch:[{prop1:'property1',prop2:'property2'},{prop1:'property11',prop2:'property22'}] 
UNWIND $batch  as data MATCH (c:Label1)-[r:关系]->(d:Label2) where c.prop1= data.prop1 and d.prop2=data.prop2 set r.prop= data.prop 

3.更新关系名称

 .apoc 
match (c:DictProduct)-[r:原关系]-(d:DictProduct) with r 
call apoc.refactor.setType(r, '新关系') yield input,output return * 

4.导出数据

 ./neo4j-admin  dump --database=kg.db --to=../ 

5.导入数据(dump文件)

 ./neo4j-admin load --from=./graph.db.dump --database=neo4j.db --force=true 
 导入数据(csv文件) 
   using periodic commit 1000 load csv from  "http://127.0.0.1:8080/data.csv"  as row CREATE (:Node{id:toInt(row[0]),prop1:toInt(row[1]),prop2:row[2],prop3:row[3],prop4:row[4]}) 

6.删除重复关系数据

  MATCH (a)-[r:相关公司]->(b) WITH a, b, TAIL (COLLECT (r)) as rr WHERE size(rr)>0 
  FOREACH (r IN rr | DELETE r) 


7.bolt链接报错的时候

Config noSSL = Config.build().withEncryptionLevel(Config.EncryptionLevel.NONE).toConfig(); 
Driver driver = GraphDatabase.driver( “bolt://127.0.0.1:7687”, AuthTokens.basic( “neo4j”, “nel4j” ), noSSL ); 
Session session = driver.session(); 

8.批量删除

MATCH (n:Node) where n.prop = 'prop' WITH n LIMIT 10000 DELETE n 

9.apoc 路径搜索(apoc)

match (startNode:Node{id:'00001'}),(endNode:Node2{id:00002}) CALL apoc.algo.dijkstra(startNode,endNode,,'min_travel_time') YIELD path,weight return path,weight 
match (startNode:Node{id:'00001'}),(endNode:Node2{id:00002}) CALL apoc.algo.dijkstra(startNode,endNode,,'distance') YIELD path,weight return path,weight

按id删除

MATCH (n:XWGJ) where id(n)=2995 delete n

下面的不行

MATCH (n:XWGJ) where n.id=2995 delete n

常用更新语句

更新相关操作

更新和添加一个属性

创建一个节点,只有一个属性name='张三'

CREATE ({name:'张三'})

给创建的"张三"节点,添加一个属性age=20,修改name属性值为"李四"

MATCH (n {name:'张三'}) 
SET n.name='李四'
SET n.age=20 
RETURN n

修改节点信息,覆盖节点属性

该语句会直接删除掉name属性,新增age属性

 MATCH (n {name:'张三'}) 
 SET n={age:20}

修改节点信息,新增节点属性

该语句不会删除掉name属性,而是在节点中新增age属性

MATCH (n {name:'张三'}) SET n += {age:20} 
RETURN n

为节点添加新标签

添加一个标签

MATCH (n{name:'张三'}) SET n:Person RETURN n

添加多个标签

MATCH (n{name:'张三'}) SET n:Person:Student RETURN n

为已经存在的两个节点添加关系

MATCH (a:Person {name: "张三"}),
   (b:Person {name: "李四"})
MERGE (a)-[r:FRIENDS]->(b)

匹配一个节点,更新属性如果属性不存在则创建该属性

MERGE (n:Person {name: "张三"})
 ON CREATE SET n.created = timestamp()
 ON MATCH SET
   n.counter = coalesce(n.counter, 0) + 1,
   n.accessTime = timestamp()

匹配一个节点为他创建一个新的关系

如果没有"王五"节点则创建一个新的

MATCH (a:Person {name: "张三"})
   MERGE
   (a)-[r:KNOWS]->(b:Person {name: "王五"})

欺诈环

最终查询:

Match (accountHolder:AccountHolder)-[]-(contactInformation)
With contactInformation,
count(accountHolder) AS RingSize
Match  (contactInformation)-[]-(accountHolder)
With  collect(accountHolder.UniqueId) AS AccountHolders,
contactInformation,RingSize
Where RingSize>1
Return AccountHolders AS FraudRing,
labels(contactInformation) AS ContactType,
RingSize
Order BY RingSize Desc


//最终查询分段 
Match (accountHolder:AccountHolder)-[]-(contactInformation)
With contactInformation,
count(accountHolder) AS RingSize
return  contactInformation , RingSize

统计根节点个数 统计叶节点个数

统计根节点个数:

match (n) where not ()-->(n) return count(distinct n)

统计叶节点个数:

match (n) where not (n)-->() return count(distinct n)

With用法示例

with从句可以连接多个查询的结果,即将上一个查询的结果用作下一个查询的开始。 两种用法:

  • 通过使用oder by 和limit,with可以限制传入下一个match子查询语句的实体数目。
  • 对聚合值过滤。

具体示例如下:

1.1 对聚合结果过滤

MATCH (david { name: "David" })--(otherPerson)-->() WITH otherPerson, count(*) AS foaf WHERE foaf > 1 RETURN otherPerson


代码块解释:(1)match与”David”关联(无向)的otherPerson;(2)然后return出度大于1的otherPerson。

1.2 对collect的元素进行排序

MATCH (n) WITH n ORDER BY n.name DESC LIMIT 3 RETURN collect(n.name)

代码块解释:(1)match所有人;(2)对所有人的name进行降序排列,并取top-3;(3)返回top-3的name并组成collect:返回结果为:[“Emil”,”David”,”Ceasar”]

1.3 在路径搜索的时候限制分支数

MATCH (n { name: "Anders" })--(m) WITH m ORDER BY m.name DESC LIMIT 1 MATCH (m)--(o) RETURN o.name

代码块解释:(1)从”Anders”出发,找到关联(无向)的所有人的集合m;(2)对集合m按照name降序排列,取top-1;(3)返回与top-1关联(无向)的所有人的name。

neo4j--Cypher语法练习(WITH、 FOREACH、Aggregation、UNWIND、UNION、CALL)

https://blog.csdn.net/qq_37503890/article/details/101565515?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase

中医知识库

MATCH (n:OLD_LABEL) REMOVE n:OLD_LABEL SET n:NEW_LABEL


MATCH (n:西医病名) REMOVE n:西医病名 SET n:西断
MATCH (n:Diagnosis) REMOVE n:Diagnosis SET n:症
MATCH (n:FangJi) REMOVE n:FangJi SET n:方
MATCH (n:ZhongYao) REMOVE n:ZhongYao SET n:药
MATCH (n:ZhongYaoPair) REMOVE n:ZhongYaoPair SET n:药对
MATCH (n:Treatment) REMOVE n:Treatment SET n:法
MATCH (n:加减变化) REMOVE n:加减变化 SET n:加减
MATCH (n:AcupointPair) REMOVE n:AcupointPair SET n:穴对
MATCH (n:Acupoint) REMOVE n:Acupoint SET n:穴
MATCH (n:Compare) REMOVE n:Compare SET n:比
MATCH (n:WBTB) REMOVE n:WBTB SET n:温病条辨
MATCH (n:WB) REMOVE n:WB SET n:温病
MATCH (n:YiAn) REMOVE n:YiAn SET n:案
MATCH (n:舌诊) REMOVE n:舌诊 SET n:舌
MATCH (n:脉诊) REMOVE n:脉诊 SET n:脉

MATCH (n:SimpleNote) REMOVE n:SimpleNote SET n:注
MATCH (n:XWGJ) REMOVE n:XWGJ SET n:性
MATCH (n:FuNotice) REMOVE n:FuNotice SET n:重
MATCH (n:TangTouGeJue) REMOVE n:TangTouGeJue SET n:诀
MATCH (n:HWSSHL) REMOVE n:HWSSHL SET n:郝万山伤寒

MATCH (n:伤寒论导入) REMOVE n:伤寒论导入 SET n:伤寒论
MATCH (n:妇科) REMOVE n:妇科 SET n:妇
MATCH (n:HWSSHL) REMOVE n:HWSSHL SET n:郝万山伤寒
MATCH (n:HWSSHL) REMOVE n:HWSSHL SET n:郝万山伤寒
MATCH (n:HWSSHL) REMOVE n:HWSSHL SET n:郝万山伤寒

问题解决

导入数字中医时,初始化时将一个对象直接保存了进去,然后查询出的内容一直是哪个空对象,连新建的对象的id都不能取到,后来只能重新创建了一个domain存储数据