问题描述
我想根据以下链接array of objects
中给出的解决方案创建通用函数例如,我的数组如下所示
ID TAGS
1 {"tags": [{"tag1": "a"},{"tag1": "b"},{"tag2":"123"},{"tag2":"345"}]}
2 {"tags": [{"tag1": "c"},{"tag1": "d"},{"tag2":"789"},{"tag2":"678"}]}
通过以上链接中提供的javascript UDF可以正常工作。但是,我想将其用作通用对象,例如通过将tag1和tag2的值作为输入参数传递来获取它们。请在下面的UDF中找到它,可以通过直接调用它们来获得tag1 / tag2的效果很好。
create or replace function extract_tags(a array)
returns array
language javascript
strict
as '
return A.map(function(d) {return d.tag1});
';
SELECT ID,EXTRACT_TAGS(PAYLOAD:tags) AS tags from t1; -- This will give the result for tag1.
我不想重新创建用于获取tag2值的相同函数。而是希望将KEY作为参数传递并获得所需的结果。非常感谢您提供任何帮助。.类似下面的内容..如果下面的代码不合适,对不起。.我是java和雪花的新手。
create or replace function extract_tags(a array,b varchar)
returns array
language javascript
strict
as '
return A.map(function(d) {return d.{B}}); //Calling the second parameter to get the appropriate values
';
SELECT ID,EXTRACT_TAGS(PAYLOAD:tags,'tag1') AS tags from t1; --To get the tag1 values
SELECT ID,'tag2') AS tags from t1; --Using the same function to get tag2 values
解决方法
在return A.map(function(d) {return d.{B}});
中,地图功能应改为return d[B]
。
(将@Pipetus答案复制到答案中,以便该问题可以找到答案的答案)