APOC是Neo4j 3.3版本推出時(shí)正式推薦的一個(gè)Java用戶擴(kuò)展過程包,里面包含豐富的函數(shù)和過程,作為對Cypher所不能提供的復(fù)雜圖算法和數(shù)據(jù)操作功能的補(bǔ)充,APOC還具有使用靈活、高性能等優(yōu)勢。
APOC的安裝:
- 在 https://github.com/neo4j-contrib/neo4j-apoc-procedures/releases 下載對應(yīng)的apoc jar 包放到Neo4j的plugin目錄下;
- 修改配置文件,conf目錄下的neo4j.conf,添加:
dbms.security.procedures.unrestricted=apoc.*
啟動(dòng)neo4j,運(yùn)行如下cypher,判斷類型
return apoc.meta.type('hello')返回STRING,注意返回值都是大寫。
return apoc.meta.type(["hello", "world"])返回LIST
create(n:Fruit{name:'apple', color:['red', 'green']})
match(n:Fruit) return apoc.meta.type(n.color)返回STRING[]
return apoc.meta.type(1)返回INTEGER
Tip:

如果出現(xiàn)上面的錯(cuò)誤,是因?yàn)榘惭b的時(shí)候沒有修改配置文件
應(yīng)用:
對Neo4j中的數(shù)據(jù)進(jìn)行修改,將字符串?dāng)?shù)組壓平為字符串,但是該屬性中既有字符串,又有字符串?dāng)?shù)組,需要判斷該屬性是哪種數(shù)據(jù)類型,進(jìn)行相應(yīng)的操作。Cypher自帶的size函數(shù),對于字符串返回的是字符串的長度,對于集合類型返回的是其中的元素個(gè)數(shù)。例如:
在前邊create(n:Fruit{name:'apple', color:['red', 'green']})的基礎(chǔ)上create(:Fruit{name:'banana', color:'yellow'})
查詢match(n:Fruit) return n.name, size(n.color)

可以看到,蘋果的顏色是一個(gè)字符串?dāng)?shù)組,長度是2,香蕉的顏色是一個(gè)字符串,長度是6,并不能通過
size函數(shù)有效的區(qū)分。
使用apoc中的函數(shù):apoc.meta.type()
查詢match(n:Fruit) return n.name, apoc.meta.type(n.color)

查找所有color屬性為字符串?dāng)?shù)組類型的節(jié)點(diǎn):
match(n:Fruit) where apoc.meta.type(n.color) = 'STRING[]' return n.name, n.color

此外apoc.meta.typeName()函數(shù)和apoc.meta.type()相同

壓平:
對數(shù)據(jù)類型為字符串?dāng)?shù)組的屬性值進(jìn)行壓平,中間用逗號(hào)隔開,逗號(hào)后邊跟一個(gè)空格,末尾不帶有括號(hào)。
create(n:Fruit{name:'grape', color:['purple', 'green', 'white']})
match(n:Fruit) where apoc.meta.type(n.color) = 'STRING[]' return substring(reduce(s='', x IN n.color | s + ', ' + x), 2)
這里使用到了Cypher自帶的reduce函數(shù)。


若將color屬性為字符串?dāng)?shù)組的,設(shè)置為字符串?dāng)?shù)組中的第一個(gè)元素:
match(n:Fruit) where apoc.meta.type(n.color) = 'STRING[]' set n.color = n.color[0]
連接:
APOC 用戶手冊 3.4.0.1 鏈接中包含可以查詢APOC的過程和函數(shù),如下
查詢APOC的過程和函數(shù)
參考:
http://neo4j.com.cn/topic/5ae72f3951bad0a10b198cca
https://blog.csdn.net/HaiYang_Gao/article/details/81320889
http://neo4j.com.cn/topic/5b5996abd40e09d75e4d235f
