题记:在同事的推荐下开始使用markdown写文档了,感觉不错,文章的排版会越来越好。
索引是为了更有效的查询数据,创建索引的代价就是增加了额外的存储空间和更慢的写入,决定是否创建索引是重要且意义重大的任务。本文主要介绍模式索引的创建与使用的相关内容。
Cypher能针对有label的node创建属性索引:
-
单属性索引:单个属性创建
-
复合索引:通过多个属性创建
索引一旦创建就会自动管理,并随着数据的更新自动创建。
1. 创建单个属性索引CREATE INDEX ON :Label(property)
example:CREATE INDEX ON :Person(firstname)
2. 查看数据库索引列表CALL db.indexes
result:
3. 创建复合索引CREATE INDEX ON :Label(prop1, …, propN)
example:CREATE INDEX ON :Person(firstname, surname)
特殊说明一下:当新增节点数据缺失属性,那么这个节点将不会被创建索引,比如:CREATE (a:Person {firstname: 'Bill', surname: 'Johnson', age: 34}), (b:Person {firstname: 'Sue', age: 39}
节点a有之前创建索引的两个属性,而b只有一个,因此b并能被创建复合索引。
4. 删除索引
-
删除单属性索引
DROP INDEX ON :Label(property)
-
删除复合索引
DROP INDEX ON :Label(prop1, …, propN)
5. 索引的使用
-
Match语句中使用
MATCH (person:Person { firstname: 'Andres' }) RETURN person
-
where语句中使用
单属性索引和复合索引均可以MATCH (n:Person) WHERE n.firstname = 'Bill' AND n.surname = 'Johnson' RETURN n
注意:复合索引并不支持以下单索引的查询
Existence: exists(n.prop)
Range: n.prop > value
STARTS WITH
ENDS WITH
CONTAINS -
索引中范围比较
MATCH (person:Person) WHERE person.firstname > 'B' RETURN person
-
索引中使用in
MATCH (person:Person) WHERE person.firstname IN ['Andres', 'Mark'] RETURN person
-
索引中使用STARTS WITH
MATCH (person:Person) WHERE person.firstname STARTS WITH 'And' RETURN person
-
索引中查看属性是否存在
MATCH (p:Person) WHERE exists(p.firstname) RETURN p
参考链接:https://neo4j.com/docs/developer-manual/3.3/cypher/schema/index/
注意:本文归作者所有,未经作者允许,不得转载