如何在JavaScript中使用Gremlin查询获取所有互连顶点的全部属性值
JavaScript获取关联顶点全属性的实现方案
以下是两种最常用场景下的实现方式,可直接匹配你提到的「查询business顶点及它出边关联的video、image顶点全属性」的需求:
场景1:内存自定义图结构
如果你的图数据是存在前端/Node.js内存中的自定义结构,可参考以下实现:
// 示例图数据结构,可直接替换为你自己的结构 const graph = { // 所有顶点集合,每个顶点保留全量属性 vertices: [ { id: 'b1', type: 'business', name: 'XX商户', address: 'XX街道XX号', contact: '13XXXXXXXXX' }, { id: 'v1', type: 'video', title: '商户宣传片', duration: 115, format: 'mp4' }, { id: 'i1', type: 'image', title: '商户门头照', size: '1.8M', resolution: '1920*1080' } ], // 所有边集合,记录顶点关联关系 edges: [ { from: 'b1', to: 'v1', relation: 'has_video' }, { from: 'b1', to: 'i1', relation: 'has_image' } ] } /** * 获取起始顶点及它所有出边关联的顶点全属性 * @param {string} startVertexId 起始顶点id,也就是你的business顶点id * @param {object} graph 图结构数据 * @returns {array} 所有关联顶点的全属性集合 */ function getConnectedVertices(startVertexId, graph) { // 先获取起始顶点的全属性 const startVertex = graph.vertices.find(v => v.id === startVertexId) if (!startVertex) return [] // 获取所有出边指向的关联顶点 const relatedVertices = graph.edges .filter(edge => edge.from === startVertexId) .map(edge => graph.vertices.find(v => v.id === edge.to)) .filter(Boolean) // 合并返回所有顶点的全量属性 return [startVertex, ...relatedVertices] } // 调用示例 const result = getConnectedVertices('b1', graph) console.log(result) // 输出包含business、video、image三个顶点的全属性数组
场景2:Neo4j图数据库(Node.js环境)
如果你的图数据存储在Neo4j中,可直接通过Cypher语句一次性查询所有关联顶点的全属性,无需多次查询:
首先安装官方JS驱动:
npm install neo4j-driver实现代码:
const neo4j = require('neo4j-driver') // 初始化Neo4j连接,替换为你自己的数据库连接信息 const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', '你的数据库密码')) async function getBusinessAllRelated(businessId) { const session = driver.session() try { // Cypher语句说明:*0..1表示查询深度为0到1层,包含起始顶点本身和直接关联的顶点 const queryRes = await session.run(` MATCH (b:business {id: $businessId})-[*0..1]->(vertex) RETURN collect(DISTINCT properties(vertex)) AS all_vertices `, { businessId }) return queryRes.records[0].get('all_vertices') } finally { await session.close() } } // 调用示例 getBusinessAllRelated('b1').then(console.log)
如果需要查询更深层的关联顶点,只需要修改Cypher语句里的深度参数即可,比如*0..3就是查询最多3层关联的所有顶点。
内容的提问来源于stack exchange,提问作者Alok Hegde
相关产品推荐
相关产品推荐

