Neo4j使用心得

1、软件环境

Neo4j桌面端管理软件版本:1.2.4
安装的数据库版本是Neo4j3.5.17

2、数据库的交换

在项目中创建出数据库名称及数据库版本,会生成对应的数据库文件databases,可以通过粗暴地替换该数据库文件实现数据库的交换。(一台机器一般只能同时运行一个数据库)
在这里插入图片描述
在这里插入图片描述

3、本体文件转换成Neo4j文件

3.1、安装与导入

OWL文件导入Neo4j 4.1.3:
https://blog.csdn.net/wsj_518/article/details/110236557
官方教程(很清楚):
https://neo4j.com/labs/neosemantics/4.0/import/

这个博客写的很详细,注意:
1、安装neosemantics (n10s)时,要注意与Neo4j图数据库版本保持一致,可以直接在Neo4j客户端进行插件安装。
https://github.com/neo4j-labs/neosemantics/tree/4.3
在这里插入图片描述

2、导入命令中的本地文件地址字符串形式,例如
初始化配置

CREATE CONSTRAINT n10s_unique_uri ON (r:Resource) ASSERT r.uri IS UNIQUE
call n10s.graphconfig.init()
call n10s.rdf.import.fetch( "file:///D:/pythonproject/RDB2OWL/data/newOWL.ttl","Turtle")
也可以是其他格式,例如官方教程给出的Turtle, N-Triples, JSON-LD, RDF/XML, TriG and N-Quads
call n10s.rdf.import.fetch( "file:///D:/pythonproject/RDB2OWL/data/newOWL.rdf","RDF/XML")

本体文件的格式,可以直接使用protege进行另存。

在这里插入图片描述
在这里插入图片描述

3.2、导入到Neo4j的效果分析

使用n10s将本体文件导入到Neo4j时,会将本体文件中自带概念、属性一并导入进来,在本体中自定义的类、数据属性和关系属性等都被添加了ns0前缀,但是数据属性的值没有被加前缀,
在这里插入图片描述

3.2、导入后的n10s的前缀处理

将中文开放知识图谱的owl文件导入到neo4j中,踩坑总结
https://blog.csdn.net/qq_43071444/article/details/121200748
OWL/RDF导入neo4j前缀消除,踩坑总结
https://blog.csdn.net/yaminne/article/details/118768139
采用的是match(n) where n.uri=~"http://www.kgtest.com#.*" set n.uri=substring(n.uri,22) return n CQL语句。

去除节点的uri属性值的http前缀
match(n) where n.uri=~"http://www.semanticweb.org/kert/ontologies/2022/6/BMMOntology#.*" set n.uri=substring(n.uri,62)    return n 
typesToLabels: false,//生成实例与类相连,无类别 ,经过n10s 4.3.0.0版本的测试,没有实现 生成实例与类相连
call n10s.rdf.import.fetch( "file:///D:/pythonproject/RDB2OWL/data/importNeo4j/BMMOntology_reasoning.owl","RDF/XML",{typesToLabels:false})

此处还提供一份python代码用于批量去除图数据库中的标签标签、关系、属性字段中的ns0__前缀

# -*- coding: utf-8 -*-
# @Time : 2022-09-01 19:46
# @Author : 山南君
# @Function : 使用python和原生Cypher语句操作Neo4j图数据,主要是为了修改 本体经n10s转存到Neo4j的图数据库标签、关系、属性字段中的ns0__前缀。使用的是官方的neo4j-driver 4.4.6
# @History :
# @Software: PyCharm
from neo4j import GraphDatabase

