简体   繁体   English

将 MongoDB 查询转换为 Snowflake

[英]Convert MongoDB query to Snowflake

I'm working on a migration project (MongoDB to Snowflake) and trying to convert one of the mongo queries to Snowflake, we have a use case to fetch records if all the elements from an array matched based on the given parameters.我正在处理一个迁移项目(MongoDB 到 Snowflake)并尝试将其中一个 mongo 查询转换为 Snowflake,如果数组中的所有元素根据给定的参数匹配,我们有一个用例来获取记录。

Mongo DB Function: $all Mongo 数据库函数:$all
The $all operator selects the documents where the value of a field is an array that contains all the specified elements. $all 运算符选择字段值是包含所有指定元素的数组的文档。

Mongo Query:蒙戈查询:

db.collection('collection_name').find({
  'code': { '$in': [ 'C0001' ] },
  'months': { '$all': [ 6, 7, 8, 9 ] } --> 6,7,8,9 given parameters
});


Table Structure in snowflake:
column name       datatype
code               varchar(50)
id                 int
months             ARRAY
weeks              ARRAY

Could you provide some suggestions on how to write this query in Snowflake?您能否就如何在 Snowflake 中编写此查询提供一些建议? Any recommendations would be helpful.任何建议都会有所帮助。

You can use ARRAY_SIZE and ARRAY_INTERSECTION to test it:您可以使用 ARRAY_SIZE 和 ARRAY_INTERSECTION 来测试它:

Here is sample table:这是示例表:

create or replace table test ( code varchar, months array );

insert into test select 'C0002', array_construct( 1, 2, 5,8,6,3)
union all select 'C0001', array_construct( 1,2,3 ) 
union all select 'C0002', array_construct( 2, 12, 3,7,9) 
union all select 'C0001', array_construct( 7,8,9,3, 2) ;

Here is query to test:这是要测试的查询:

select * from test where code in ('C0001','C0002')
and ARRAY_SIZE( ARRAY_INTERSECTION(  months, array_construct( 3, 2 ))) = 2;

So I find the intersection of two arrays, and check the number of items.所以我找到了两个数组的交集,并检查项目的数量。 If you want to look for 3 items, you should set 3 (and it goes like this):如果要查找 3 个项目,则应设置 3(如下所示):

select * from test where code in ('C0001','C0002')
and ARRAY_SIZE( ARRAY_INTERSECTION(  months, array_construct( 3, 2, 7 ))) = 3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM