繁体   English   中英

Azure CosmosDB 用户定义 Function 返回等于表中记录总数的记录

[英]Azure CosmosDB User Defined Function returns records equal to the total number of records in the table

我只是不了解 CosmosDB 中用户定义的函数是如何工作的。

为什么 Cosmos DB 中的我的 UDF 返回的结果等于表中的记录数?

我的表目前有 4 条记录。

以下是记录——

{
    "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"
        }
    ]
}

这是我的 UDF -

function findUserByPhoneNumber(users, contactNumbers){
    var result;
    for (let i = 0; i < contactNumbers.length; i++) {
        if (contactNumbers[i] == "14168000000") {
            result = contactNumbers[i];
        }
    return result;
}

这是我的 SQL -

SELECT udf.findUserByPhoneNumber(c,["14168000000","17200000000"]) FROM c

这是我得到的结果 -

[
    {
        "$1": "14168000000"
    },
    {
        "$1": "14168000000"
    },
    {
        "$1": "14168000000"
    },
    {
        "$1": "14168000000"
    }
]

我只希望返回一条记录。

查询中的SELECT语句永远不会帮助您过滤查询中的项目。 如果你想过滤你应该在你的查询中使用WHERE 虽然您可以在返回例如 boolean 的WHERE语句中使用 UDF,但您通常应该避免使用它,因为数据库无法使用它索引来有效检索数据,并且必须在每个文档上使用 UDF 来计算是否应该检索它.

对于您的场景,查询可能是:

SELECT * 
FROM c
WHERE ARRAY_CONTAINS(['14168000000', '17200000000'], c.userPhoneNumber)

你的 UDF 总是返回14168000000的原因是因为你总是使用数组['14168000000', '17200000000']作为你的 UDF 的输入并检查这些值中的任何一个是否等于14168000000并返回它。

暂无
暂无

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

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