使用Vue-neo4j绘制三国人物图谱关系

3 篇文章 0 订阅
1 篇文章 0 订阅

前言

发现一个很有用的Vue插件:https://www.npmjs.com/package/vue-neo4j
这个能在前端直连neo4j服务器啦,下图就是测试效果绘制三国人物图谱关系

演示地址

在这里插入图片描述

版本说明

  1. vue 3.0版本
  2. vue-neo4j 0.4.8版本
  3. neo4j服务端版本 4.3.6版本,可以直接去官网下载。
  4. echarts 5.22版本

开发说明

一、windows服务器部署neo4j

1、部署jdk11, 因为neo4j 4.3.6使用的版本是jdk11以上,否则启动不了哦

2、下载neo4j,解压

3、到 .\conf目录修改 neo4j.conf文件修改default_listen_address为0.0.0.0,因为不改的话,会导致启动后只能本机访问

在这里插入图片描述

4、cmd到.\bin目录执行 noe4j console. 这样就完成启动了

在这里插入图片描述

5、浏览器打开网址 http://127.0.0.1:7474

默认密码为neo4j/neo4j 首次进入会提示修改密码

二、vue3.0 版本前端工程说明

1、引入依赖 yarn add vue-neo4j

2、由于vue-neo4j 0.4.8 该版本只适配vue2.0版本,所以要改下源码,把 Vue.property.$neo4j 改为 Vue.config.globalProperties.$neo4j在这里插入图片描述

3、main.js引入

import VueNeo4j from 'vue-neo4j';
let app = createApp(App);
app.use(VueNeo4j );

在这里插入图片描述

4、逻辑编写

<template>
  <div class="neo4jMain">
    <div class="addContent">
      <el-form :inline="true" :model="formInline" :rules="rules" ref="neo4jform">
        <el-form-item label="开始节点名称" prop="startNode">
          <el-input v-model="formInline.startNode" placeholder="请输入开始节点名称"></el-input>
        </el-form-item>
        <el-form-item label="关系名称" prop="relationName">
          <el-input v-model="formInline.relationName" placeholder="请输入关系名称"></el-input>
        </el-form-item>
        <el-form-item label="结束节点名称" prop="endNode">
          <el-input v-model="formInline.endNode" placeholder="请输入结束节点名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
<!--          <el-button type="primary" @click="onDelete">清空表</el-button>-->
        </el-form-item>
      </el-form>
    </div>
    <div class="echarts" ref="echarts">
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "Main.vue",
  mounted() {
    this.query();
  },
  data() {
    return {
      formInline: {
        startNode: '',
        endNode: '',
        relationName: ''
      },
      rules: {
        startNode: [{required: true, trigger: 'blur'}],
        endNode: [{required: true, trigger: 'blur'}],
        relationName: [{required: true, trigger: 'blur'}]
      },
      protocol: 'bolt',
      host: '127.0.0.1',
      port: 7687,
      username: 'neo4j',
      password: '123456',
      echartsData: [],
      nodesRelation: []
    }
  },
  methods: {
    onDelete() {
      this.connect();
      const session = this.$neo4j.getSession();
      let cypher = `match p=(n:Person)-[]->(m:Person) delete p `;
      session.run(cypher);
      cypher = `MATCH (n:Person) delete n`;
      session.run(cypher).then(() => {
        session.close()
      });
      this.query();
    },
    initEcharts() {
      // 基于准备好的dom,初始化echarts实例
      let myChart = echarts.init(this.$refs.echarts)
      // 绘制图表
      myChart.setOption({
        title: {
          text: 'Neo4j 图谱关系'
        },
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            type: 'graph',
            layout: 'force',
            force: {
              edgeLength: 40,
              repulsion: 50,
              gravity: 0.1
            },
            symbolSize: 50,
            roam: true,
            label: {
              show: true
            },
            edgeSymbol: ['circle', 'arrow'],
            edgeSymbolSize: [4, 10],
            edgeLabel: {
              fontSize: 20
            },
            data: this.echartsData,
            // links: [],
            links: this.nodesRelation,
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }
        ]
      });
    },
    query() {
      this.connect();
      const session = this.$neo4j.getSession();
      let cypher = `match p=(n:Person)-[]->(m:Person) return p limit 1000`;
      session.run(cypher).then(res => {
        let records = res.records;
        let nodes = new Set();
        this.nodesRelation = [];
        for (let i = 0; i < records.length; i++) {
          nodes.add(records[i]._fields[0].segments[0].start.properties.name);
          nodes.add(records[i]._fields[0].segments[0].end.properties.name);
          this.nodesRelation.push({
            source: records[i]._fields[0].segments[0].start.properties.name,
            target: records[i]._fields[0].segments[0].end.properties.name,
            lineStyle: {
              curveness: 0
            },
            label: {
              show: true,
              formatter: function() {
                return records[i]._fields[0].segments[0].relationship.type
              }
            }
          });
        }
        let curveness = [0, 0.4, -0.4, 0.3, -0.3, 0.2, -0.2, 0.1, -0.1];
        for (let j = 0; j < this.nodesRelation.length; j++) {
          let repeatNumber = 0;
          for (let s = j+1; s < this.nodesRelation.length; s++) {
            let r1 = this.nodesRelation[j];
            let r2 = this.nodesRelation[s];
            if (r1.source === r2.source &&
                r1.target === r2.target) {
              repeatNumber =  repeatNumber + 1;
            }
            else if (r1.target === r2.source &&
                r1.source === r2.target) {
              repeatNumber =  repeatNumber + 1;
            }
          }
          this.nodesRelation[j].repeatNumber = repeatNumber;
        }
        for (let j = 0; j < this.nodesRelation.length; j++) {
          console.log(this.nodesRelation[j].repeatNumber);
          this.nodesRelation[j].lineStyle.curveness = curveness[this.nodesRelation[j].repeatNumber];
        }


        this.echartsData = [];
        nodes.forEach((e) => {
          let index = Math.ceil(Math.random()*10);
          let color = () => {
            if (index%4===0) {
              return '#228B22'
            } else if (index%4===1) {
              return '#FFFF00'
            } else if (index%4===2) {
              return '#20B2AA'
            } else if (index%4===3) {
              return '#FFB6C1'
            }
            return '#87CEFA';
          }
          this.echartsData.push({
            name: e,
            x: Math.random() * 100,
            y: Math.random() * 100,
            itemStyle: {
              color: color()
            }
          });
        })
        this.initEcharts();
      }).then(() => {
        session.close()
      });
    },
    onSubmit() {
      this.$refs.neo4jform.validate((valid) => {
        if (valid) {
          this.connect();
          const session = this.$neo4j.getSession();
          let cypher = `Merge (n:Person{name: '${this.formInline.startNode}'})
          Merge (m:Person{name: '${this.formInline.endNode}'}) Merge (n)-[r:${this.formInline.relationName}]->(m)`;
          session.run(cypher).then(() => {
            this.formInline = {
              startNode: '',
              endNode: '',
              relationName: ''
            };
            this.query();
          }).then(() => {
            session.close()
          });
        }
      })
    },
    connect() {
      return this.$neo4j.connect(this.protocol, this.host, this.port, this.username, this.password);
    },
    driver() {
      // Get a driver instance
      return this.$neo4j.getDriver()
    },
    testQuery() {
      // Get a session from the driver
      const session = this.$neo4j.getSession()

      // Or you can just call this.$neo4j.run(cypher, params)
      session.run('MATCH (n) RETURN n')
          .then(res => {
            console.log(res)
            // console.log(res.records[0].get('count'))
          })
          .then(() => {
            session.close()
          })
    }
  }
}
</script>

