摘要
NLP应用中一个很重要的内容是知识图谱,而图数据库是构建知识图谱的很好选择,所以,耍起
基本语句
Step 1 :创建实体
(1) CREATE (:Person {name:'TangBrother1', gender:'Male'})
Step 2 : 查询实体
(2) MATCH (p:Person) RETURN p
然后可以看到我们刚刚创建的Person实体TangBrother:
Step 3 :创建关系
首先,我们加入Uncle1 作为TangBrother1的父亲
(3) CREATE (:Person {name:'Uncle1', gender:'Male'})
然后,我们通过MATCH来得到这两个实体,并新建关系ChildOf
(4)
MATCH (u1:Person {name:'Uncle1'}), (b1:Person {name:'TangBrother1'})
CREATE (b1)-[:ChildOf]->(u1)
我们用命名(2)来查看一下当前的Person关系图,发现TangBrother1已经是Uncle1的Child了:
Step 4 :补充家庭关系
首先,创建我的家庭,包含我、我爹和我娘:
(5)
CREATE (:Person {name:'Me', gender:"Male"}), (:Person {name:'Father', gender:"Male"}), (:Person {name:'Mother', gender:"Female"})
创建我们家的关系:
(6)
MATCH (me:Person {name:'Me', gender:"Male"}), (dad:Person {name:'Father', gender:"Male"}), (mom:Person {name:'Mother', gender:"Female"}) CREATE (me)-[:ChildOf]->(dad), (me)-[:ChildOf]->(mom)
然后添加小姨妈一家,创建实体以及创建关系可以同时进行:
(7)
CREATE (aunt:Person {name:'Aunt1', gender:"Female"}), (brother:Person {name:'BiaoBrother1', gender:"Male"}), (brother)-[:ChildOf]->(aunt)
现在就有了三个家庭:我家,我叔叔家,和我小姨妈家
最后,将叔叔、小姨妈和我爹妈联系起来
(8)
MATCH (dad:Person {name:'Father'}), (uncle:Person {name:'Uncle1'}) CREATE (dad)-[:BrotherOf]->(uncle), (uncle)-[:BrotherOf]->(dad)
MATCH (mom:Person {name:'Mother'}), (aunt:Person {name:'Aunt1'}) CREATE (mom)-[:SisterOf]->(aunt), (aunt)-[:SisterOf]->(mom)
Step 5 :查找亲戚
我想要查找的远房兄弟姐妹,首先要做的就是找父母的兄弟姐妹,然后再找父母的兄弟姐妹的孩纸,有了这个思路,问题就很简单了
查找父母的兄弟姐妹,并查找他们的孩子:
(9)
MATCH (dad:Person {name:'Father'}), (mom:Person {name:'Mother'}), (p1:Person), (p2:Person)
WHERE
((p1)-[:BrotherOf]-(dad) or (p1)-[:SisterOf]-(dad) or
(p1)-[:BrotherOf]-(mom) or (p1)-[:SisterOf]-(mom))
AND
((p2)-[:ChildOf]-(p1) or (p2)-[:ChildOf]-(p1))
RETURN p2
得到最终结果:
完美!
总结
Neo4J确实好用,但是刚开始的时候还是遇到了很多坑
算是为知识图谱打基础了