一、搭建 Neo4j 图数据库
1、方式选择
- windows 使用 Neo4j Desktop (2024-12-09开始 Neo4j desktop 无法打开表现为三个/四个僵尸进程,查看本地日志会发现[403]无法获取到https://dist.neo4j.org/neo4j-desktop/win/latest.yml这个路径的资源。解决方案:断网打开 Neo4j Desktop / Neo4j Desktop 1.5.8 Launches Zombie Processes Only - Neo4j Graph Platform / Desktop - Neo4j Online Community)
- 云环境 dockerfile + docker-compose (部署构建简单易懂无需专注 jdk 版本,优先考虑)
- 最终理想化:kubernetes 部署 (符合主流技术导向,虽说部署较复杂且多坑但是企业级以及行业主导地位等因素使用 k8s 部署还是最佳实践)
首次部署优先采用 dockerfile + docker-compose
2、Dockerfile+docker-compose部署neo4j容器
2.1、更新 yum 镜像源
bash
rm -rf /etc/yum.repos.d/* wget -O /etc/yum.repos.d/centos7.repo http://mirrors.aliyun.com/repo/Centos-7.repo wget -O /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
2.2、安装 docker-ce 社区版
bash
yum install -y docker-ce
2.3、配置镜像加速
bash
cat > /etc/docker/daemon.json << EOF
{
"exec-opts": ["native.cgroupdriver=systemd"],
"registry-mirrors": [
"https://dockerhub.icu",
"https://hub.rat.dev",
"https://docker.wanpeng.top",
"https://doublezonline.cloud",
"https://docker.mrxn.net",
"https://docker.anyhub.us.kg",
"https://dislabaiot.xyz",
"https://docker.fxxk.dedyn.io"
]
}
EOF
systemctl daemon-reload && systemctl restart docker && systemctl enable docker
2.4、安装 Docker Compose
2.4.1、下载 Docker Compose 二进制包
bash
curl -L "https://github.com/docker/compose/releases/download/v2.5.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
-L: 是curl的一个选项,表示跟随重定向。如果下载链接是重定向的,这个选项会让curl自动跟踪到最后的目标地址。"https://github.com/docker/compose/releases/download/v2.5.1/docker-compose-$(uname -s)-$(uname -m)": 这是Docker Compose的下载URL,其中v2.5.1指定了要下载的Docker Compose版本号。$(uname -s)和$(uname -m)是shell命令,分别返回当前系统的类型(如Linux)和机器的硬件架构(如x86_64),这样可以确保下载与当前系统架构相匹配的Docker Compose二进制文件。-o /usr/local/bin/docker-compose:-o或--output指定了下载文件的保存位置及名称。这里,文件会被保存为/usr/local/bin/docker-compose,这是Docker Compose常见的安装路径,将其放在此处可以使其在PATH环境变量中,从而可以直接在命令行中通过docker-compose命令调用。
2.4.2、设置可执行权限
bash
chmod +x /usr/local/bin/docker-compose
2.4.3、查看版本
bash
docker-compose -v
2.5、创建目录结构
bash
mkdir -p neo4j-docker/{conf,data,import,logs} && touch neo4j-docker/conf/neo4j.conf
chown -R neo4j:neo4j ./{conf,data,import,logs}
chmod 755 ./{conf,data,logs,import}
tree -L 2 neo4j-docker
neo4j-docker
├── conf
│ └── neo4j.conf
├── data
├── import
└── logs
2.6、编写neo4j.conf配置文件
bash
cat > /root/neo4j-docker/conf/neo4j.conf << EOF server.directories.import=/var/lib/neo4j/import server.memory.pagecache.size=512M server.default_listen_address=0.0.0.0 dbms.security.allow_csv_import_from_file_urls=true server.directories.logs=/logs EOF
2.7、编写 dockerfile 文件
dockerfile
cat > /root/neo4j-docker/Dockerfile << EOF # 使用官方 Neo4j 最新版本镜像作为基础镜像 FROM neo4j:latest # 设置环境变量,仅用于配置 Neo4j 认证 ENV NEO4J_AUTH=neo4j/neo4jpassword # 拷贝本地的配置文件到容器中 COPY ./conf/neo4j.conf /var/lib/neo4j/conf/ # 定义容器启动时执行的命令 CMD ["neo4j"] EOF
2.8、构建ne4j容器镜像
bash
# 命令位置需要与Dockerfile位置同级 docker build -t my_neo4j:v1 .
2.9、编写docker-compose.yaml文件
有坑:neo4j 5.x 版本所需密码位数需要在 8 位以上
yaml
version: '3'
services:
neo4j:
build: .
image: my_neo4j:v1
container_name: neo4j_container
restart: always
ports:
- "7474:7474"
- "7687:7687"
environment:
- NEO4J_AUTH=neo4j/neo4jpassword
volumes:
- ./data:/data
- ./logs:/logs
- ./import:/var/lib/neo4j/import
- ./conf:/var/lib/neo4j/conf
command: ["neo4j"]
2.10、运行docker-compose
bash
docker-compose -f docker-compose.yaml up -d
2.11、浏览器登录 neo4j
bash
http://192.168.112.30:7474 # 输入用户名:neo4j # 输入密码:neo4jpassword
二、Neo4j 初始配置
1、清空 Neo4j 数据库
cypher
MATCH (n) DETACH DELETE n
三、PyCharm 项目安装必备库
1、py2neo 库
python
pip install py2neo
简化 Neo4j 连接和查询
- 连接到 Neo4j:
py2neo提供了简单易用的接口来连接到 Neo4j 数据库,支持 HTTP 和 Bolt 协议。 - 执行 Cypher 查询:
py2neo允许你直接执行 Cypher 查询(Neo4j 的图查询语言),并以 Python 对象的形式返回结果。
- 连接到 Neo4j:
创建和管理图数据
- 创建节点和关系:
py2neo提供了高级抽象,允许你像操作 Python 对象一样创建和管理 Neo4j 中的节点和关系。你可以使用Node和Relationship类来表示图中的实体,并将它们保存到数据库中。 - 批量操作:
py2neo支持批量创建节点和关系,提高性能,减少网络往返次数。
- 创建节点和关系:
2、pymongo 库
python
pip install pymongo
- 用于连接和操作 MongoDB 数据库,读取、处理并重新插入医疗数据。
- 提供了高效的 CRUD 操作,支持批量数据处理。
3、lxml 库
python
pip install lxml
- 用于解析存储在 MongoDB 中的 HTML 文档,提取有用的医疗检查信息(如疾病名称、描述等)。
- 通过 XPath 提取数据,并进行必要的清理和格式化。
四、python 连接 Neo4j
1、浏览器 browser 查看Neo4j 连接状态
cypher
:server status
记住 URL (不是传统意义上的 http://,以及默认的端口号7474)
2、修改源文件中 Graph 连接格式
python
import os
import json
from py2neo import Graph,Node
class MedicalGraph:
def __init__(self):
cur_dir = '/'.join(os.path.abspath(__file__).split('/')[:-1])
self.data_path = os.path.join(cur_dir, 'data/medical.json')
self.g = Graph("neo4j://192.168.112.30:7687", auth=("neo4j", "neo4jpassword"))
build_medicalgraph.py和answer_search.py两个原文件中的self.g = Graph()的连接格式都更改为上述代码中的格式。
五、PyCharm 导入医疗知识图谱
1、读取文件
python
# 读取文件
def read_nodes(self):
# 共7类节点
drugs = [] # 药品
foods = [] # 食物
checks = [] # 检查
departments = [] #科室
producers = [] #药品大类
diseases = [] #疾病
symptoms = []#症状
disease_infos = []#疾病信息
# 构建节点实体关系
rels_department = [] # 科室-科室关系
rels_noteat = [] # 疾病-忌吃食物关系
rels_doeat = [] # 疾病-宜吃食物关系
rels_recommandeat = [] # 疾病-推荐吃食物关系
rels_commonddrug = [] # 疾病-通用药品关系
rels_recommanddrug = [] # 疾病-热门药品关系
rels_check = [] # 疾病-检查关系
rels_drug_producer = [] # 厂商-药物关系
rels_symptom = [] #疾病症状关系
rels_acompany = [] # 疾病并发关系
rels_category = [] # 疾病与科室之间的关系
count = 0
for data in open(self.data_path, encoding='utf8', mode='r'):
disease_dict = {}
count += 1
print(count)
data_json = json.loads(data)
disease = data_json['name']
disease_dict['name'] = disease
diseases.append(disease)
disease_dict['desc'] = ''
disease_dict['prevent'] = ''
disease_dict['cause'] = ''
disease_dict['easy_get'] = ''
disease_dict['cure_department'] = ''
disease_dict['cure_way'] = ''
disease_dict['cure_lasttime'] = ''
disease_dict['symptom'] = ''
disease_dict['cured_prob'] = ''
if 'symptom' in data_json:
symptoms += data_json['symptom']
for symptom in data_json['symptom']:
rels_symptom.append([disease, symptom])
if 'acompany' in data_json:
for acompany in data_json['acompany']:
rels_acompany.append([disease, acompany])
if 'desc' in data_json:
disease_dict['desc'] = data_json['desc']
if 'prevent' in data_json:
disease_dict['prevent'] = data_json['prevent']
if 'cause' in data_json:
disease_dict['cause'] = data_json['cause']
if 'get_prob' in data_json:
disease_dict['get_prob'] = data_json['get_prob']
if 'easy_get' in data_json:
disease_dict['easy_get'] = data_json['easy_get']
if 'cure_department' in data_json:
cure_department = data_json['cure_department']
if len(cure_department) == 1:
rels_category.append([disease, cure_department[0]])
if len(cure_department) == 2:
big = cure_department[0]
small = cure_department[1]
rels_department.append([small, big])
rels_category.append([disease, small])
disease_dict['cure_department'] = cure_department
departments += cure_department
if 'cure_way' in data_json:
disease_dict['cure_way'] = data_json['cure_way']
if 'cure_lasttime' in data_json:
disease_dict['cure_lasttime'] = data_json['cure_lasttime']
if 'cured_prob' in data_json:
disease_dict['cured_prob'] = data_json['cured_prob']
if 'common_drug' in data_json:
common_drug = data_json['common_drug']
for drug in common_drug:
rels_commonddrug.append([disease, drug])
drugs += common_drug
if 'recommand_drug' in data_json:
recommand_drug = data_json['recommand_drug']
drugs += recommand_drug
for drug in recommand_drug:
rels_recommanddrug.append([disease, drug])
if 'not_eat' in data_json:
not_eat = data_json['not_eat']
for _not in not_

