当对象包含嵌套对象时,使用Spark SQL执行sql查询抛出scala.MatchError异常

当使用Spark SQL处理包含嵌套对象的数据时,执行SQL查询可能会遇到scala.MatchError异常。文章介绍了问题出现的原因,并提供了解决方案:一是通过编程指定Schema创建DataFrame,二是创建自定义的UserDefinedType(UDT)并注册。
摘要由CSDN通过智能技术生成
1. 运行环境

本文使用Spark SQL 2.1.0版本

2. 使用代码

例如有个对象,除了包含简单的基本数据String,int之外还包含一个Location对象,就是所说的嵌套对象:

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 1L;
	private String name;
	private int age;
	private Location location;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Location getLocation() {
		return location;
	}

	public void setLocation(Location location) {
		this.location = location;
	}

}

public class Location implements Serializable {

	private static final long serialVersionUID = 1L;
	private String city;
	private String country;

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

}

Spark SQL代码:

// 初始化 spark session
SparkSession spark = SparkSession
		.builder()
		.appName("Java Spark SQL Schema test")
		.master("local[*]")
		.getOrCreate();

// 创建Person的JavaRDD
JavaRDD<Person> peopleRDD = spark
		.read()
		.textFile("examples/src/main/resources/people.txt")
		.javaRDD().map(line -> {
			String[] parts = line.split(",");
			Person person = new Person();
			person.setName(parts[0]);
			person.setAge(Integer.parseInt(parts[1].trim()));
			Location location = new Location();
			location.setCity(parts[2
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值