生产环境_从数据到层级结构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

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

基于MySQL Binlog的Elasticsearch数据同步实践

一、为什么要做 随着马蜂窝的逐渐发展,我们的业务数据越来越多,单纯使用 MySQL 已经不能满足我们的数据查询需求,例如对于商品、订单等数据的多维度检索。 使用 Elasticsearch 存储业务数据可以很好的解决我们业务中的搜索需求。而数据进行异构存储后,随之而来的就是数据同步的问题。 二、现有方法及问题 对于数据同步,我们目前的解决方案是建立数据中间表。把需要检索的业务数据,统一放到一张M

关于数据埋点,你需要了解这些基本知识

产品汪每天都在和数据打交道,你知道数据来自哪里吗? 移动app端内的用户行为数据大多来自埋点,了解一些埋点知识,能和数据分析师、技术侃大山,参与到前期的数据采集,更重要是让最终的埋点数据能为我所用,否则可怜巴巴等上几个月是常有的事。   埋点类型 根据埋点方式,可以区分为: 手动埋点半自动埋点全自动埋点 秉承“任何事物都有两面性”的道理:自动程度高的,能解决通用统计,便于统一化管理,但个性化定

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

异构存储(冷热数据分离)

异构存储主要解决不同的数据,存储在不同类型的硬盘中,达到最佳性能的问题。 异构存储Shell操作 (1)查看当前有哪些存储策略可以用 [lytfly@hadoop102 hadoop-3.1.4]$ hdfs storagepolicies -listPolicies (2)为指定路径(数据存储目录)设置指定的存储策略 hdfs storagepolicies -setStoragePo

Hadoop集群数据均衡之磁盘间数据均衡

生产环境,由于硬盘空间不足,往往需要增加一块硬盘。刚加载的硬盘没有数据时,可以执行磁盘数据均衡命令。(Hadoop3.x新特性) plan后面带的节点的名字必须是已经存在的,并且是需要均衡的节点。 如果节点不存在,会报如下错误: 如果节点只有一个硬盘的话,不会创建均衡计划: (1)生成均衡计划 hdfs diskbalancer -plan hadoop102 (2)执行均衡计划 hd

NameNode内存生产配置

Hadoop2.x 系列,配置 NameNode 内存 NameNode 内存默认 2000m ,如果服务器内存 4G , NameNode 内存可以配置 3g 。在 hadoop-env.sh 文件中配置如下。 HADOOP_NAMENODE_OPTS=-Xmx3072m Hadoop3.x 系列,配置 Nam

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件