You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Neo4j合并重复边并将重复数设为权重的查询语句需求

Consolidating Duplicate Edges into Weighted Relationships in Neo4j

Sure thing! This is a common use case for turning duplicate edges into weighted relationships in Neo4j, and there's a straightforward query to handle it. Here's how you can make it work:

Core Query

First, replace YOUR_RELATION_TYPE with the actual relationship type you're working with (like CONNECTS_TO, FRIENDS_WITH, or whatever your graph uses):

// Step 1: Count how many duplicate edges exist between each node pair
MATCH (startNode)-[rel:YOUR_RELATION_TYPE]->(endNode)
WITH startNode, endNode, type(rel) AS relType, count(rel) AS edgeCount

// Step 2: Create or match a single edge between the nodes, set its weight to the duplicate count
MERGE (startNode)-[weightedRel:YOUR_RELATION_TYPE]->(endNode)
SET weightedRel.weight = edgeCount

// Optional Step 3: Clean up the original duplicate edges (removes redundancy)
WITH startNode, endNode, edgeCount, collect(rel) AS duplicateEdges
WHERE edgeCount > 1
UNWIND duplicateEdges AS oldEdge
DELETE oldEdge

What Each Part Does

Let’s break down the query so you understand exactly what’s happening:

  • MATCH (startNode)-[rel:YOUR_RELATION_TYPE]->(endNode): Pulls all edges of your target relationship type from the graph.
  • WITH startNode, endNode, type(rel) AS relType, count(rel) AS edgeCount: Groups edges by their start node, end node, and relationship type, then counts how many duplicates exist for each group.
  • MERGE (startNode)-[weightedRel:YOUR_RELATION_TYPE]->(endNode): Makes sure there’s exactly one edge of this type between the node pair—if one already exists, it matches it; if not, it creates a new one.
  • SET weightedRel.weight = edgeCount: Assigns the duplicate count as the weight property of the consolidated edge.
  • The final optional section deletes all original duplicate edges (only if there was more than one) to keep your graph clean and avoid redundant data.

Quick Notes

  • If your original edges have other properties you want to keep (not just the count), you can adjust the query to aggregate those values—for example, using avg(rel.someProperty) or head(collect(rel.someProperty)) to retain the first value from the duplicates.
  • Always test with a RETURN startNode, endNode, edgeCount instead of DELETE first to double-check the counts are correct before modifying your graph!

内容的提问来源于stack exchange,提问作者Stetco Oana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:01:59