生产环境_从数据到层级结构JSON:使用Spark构建多层次树形数据_父子关系生成

本文主要是介绍生产环境_从数据到层级结构JSON:使用Spark构建多层次树形数据_父子关系生成,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

代码补充了!兄弟萌

造的样例数据

val data = Seq(("USA", "Male", "Asian", "Chinese"),("USA", "Female", "Asian", "Chinese"),("USA", "Male", "Black", "African"),("USA", "Female", "Black", "African"),("USA", "Male", "White", "European"),("USA", "Female", "White", "European"),("Europe", "Male", "Asian", "Chinese"),("Europe", "Female", "Asian", "Chinese"),("Europe", "Male", "Black", "African"),("Europe", "Female", "Black", "African"),("Europe", "Male", "White", "European"),("Europe", "Female", "White", "European")
)

代码核心逻辑

import org.apache.hadoop.io.serializer.Serialization
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.types.{StringType, StructField, StructType}import org.apache.spark.sql.{Dataset, Row, SparkSession}
import org.json4s.NoTypeHints
import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization.writePretty定义Node类
//case class Node(title: String, key: String, children: Seq[Node])
/*作者:Matrix70
博客地址:https://blog.csdn.net/qq_52128187?type=blog
时间:20231205*/
object Parent_child_v7_xuqiu {def main(args: Array[String]): Unit = {val conf = new SparkConf().setAppName("Parent_child_v3").setMaster("local[1]")val sc = new SparkContext(conf)val spark = SparkSession.builder.appName("Parent_child_v3").getOrCreate()import spark.implicits._val df1 = sc.textFile("C:\\zzcode\\workplace\\src\\main\\data\\country")val schema = StructType(Array(StructField("Country", StringType, nullable = true),StructField("Gender", StringType, nullable = true),StructField("Ethnicity", StringType, nullable = true),StructField("Race", StringType, nullable = true)))val rowRDD = df1.map(line => {val parts = line.split(",")Row(parts(0), parts(1), parts(2), parts(3))})val df = spark.createDataFrame(rowRDD, schema)df.show()// 构建节点层级结构并转换为JSON格式def toHierarchy(df: Dataset[Row]): String = {def buildHierarchy(country: String): Node = {val uniqueGenders = df.filter($"Country" === country).select("Gender").distinct().as[String].collect()val genderNodes = uniqueGenders.map { gender =>val filteredRows = df.filter($"Country" === country && $"Gender" === gender)val ethnicityNodes = filteredRows.select("Ethnicity").distinct().as[String].collect().map { ethnicity =>val children = filteredRows.filter($"Ethnicity" === ethnicity).select("Race").as[String].collect().map(race => Node(race, s"$country-$gender-$ethnicity-$race", Seq.empty))Node(ethnicity, s"$country-$gender-$ethnicity", children)}Node(gender, s"$country-$gender", ethnicityNodes)}Node(country, country, genderNodes)}val uniqueCountries = df.select("Country").distinct().as[String].collect()val roots = uniqueCountries.map(buildHierarchy)implicit val formats: DefaultFormats.type = DefaultFormatswritePretty(roots)}// 调用toHierarchy并打印结果val resultJSON = toHierarchy(df)println(resultJSON)spark.stop()}
}

提供给前端的html树结构样例

代码生成结果提供给前端的格式

[{"title": "USA","key": "USA","children": [{"title": "Male","key": "USA-Male","children": [{"title": "Asian","key": "USA-Male-Asian","children": [{"title": "Chinese","key": "USA-Male-Asian-Chinese","children": []}]},{"title": "Black","key": "USA-Male-Black","children": [{"title": "African","key": "USA-Male-Black-African","children": []}]},{"title": "White","key": "USA-Male-White","children": [{"title": "European","key": "USA-Male-White-European","children": []}]}]},{"title": "Female","key": "USA-Female","children": [{"title": "Asian","key": "USA-Female-Asian","children": [{"title": "Chinese","key": "USA-Female-Asian-Chinese","children": []}]},{"title": "Black","key": "USA-Female-Black","children": [{"title": "African","key": "USA-Female-Black-African","children": []}]},{"title": "White","key": "USA-Female-White","children": [{"title": "European","key": "USA-Female-White-European","children": []}]}]}]},{"title": "Europe","key": "Europe","children": [{"title": "Male","key": "Europe-Male","children": [{"title": "Asian","key": "Europe-Male-Asian","children": [{"title": "Chinese","key": "Europe-Male-Asian-Chinese","children": []}]},{"title": "Black","key": "Europe-Male-Black","children": [{"title": "African","key": "Europe-Male-Black-African","children": []}]},{"title": "White","key": "Europe-Male-White","children": [{"title": "European","key": "Europe-Male-White-European","children": []}]}]},{"title": "Female","key": "Europe-Female","children": [{"title": "Asian","key": "Europe-Female-Asian","children": [{"title": "Chinese","key": "Europe-Female-Asian-Chinese","children": []}]},{"title": "Black","key": "Europe-Female-Black","children": [{"title": "African","key": "Europe-Female-Black-African","children": []}]},{"title": "White","key": "Europe-Female-White","children": [{"title": "European","key": "Europe-Female-White-European","children": []}]}]}]}
]
//https://blog.csdn.net/qq_52128187?type=blog

补充html文件

json生成前端界面展示代码,可以保存在本地文件,命名为html即可在浏览器打开查看,就是我上面的层级结构的样子了。

<!DOCTYPE html>
<html>
<head><title>JSON to Tree Example</title><script src="https://d3js.org/d3.v6.min.js"></script><style>.node circle {fill: #fff;stroke: steelblue;stroke-width: 1.5px;}.node text {font-size: 12px;}</style>
</head>
<body><div id="tree-container"></div><script>
// JSON字符串
const jsonStr = `{"title": "USA","key": "USA","children": [{"title": "Asian","key": "USA-Asian","children": [{"title": "Chinese","key": "USA-Asian-Chinese","children": [{"title": "Beijing","key": "USA-Asian-Chinese-Beijing","children": []}]}]},{"title": "Black","key": "USA-Black","children": [{"title": "African","key": "USA-Black-African","children": [{"title": "Nigeria","key": "USA-Black-African-Nigeria","children": []}]}]},{"title": "White","key": "USA-White","children": [{"title": "European","key": "USA-White-European","children": [{"title": "Italy","key": "USA-White-European-Italy","children": []}]}]}]
}`;// 解析JSON字符串为树状结构
const data = JSON.parse(jsonStr);// 创建绘图容器
const svg = d3.select("#tree-container").append("svg").attr("width", 500).attr("height", 500);// 创建树布局
const treeLayout = d3.tree().size([400, 400]);// 将数据转换为层级关系
const root = d3.hierarchy(data);// 计算节点的位置
treeLayout(root);// 绘制节点和链接
const nodes = root.descendants();
const links = root.links();const nodeGroup = svg.selectAll(".node").data(nodes).enter().append("g").attr("transform", d => `translate(${d.y}, ${d.x})`);nodeGroup.append("circle").attr("r", 5).style("fill", "#fff").style("stroke", "steelblue").style("stroke-width", "1.5px");nodeGroup.append("text").attr("x", 13).attr("y", 4).style("font-size", "12px").text(d => d.data.title);svg.selectAll(".link").data(links).enter().append("path").attr("class", "link").attr("d", d => {return `M${d.source.y},${d.source.x}L${d.target.y},${d.target.x}`;}).style("fill", "none").style("stroke", "#ccc").style("stroke-width", "1px");
</script>
</body>
</html>

其实我要的结果就是能匹配上数据格式,如下图。前端的同事他们渲染后,基本就是这个样子

参考文章获连接:

Ant Design Vue — An enterprise-class UI components based on Ant Design and Vue.js,这个网页是树形控件的结构,给我提供一个基本构建思路吧

ok!!!

这篇关于生产环境_从数据到层级结构JSON:使用Spark构建多层次树形数据_父子关系生成的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/461615

相关文章

如何使用celery进行异步处理和定时任务(django)

《如何使用celery进行异步处理和定时任务(django)》文章介绍了Celery的基本概念、安装方法、如何使用Celery进行异步任务处理以及如何设置定时任务,通过Celery,可以在Web应用中... 目录一、celery的作用二、安装celery三、使用celery 异步执行任务四、使用celery

使用Python绘制蛇年春节祝福艺术图

《使用Python绘制蛇年春节祝福艺术图》:本文主要介绍如何使用Python的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

详谈redis跟数据库的数据同步问题

《详谈redis跟数据库的数据同步问题》文章讨论了在Redis和数据库数据一致性问题上的解决方案,主要比较了先更新Redis缓存再更新数据库和先更新数据库再更新Redis缓存两种方案,文章指出,删除R... 目录一、Redis 数据库数据一致性的解决方案1.1、更新Redis缓存、删除Redis缓存的区别二

Jsoncpp的安装与使用方式

《Jsoncpp的安装与使用方式》JsonCpp是一个用于解析和生成JSON数据的C++库,它支持解析JSON文件或字符串到C++对象,以及将C++对象序列化回JSON格式,安装JsonCpp可以通过... 目录安装jsoncppJsoncpp的使用Value类构造函数检测保存的数据类型提取数据对json数

Redis事务与数据持久化方式

《Redis事务与数据持久化方式》该文档主要介绍了Redis事务和持久化机制,事务通过将多个命令打包执行,而持久化则通过快照(RDB)和追加式文件(AOF)两种方式将内存数据保存到磁盘,以防止数据丢失... 目录一、Redis 事务1.1 事务本质1.2 数据库事务与redis事务1.2.1 数据库事务1.

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

SpringBoot操作spark处理hdfs文件的操作方法

《SpringBoot操作spark处理hdfs文件的操作方法》本文介绍了如何使用SpringBoot操作Spark处理HDFS文件,包括导入依赖、配置Spark信息、编写Controller和Ser... 目录SpringBoot操作spark处理hdfs文件1、导入依赖2、配置spark信息3、cont

springboot整合 xxl-job及使用步骤

《springboot整合xxl-job及使用步骤》XXL-JOB是一个分布式任务调度平台,用于解决分布式系统中的任务调度和管理问题,文章详细介绍了XXL-JOB的架构,包括调度中心、执行器和Web... 目录一、xxl-job是什么二、使用步骤1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功

使用Nginx来共享文件的详细教程

《使用Nginx来共享文件的详细教程》有时我们想共享电脑上的某些文件,一个比较方便的做法是,开一个HTTP服务,指向文件所在的目录,这次我们用nginx来实现这个需求,本文将通过代码示例一步步教你使用... 在本教程中,我们将向您展示如何使用开源 Web 服务器 Nginx 设置文件共享服务器步骤 0 —