如何筛选 属性 的值包含在数组 X 中的结果
how to filter for results for which a property has a value contained in array X
假设我有一个值 [x,y,z]
的动态数组 A。
我想要 return 所有 属性 P 具有 A 中存在的值的结果。
我可以编写一些递归过滤器,为 A 中的每个值连接“或”,但它非常笨重。
还有其他开箱即用的方法吗?
您可以结合使用 filter
命令和 reduce
and contains
命令来完成此操作。
例子
假设您有以下文件:
{
"id": "41e352d0-f543-4731-b427-6e16a2f6fb92" ,
"property": [ 1, 2, 3 ]
}, {
"id": "a4030671-7ad9-4ab9-a21f-f77cba9bfb2a" ,
"property": [ 5, 6, 7 ]
}, {
"id": "b0694948-1fd7-4293-9e11-9e5c3327933e" ,
"property": [ 2, 3, 4 ]
}, {
"id": "4993b81b-912d-4bf7-b7e8-e46c7c825793" ,
"property": [ "b" ,"c" ]
}, {
"id": "ce441f1e-c7e9-4a7f-9654-7b91579029be" ,
"property": [ "a" , "b" , "c" ]
}
从这些序列中,您想要获得在 property
属性 中包含 "a"
或 1
的所有文档。您可以使用 reduce
.
编写 returns 链式 contains
语句的查询
r.table('30510212')
// Filter documents
.filter(function (row) {
// Array of properties you want to filter for
return r.expr([ 1, 'a' ])
// Insert `false` as the first value in the array
// in order to make it the first value in the reduce's left
.insertAt(0, false)
// Chain up the `contains` statement
.reduce(function (left, right) {
return left.or(row('property').contains(right));
});
})
更新:更好的方法
实际上,您可以使用 2 contains
来执行相同的查询。这更短,可能更容易理解。
r.table('30510212')
.filter(function (row) {
return row('property').contains(function (property) {
return r.expr([ 1, 'a' ]).contains(property);
})
})
假设我有一个值 [x,y,z]
的动态数组 A。
我想要 return 所有 属性 P 具有 A 中存在的值的结果。
我可以编写一些递归过滤器,为 A 中的每个值连接“或”,但它非常笨重。
还有其他开箱即用的方法吗?
您可以结合使用 filter
命令和 reduce
and contains
命令来完成此操作。
例子
假设您有以下文件:
{
"id": "41e352d0-f543-4731-b427-6e16a2f6fb92" ,
"property": [ 1, 2, 3 ]
}, {
"id": "a4030671-7ad9-4ab9-a21f-f77cba9bfb2a" ,
"property": [ 5, 6, 7 ]
}, {
"id": "b0694948-1fd7-4293-9e11-9e5c3327933e" ,
"property": [ 2, 3, 4 ]
}, {
"id": "4993b81b-912d-4bf7-b7e8-e46c7c825793" ,
"property": [ "b" ,"c" ]
}, {
"id": "ce441f1e-c7e9-4a7f-9654-7b91579029be" ,
"property": [ "a" , "b" , "c" ]
}
从这些序列中,您想要获得在 property
属性 中包含 "a"
或 1
的所有文档。您可以使用 reduce
.
contains
语句的查询
r.table('30510212')
// Filter documents
.filter(function (row) {
// Array of properties you want to filter for
return r.expr([ 1, 'a' ])
// Insert `false` as the first value in the array
// in order to make it the first value in the reduce's left
.insertAt(0, false)
// Chain up the `contains` statement
.reduce(function (left, right) {
return left.or(row('property').contains(right));
});
})
更新:更好的方法
实际上,您可以使用 2 contains
来执行相同的查询。这更短,可能更容易理解。
r.table('30510212')
.filter(function (row) {
return row('property').contains(function (property) {
return r.expr([ 1, 'a' ]).contains(property);
})
})