<style scoped lang="less">
.neo4jMain {
  height: 100%;
  display: flex;
  flex-direction: column;
  .addContent {
    padding: 15px;
    box-shadow: -10px 0 10px #D3D3D3, /*左边阴影*/ 10px 0 10px #D3D3D3, /*右边阴影*/
      0 -10px 10px #D3D3D3, /*顶部阴影*/ 0 10px 10px #D3D3D3;
  }

  .echarts {
    background-color: #333;
    flex: 1;
    flex-grow: 1;
  }
}
</style>

结束语

优点是前端可以直接操作数据库, 弊端是数据库配置暴露了。建议还是通过后端连接数据库操作数据。

  • 3
    点赞
  • 89
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
下面是一个简单的示例代码,展示了如何使用Vue.jsNeo4j和ECharts来实现图谱可视化: 1. 安装依赖: ``` npm install neo4j-driver echarts --save ``` 2. 在Vue.js组件中引入neo4j-driver和echarts: ```javascript import neo4j from 'neo4j-driver'; import echarts from 'echarts'; ``` 3. 定义Neo4j连接: ```javascript const driver = neo4j.driver( 'bolt://localhost:7687', neo4j.auth.basic('neo4j', 'password') ); ``` 4. 实现查询Neo4j数据库的函数: ```javascript async function runCypherQuery(query, params) { const session = driver.session(); const result = await session.run(query, params); session.close(); return result.records; } ``` 5. 在Vue.js组件中定义ECharts实例和数据: ```javascript data() { return { chart: null, chartData: { nodes: [], links: [] } }; }, mounted() { this.chart = echarts.init(this.$refs.chart); } ``` 6. 实现查询Neo4j数据库并将结果转换为ECharts数据格式的函数: ```javascript async function queryAndTransformData() { const result = await runCypherQuery('MATCH (n)-[r]->(m) RETURN n,r,m', {}); const nodes = []; const links = []; for (const record of result) { const node1 = record.get('n'); const node2 = record.get('m'); const link = record.get('r'); const node1Index = nodes.findIndex(node => node.id === node1.identity.toString()); const node2Index = nodes.findIndex(node => node.id === node2.identity.toString()); if (node1Index === -1) { nodes.push({ id: node1.identity.toString(), name: node1.properties.name }); } if (node2Index === -1) { nodes.push({ id: node2.identity.toString(), name: node2.properties.name }); } links.push({ source: node1.identity.toString(), target: node2.identity.toString(), name: link.type }); } return { nodes, links }; } ``` 7. 在Vue.js组件中实现获取数据、更新ECharts图表的函数: ```javascript async function updateChart() { const data = await queryAndTransformData(); this.chartData = data; const option = { series: [ { type: 'graph', layout: 'force', force: { repulsion: 100, edgeLength: 50 }, data: data.nodes.map(node => ({ name: node.name, draggable: true })), links: data.links.map(link => ({ source: link.source, target: link.target, name: link.name })), label: { show: true }, lineStyle: { width: 2, curveness: 0.3, color: '#999' } } ] }; this.chart.setOption(option); } ``` 8. 在Vue.js组件中调用updateChart()函数以获取数据并更新ECharts图表: ```javascript mounted() { this.chart = echarts.init(this.$refs.chart); this.updateChart(); }, methods: { async updateChart() { // 实现updateChart函数的代码 } } ``` 希望这个示例代码能够帮助你开始使用Vue.jsNeo4j和ECharts来实现图谱可视化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值