gpt4 book ai didi

xpath - 在 Hive 中爆破一行 XML 数据

转载 作者:可可西里 更新时间:2023-11-01 14:14:07 24 4
gpt4 key购买 nike

我们将 XML 数据作为名为 XML 的单个字符串列加载到 Hadoop 中。我们正在尝试检索到数据级别,将其规范化或将其分解为单行以进行处理(你知道,就像一个表格!)已经尝试过分解函数,但没有得到我们想要的。

示例 XML

<Reports>
<Report ID="1">
<Locations>
<Location ID="20001">
<LocationName>Irvine Animal Shelter</LocationName>
</Location>
<Location ID="20002">
<LocationName>Irvine City Hall</LocationName>
</Location>
</Locations>
</Report>
<Report ID="2">
<Locations>
<Location ID="10001">
<LocationName>California Fish Grill</LocationName>
</Location>
<Location ID="10002">
<LocationName>Fukada</LocationName>
</Location>
</Locations>
</Report>
</Reports>

查询 1

我们正在查询更高级别的 Report.Id,然后是子项 (Locations/Location) 的 ID 和名称。下面基本上给出了所有可能组合的笛卡尔积(在这个例子中,8 行而不是我们希望的 4 行。)

SELECT xpath_int(xml, '/Reports/Report/@ID') AS id, location_id, location_name 
FROM xmlreports
LATERAL VIEW explode(xpath(xml, '/Reports/Report/Locations/Location/@ID')) myTable1 AS location_id
LATERAL VIEW explode(xpath(xml, '/Reports/Report/Locations/Location/LocationName/text()')) myTable2 AS location_name;

查询 2

试图组合成一个结构然后分解,但这会返回两行和两个数组。

SELECT id, loc.col1, loc.col2
FROM (
SELECT xpath_int(xml, '/Reports/Report/@ID') AS id,
array(struct(xpath(xml, '/Reports/Report/Locations/Location/@ID'), xpath(xml, '/Reports/Report/Locations/Location/LocationName/text()'))) As foo
FROM xmlreports) x
LATERAL VIEW explode(foo) exploded_table as loc;

结果

1   ["20001","20002"]       ["Irvine Animal Shelter","Irvine City Hall"]
2 ["10001","10002"] ["California Fish Grill","Irvine Spectrum"]

我们想要的是

1   "20001" "Irvine Animal Shelter"
1 "20002" "Irvine City Hall"
2 "10001" "California Fish Grill"
2 "10002" "Irvine Spectrum"

这似乎是一件很常见的事情,但找不到任何例子。非常感谢任何帮助。

最佳答案

我看到有两种方法可以解决这个问题。

  1. 创建自定义 UDF,它将解析一个 XML 元素并返回您需要的数组。在爆炸阵列之后。

  2. 使用子选择。

我使用子选择实现了解决方案 2。即使在使用子选择时,Hive 也“足够聪明”为此创建一个 map-reduce 作业,所以我认为您不会遇到性能问题。

SELECT 
l2.key,
l2.rid,
l2.location_id,
location_name
FROM (
SELECT
l1.key as key,
l1.rid as rid,
location_id as location_id,
l1.xml as xml
FROM (
SELECT key, xml, rid
FROM xmlreports
LATERAL VIEW explode(xpath(xml, '/Reports/Report/@ID')) rids as rid
) l1
LATERAL VIEW explode(xpath(l1.xml, concat('/Reports/Report[@ID = ',l1.rid, ']/Locations/Location/@ID'))) locids as location_id
) l2
LATERAL VIEW explode(xpath(l2.xml, concat('/Reports/Report[@ID = ',l2.rid, ']/Locations/Location[@ID = ', l2.location_id ,' ]/LocationName/text()'))) locnames as location_name;

在对您提供的 XML 文件运行此查询后,我得到了您正在搜索的结果

1   1   20001   Irvine Animal Shelter
1 1 20002 Irvine City Hall
1 2 10001 California Fish Grill
1 2 10002 Fukada

希望这能解决您的问题。

问候,恐龙

关于xpath - 在 Hive 中爆破一行 XML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15375031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com