一、接口相关
在基于 Neo4j 图数据库的应用开发中,处理节点关系的增删改查是核心操作。本文将聚焦于两个常见的接口场景:删除已存在的关系,以及修改关系的属性。
1. 保存接口之删除节点关系
需求描述:开发一个保存接口,接收前端传来的待删除关系ID列表,并执行批量删除操作。请求数据格式示例如下:
"deletedRelationships": "1152925902653358196,1157429502280728692"
多个关系ID以逗号分隔。此功能可借鉴节点删除的逻辑来实现。
实现步骤:
第一步:编写删除节点关系的程序
核心操作基于Cypher查询语言。删除单个关系的语句如下:
MATCH ()-[r]->()
WHERE id(r) = 1152925902653358198
DELETE r
若要批量删除,则需要使用 IN 操作符。对应的Python程序实现如下:
def delete_node_relation(relation_ids):
node_relation_data = {"relation_ids":relation_ids}
# 删除关系
sql = """
MATCH ()-[r]->()
WHERE id(r) in["""+relation_ids+"""]
DELETE r
"""
writeMyLog(sql,'delete-sql-'+get_caller_line_number())
result = getSelectData(sql)
关键点:在Cypher语句中,用于匹配的多个ID必须用方括号 [] 包围。
第二步:测试
经过验证,上述程序功能正常。
2. 保存接口之修改节点关系属性
需求描述:开发一个保存接口,用于更新特定关系的属性。其请求体通常包含关系ID、类型、起止节点ID以及需要更新的属性键值对,数据结构示例如下:
"assignedRelationshipProperties":[
{
"relation_id":1152925902653358196,
"type": "CONNECTED_TO",
"s_node_id": 116,
"e_node_id": 115,
"properties": {
"weight": "1.0",
"description": "肌肉注射和静脉注射都是临床上常用的给药方法,适用于不同类型的药物。",
"source_id1": "内科/【47】宠物诊疗金鉴.pdf.txt-25000"
}
}
]
此功能同样可参考节点属性修改的逻辑,但通常只允许更新指定的几个业务字段(如示例中的weight、description、source_id),而不能修改关系的类型或连接的节点。
实现步骤:
第一步:编写修改节点关系属性的程序
基础的Cypher更新语句如下:
MATCH ()-[r]->()
WHERE id(r) = <relationship_id>
SET r.weight = 5, r.created_at = datetime()
基于此,编写Python处理程序。该程序需要解析传入的JSON数据,提取目标关系ID和需要更新的属性,并动态构建SET子句。
def assigned_node_relation(param_data):
if not param_data:
return jsonify({"error": "No JSON data received"}), 400
relation_id = defaultStr(param_data['relation_id'])
properties = param_data['properties']
description = ''
if 'description' in properties:
description = defaultStr(properties['description'])
source_id = ''
if 'source_id' in properties:
source_id = defaultStr(properties['source_id'])
weight = ''
if 'weight' in properties:
weight = defaultStr(properties['weight'])
if relation_id and (description or source_id or weight):
sql = """
MATCH ()-[n]->()
WHERE id(n) = """+relation_id
sql = jointUpdateSql(sql,'description',description)
sql = jointUpdateSql(sql,'source_id',source_id)
sql = jointUpdateSql(sql,'weight',weight)
sql = sql + """ RETURN n """
# writeMyLog(sql,'assigned_node_data-sql-'+get_caller_line_number())
result = getSelectData(sql)
res_json = {"relation_id":relation_id}
return json.dumps(res_json,ensure_ascii=False)
实现要点:
- 空值处理:需要对每个待更新的字段进行判断,仅当传入值非空时才将其加入更新语句。
- 字段管理:示例中硬编码了
description、source_id、weight三个字段。最佳实践是将这些可更新的标准字段定义在配置或常量中,后续增加字段只需修改一处。
第二步:测试
程序功能测试通过。