[英]Azure CosmosDB User Defined Function returns records equal to the total number of records in the table
I am just no understanding how user defined functions in CosmosDB works.我只是不了解 CosmosDB 中用户定义的函数是如何工作的。
Why is the my UDF in Cosmos DB returning results equal to the number of records in the table?为什么 Cosmos DB 中的我的 UDF 返回的结果等于表中的记录数?
My table has 4 records currently.我的表目前有 4 条记录。
Here are the records -以下是记录——
{
"users": [
{
"partitionKey": "user",
"userPhoneNumber": "14168000000",
"userDisplayName": "Test User 1"
},
{
"partitionKey": "user",
"userPhoneNumber": "18055678978",
"userDisplayName": "Test User 2"
},
{
"partitionKey": "user",
"userPhoneNumber": "17202228799",
"userDisplayName": "Test User 3"
},
{
"partitionKey": "user",
"userPhoneNumber": "17780265987",
"userDisplayName": "Test User 4"
}
]
}
Here is my UDF -这是我的 UDF -
function findUserByPhoneNumber(users, contactNumbers){
var result;
for (let i = 0; i < contactNumbers.length; i++) {
if (contactNumbers[i] == "14168000000") {
result = contactNumbers[i];
}
return result;
}
Here is my SQL -这是我的 SQL -
SELECT udf.findUserByPhoneNumber(c,["14168000000","17200000000"]) FROM c
And here is the result I am getting -这是我得到的结果 -
[
{
"$1": "14168000000"
},
{
"$1": "14168000000"
},
{
"$1": "14168000000"
},
{
"$1": "14168000000"
}
]
I am only expecting one record to be returned.我只希望返回一条记录。
The SELECT
statement in your query will never help you filter items in your query.查询中的
SELECT
语句永远不会帮助您过滤查询中的项目。 If you want to filter you should use WHERE
in your query.如果你想过滤你应该在你的查询中使用
WHERE
。 While you could use a UDF in a WHERE
statement that returns eg a boolean you should typically avoid it as the database can not use it indexes to efficiently retrieve your data and will have to use your UDF on every document to calculate if it should be retrieved.虽然您可以在返回例如 boolean 的
WHERE
语句中使用 UDF,但您通常应该避免使用它,因为数据库无法使用它索引来有效检索数据,并且必须在每个文档上使用 UDF 来计算是否应该检索它.
For your scenario the query could be:对于您的场景,查询可能是:
SELECT *
FROM c
WHERE ARRAY_CONTAINS(['14168000000', '17200000000'], c.userPhoneNumber)
The reason your UDF always returns 14168000000
is because you always use the array ['14168000000', '17200000000']
as input in your UDF and check if any of those values equals 14168000000
and return that.你的 UDF 总是返回
14168000000
的原因是因为你总是使用数组['14168000000', '17200000000']
作为你的 UDF 的输入并检查这些值中的任何一个是否等于14168000000
并返回它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.