sql—在配置单元中正确使用结构

jobtbby3  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(635)

我想使用一个包含字符串和数组的结构。字符串表示服务的名称,而数组列出执行该服务的公司ID。
我知道我可以创建并插入结构外观,以便:

  1. CREATE TABLE struct_test
  2. (
  3. property_id INT,
  4. service STRUCT<
  5. type: STRING
  6. ,provider: ARRAY<INT>
  7. >
  8. );
  9. INSERT INTO TABLE struct_test
  10. SELECT 989, NAMED_STRUCT('type','Cleaning','provider', ARRAY(587, 887)) AS address
  11. FROM tmp LIMIT 1;

这给了我以下信息:

  1. >{"type":"Cleaning","provider":[587,887]}

但是,我想说明同一属性上的多个服务类型。我的电脑里怎么会有不止一种类型 service 结构?
理想情况下,我希望实现以下类似的目标:
{“type”:“cleaning”,“provider”:[587887]},{“type”:“pricing”,“provider”:[932]},{“type”:“security”,“provider”:[187577946]}
通过这种方式,我可以在列中存储多个服务以及提供该服务的提供者。这个模型可以用struct实现吗?

czfnxgou

czfnxgou1#

这可以通过 array<struct<type: STRING, provider: ARRAY<INT>>> 创建表:

  1. CREATE TABLE struct_test
  2. (
  3. property_id INT,
  4. service array<STRUCT<
  5. type: STRING
  6. ,provider: ARRAY<INT>
  7. >>
  8. );

插入数据:

  1. with
  2. test_data as(
  3. SELECT 989 property_id, array(NAMED_STRUCT('type','Cleaning','provider', ARRAY(587, 887)),
  4. NAMED_STRUCT('type','Pricing','provider', ARRAY(932))
  5. ) as service
  6. )
  7. INSERT INTO TABLE struct_test
  8. select * from test_data;

检查数据:

  1. select t.property_id, t.service from struct_test t;

结果:

  1. OK
  2. property_id service
  3. 989 [{"type":"Cleaning","provider":[587,887]},{"type":"Pricing","provider":[932]}]
  4. Time taken: 0.064 seconds, Fetched: 1 row(s)

如果要在select中收集结构数组,而不是硬编码的值,请参见以下答案:https://stackoverflow.com/a/48175749/2700344
对于如此复杂的数据类型,您肯定需要brickhouse库

展开查看全部

相关问题