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 类型的数量值。
查询选项
| 选项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
entityId | string | 必填 | 起始节点 ID |
level | number | 1 | 最大跳数(1-10) |
direction | 'in' | 'out' | 'both' | 'both' | 查询方向 |
where | RuleGroup | - | 节点过滤条件 |
edgeWhere | EdgeFilterOptions | - | 边过滤条件 |
查询方向
// 统计关注的人数
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:
- Angular
- React
- Vue
import { useCountNeighbors } from '@aiao/rxdb-angular';
const count = useCountNeighbors(UserNode, () => ({
entityId: userId(),
level: 1
}));
import { useCountNeighbors } from '@aiao/rxdb-react';
const { value: count, isLoading } = useCountNeighbors(UserNode, {
entityId: userId,
level: 1
});
<script setup lang="ts">
import { useCountNeighbors } from '@aiao/rxdb-vue';
const { value: count } = toRefs(
useCountNeighbors(UserNode, () => ({
entityId: userId.value,
level: 1
}))
);
</script>
参考
- 图结构定义
- findNeighbors - 查找邻居节点
- findPaths - 查找路径