跳到主要内容

countNeighbors

统计图结构中邻居节点的数量,高性能版本(不返回完整节点数据)。

基本用法

import { UserNode } from './entities/UserNode';

// 统计直接好友数量
const friendCount = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 1
});

// 统计 2 度人脉数量
const networkSize = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 2
});

返回结果

返回 number 类型的数量值。

查询选项

选项类型默认值说明
entityIdstring必填起始节点 ID
levelnumber1最大跳数(1-10)
direction'in' | 'out' | 'both''both'查询方向
whereRuleGroup-节点过滤条件
edgeWhereEdgeFilterOptions-边过滤条件

查询方向

// 统计关注的人数
const followingCount = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 1,
direction: 'out'
});

// 统计粉丝数
const followerCount = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 1,
direction: 'in'
});

// 统计双向连接数(默认)
const connectionCount = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 1,
direction: 'both'
});

过滤条件

// 按节点属性过滤
const businessContactCount = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 2,
where: {
combinator: 'and',
rules: [{ field: 'type', operator: '=', value: 'business' }]
}
});

// 按边属性过滤
const highValueFriendCount = await UserNode.countNeighbors({
entityId: 'alice-id',
level: 1,
edgeWhere: {
weight: { min: 5 }
}
});

与 findNeighbors 的区别

  • countNeighbors 只返回数量,性能更高
  • findNeighbors 返回完整节点数据和边信息
  • 统计规则与 findNeighbors 一致(不包含起始节点)

框架集成

各框架提供响应式 Hooks:

import { useCountNeighbors } from '@aiao/rxdb-angular';

const count = useCountNeighbors(UserNode, () => ({
entityId: userId(),
level: 1
}));

参考