class CQLHelper:
    def __init__(self):
        self.uri = "neo4j://localhost:7687"
        self.driver = GraphDatabase.driver(self.uri, auth=("neo4j", "123456"))

    def RunCQLstrs(self,CQLstrPath):
        '''
        从txt文件中按行读取多条CQL命令进行循环执行
        Args:
            CQLstrPath: CQL命令所在txt文件路径
        Returns:
        '''
        CQLstrs = [i.strip() for i in open(CQLstrPath, encoding='utf-8') if i.strip()]
        for cql in CQLstrs:
            if len(cql)!=0:
                with self.driver.session() as session:
                    res = session.run(cql)
                    print(res.data())

    def updateRelation(self):
        cql1="MATCH ()-[r]->() RETURN r "
        relations=[]
        with self.driver.session() as session:
            res = session.run(cql1)
            for dt in res.data():
                relation=dt['r'][1]
                if relation not in relations:
                    relations.append(relation) #将所有的关系放在一个list中

        #将关系名中的ns0__前缀删除
        for relation in relations:
            newRelation=str.replace(relation,"ns0__","")
            cql2 = "match(n)-[r:{0}]->(m) create(n)-[r2:{1}]->(m) set r2=r with r delete r".format(relation,newRelation)
            with self.driver.session() as session:
                res = session.run(cql2)
                print(res.data())

    def updateLabelAndProperty(self):
        cql1="Match (n) return  labels(n) AS label"
        labels=[]
        with self.driver.session() as session:
            res = session.run(cql1)
            for li in res.data():
                label=li['label']
                labels=labels+label

        labels=list(set(labels)) #对标签进行去重
        print(labels)
        #修改标签名,去除标签名中的ns0__ 前缀
        for lab in labels:
            if "ns0__" in lab:
                newlab = str.replace(lab, "ns0__", "")
                cqlstr=''' MATCH (n:`{0}`)  REMOVE n:`{0}`  SET n:`{1}`   '''.format(lab,newlab)
                with self.driver.session() as session:
                    res = session.run(cqlstr)
                print("标签:", lab,  "新标签:", newlab)
        print("图数据库中的所有标签集合:",labels)
        print("所有标签已经修改完成,或者没有要修改的标签")

        #按标签类型获取每个标签类型的字段属性集合
        for lab in labels:
            props = []
            cql2 = r"MATCH (n:`{0}`) WITH n  UNWIND keys(n) as key RETURN distinct key".format(lab)
            with self.driver.session() as session:
                res = session.run(cql2)
                for i in res.data():
                    if i not in props:
                        props.append(i['key'])
            print("标签:", lab, "对应的属性集合:", props)

            #按标签名依次去除该标签名的属性名中的 ns0__ 前缀
            for key in props:
                if "ns0__" in key:
                    newKey=str.replace(key,"ns0__","")
                    cql3 = "match(n:`{0}`) set n.`{1}`=n.`{2}` remove n.`{2}`".format(lab,newKey,key)
                    with self.driver.session() as session:
                        res = session.run(cql3)
                    print("标签:", lab, "属性:", key,"新属性:",newKey)
        print("所有标签的所有属性已经修改完成,或者没有要修改的属性")

if __name__ == '__main__':
    helper=CQLHelper()
    path="CQLStrings.txt"
    helper.updateLabelAndProperty()

9、其他拓展资料

1、如何在一台机器上同时运行多个图数据库
https://blog.csdn.net/ljp1919/article/details/103170995
2、neo4j属性无法写入的字符
https://blog.csdn.net/for_yayun/article/details/121148849
由于Neo4j不支持特殊字符,如 - []等,但是支持下划线和小数点_ .,所以使用n10s时导入本体时,就要求本体中不可以包含一些特殊字符。如果本体中包括特殊字符,n10s就会报错。
在这里插入图片描述

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Neo4j是一个基于图形理论的高性能图形数据库。它使用图形结构存储数据,因此非常适合处理大量复杂而相互关联的数据。下面是Neo4j使用教程: 1. 下载Neo4j: 首先你需要下载和安装Neo4j,可以在官网上下载对应的版本。 2. 启动Neo4j:安装完成后,启动Neo4j服务器。在浏览器中输入http://localhost:7474/访问Neo4j Web Console。 3. 建立节点和关系:在Neo4j中,节点是数据的基本单元,而关系是节点之间的连接。通过Cypher语言可以对节点和关系进行操作。以下是一些示例代码: 创建节点: CREATE (n:Person {name: 'John', age: 25}) 创建关系: MATCH (a:Person),(b:Person) WHERE a.name = 'John' AND b.name = 'Tom' CREATE (a)-[r:Friend]->(b) 4. 查询数据:在Neo4j中,可以通过Cypher查询语言查询数据。以下是一些示例代码: 查找所有节点: MATCH (n) RETURN n 查找所有名为John的人: MATCH (n:Person {name: 'John'}) RETURN n 查找John和Tom之间的关系: MATCH (a:Person)-[r:Friend]->(b:Person) WHERE a.name = 'John' AND b.name = 'Tom' RETURN r 5. 删除节点和关系:在Neo4j中,可以通过Cypher删除语言删除节点和关系。以下是一些示例代码: 删除所有节点和关系: MATCH (n) DETACH DELETE n 删除名为John的人及其关系: MATCH (n:Person {name: 'John'}) DETACH DELETE n 以上是Neo4j的简单使用教程,更多详细的内容可以参考官方文档。如果有任何问题,欢迎随时向我提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值