知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Python 操作

简介: 知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - Python 操作

数据基于: 知识图谱(Knowledge Graph)- Neo4j 5.10.0 使用 - CQL - 太极拳传承谱系表

这是一个非常简单的web应用程序,它使用我们的Movie图形数据集来提供列表搜索、详细视图和图形可视化。

我们提供了两种不同的方式来运行应用程序:同步和异步(使用asyncio)。

Web framework:

  • sync: Flask (Micro-Webframework)
  • async: FastAPI (Micro-Webframework)

前端:

  • jquery
  • bootstrap
  • d3.js

Neo4j 数据连接: Neo4j Python Driver for Cypher Docs

py2neo 目前不支持 neo4j 5.X 所在使用 Neo4j Driver

Python连接Neo4j工具比较 Neo4j Driver、py2neo

依赖文件

基础依赖:requirements.txt

# common requirements for sync and async example
neo4j==5.10.0
typing_extensions==4.7.1

同步依赖:requirements-sync.txt

# common requirements
-r requirements.txt
# sync web framework
Flask==2.3.2

同步依赖:requirements-async.txt

# common requirements
-r requirements.txt
# async web framework
uvicorn==0.23.2
fastapi==0.101.1

安装依赖

同步依赖

D:\OpenSource\Neo4j\Python\dependencies> pip install -r requirements-sync.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

异步依赖

D:\OpenSource\Neo4j\Python\dependencies> pip install -r requirements-async.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

代码

#!/usr/bin/env python
import logging
import os
from json import dumps
from textwrap import dedent
from typing import cast
import neo4j
from flask import Flask, Response, request
from neo4j import GraphDatabase, basic_auth
from typing_extensions import LiteralString #这边红的波浪线,不用管
app = Flask(__name__, static_url_path="/static/")
# 获取环境变量值,如果没有就返回默认值
url = os.getenv("NEO4J_URI", "neo4j://172.16.3.64:7687")
username = os.getenv("NEO4J_USER", "neo4j")
password = os.getenv("NEO4J_PASSWORD", "password")
neo4j_version = os.getenv("NEO4J_VERSION", "5")
database = os.getenv("NEO4J_DATABASE", "neo4j")
port = int(os.getenv("PORT", 8080))
driver = GraphDatabase.driver(url, auth=basic_auth(username, password))
@app.route("/")
def get_index():
    return app.send_static_file("index.html")
def query(q: LiteralString) -> LiteralString:
    # this is a safe transform:
    # no way for cypher injection by trimming whitespace
    # hence, we can safely cast to LiteralString
    return cast(LiteralString, dedent(q).strip())
def serialize_person(person):
    return {
        "id": person["id"],
        "name": person["name"],
        "generation": person["generation"],
        "votes": person.get("votes", 0)
    }
@app.route("/search")
def get_search():
    try:
        q = request.args["q"]
    except KeyError:
        return []
    else:
        cql = query("""
                MATCH (p:Person) WHERE p.name CONTAINS $name RETURN p
            """)
        records, _, _ = driver.execute_query(
            cql,
            name=q,  #将参数 q 传给cql 变量
            database_=database,
            routing_="r",
        )
        for record in records:
            # 打印出 record 属性
            logging.info("%s, %s", record["p"]["name"], record["p"]["generation"])
        # desc = [record['p']["name"] for record in records]
        # logging.info(desc)
        return Response(
            # WEB 会显示序列化后的 JSON,汉字没有直观显示,属于正常现象
            dumps([serialize_person(record["p"]) for record in records]),
            mimetype="application/json"
        )
if __name__ == "__main__":
    logging.root.setLevel(logging.INFO)
    logging.info("Starting on port %d, database is at %s", port, url)
    try:
        app.run(port=port)
    finally:
        driver.close()

测试

http://127.0.0.1:8080/search?q=陈长兴

源码地址:https://gitee.com/VipSoft/VipNeo4j/tree/master/Python

参考:

https://github.com/neo4j-examples/movies-python-bolt

https://neo4j.com/developer/python/

目录
相关文章
|
5月前
|
存储 JSON 数据可视化
从零构建知识图谱:使用大语言模型处理复杂数据的11步实践指南
本文将基于相关理论知识和方法构建一个完整的端到端项目,系统展示如何利用知识图谱方法对大规模数据进行处理和分析。
754 7
从零构建知识图谱:使用大语言模型处理复杂数据的11步实践指南
|
7月前
|
机器学习/深度学习 人工智能 搜索推荐
Second Me:硅基生命或成现实?如何用AI克隆自己,打造你的AI数字身份!
Second Me 是一个开源AI身份系统,允许用户创建完全私有的个性化AI代理,代表用户的真实自我,支持本地训练和部署,保护用户隐私和数据安全。
883 8
Second Me:硅基生命或成现实?如何用AI克隆自己,打造你的AI数字身份!
|
10月前
|
数据采集 前端开发 物联网
【项目实战】通过LLaMaFactory+Qwen2-VL-2B微调一个多模态医疗大模型
本文介绍了一个基于多模态大模型的医疗图像诊断项目。项目旨在通过训练一个医疗领域的多模态大模型,提高医生处理医学图像的效率,辅助诊断和治疗。作者以家中老人的脑部CT为例,展示了如何利用MedTrinity-25M数据集训练模型,经过数据准备、环境搭建、模型训练及微调、最终验证等步骤,成功使模型能够识别CT图像并给出具体的诊断意见,与专业医生的诊断结果高度吻合。
17783 7
【项目实战】通过LLaMaFactory+Qwen2-VL-2B微调一个多模态医疗大模型
|
9月前
|
自然语言处理
高效团队的秘密:7大团队效能模型解析
3分钟了解7大团队效能模型,有效提升团队绩效。
759 7
高效团队的秘密:7大团队效能模型解析
|
人工智能 JSON 数据格式
RAG+Agent人工智能平台:RAGflow实现GraphRA知识库问答,打造极致多模态问答与AI编排流体验
【9月更文挑战第6天】RAG+Agent人工智能平台:RAGflow实现GraphRA知识库问答,打造极致多模态问答与AI编排流体验
3071 9
RAG+Agent人工智能平台:RAGflow实现GraphRA知识库问答,打造极致多模态问答与AI编排流体验
|
人工智能 运维 开发者
CodeFuse 开源官网上线啦~
CodeFuse是一个致力于开发大型代码语言模型以支持软件全生命周期的项目,涵盖设计、编码、测试等阶段,旨在提供创新的解决方案,优化开发者体验。其开源官网提供项目背景、相关AI开发项目展示、详细文档及贡献指南。团队已推出多个代码模型和开源工具,并在相关领域有学术成果和行业奖项。感兴趣者可通过GitHub、HuggingFace和魔搭社区主页联系或关注。
635 0
CodeFuse 开源官网上线啦~
|
存储 NoSQL 容灾
Neo4j【环境部署 01】图形数据库(简介+下载地址+安装+配置+demo源码+学习教程地址)
Neo4j【环境部署 01】图形数据库(简介+下载地址+安装+配置+demo源码+学习教程地址)
1572 1
|
数据库 知识图谱
知识图谱(Knowledge Graph)- Neo4j 5.10.0 Desktop & GraphXR 连接自建数据库
知识图谱(Knowledge Graph)- Neo4j 5.10.0 Desktop & GraphXR 连接自建数据库
189 0
vscode——Prettier插件保存自动格式化
vscode——Prettier插件保存自动格式化
513 0
|
NoSQL Java 数据库
neo4j图数据库下载安装配置
neo4j图数据库下载安装配置