Azure Cosmos DB 中的 JavaScript 查询 APIJavaScript query API in Azure Cosmos DB

除了使用 Azure Cosmos DB 中的 SQL API 发出查询外,Cosmos DB 服务器端 SDK 还提供了一个 JavaScript 接口,用于在 Cosmos DB 存储过程和触发器中执行优化查询。In addition to issuing queries using the SQL API in Azure Cosmos DB, the Cosmos DB server-side SDK provides a JavaScript interface for performing optimized queries in Cosmos DB Stored Procedures and Triggers. 你不需要了解 SQL 语言便可使用此 JavaScript 接口。You don't have to be aware of the SQL language to use this JavaScript interface. JavaScript 查询 API 允许使用与 ECMAScript5 的数组内置项类似的语法以及 Lodash 之类的热门 JavaScript 库,通过将谓词函数传递到函数调用序列中以编程方式生成查询。The JavaScript query API allows you to programmatically build queries by passing predicate functions into sequence of function calls, with a syntax familiar to ECMAScript5's array built-ins and popular JavaScript libraries like Lodash. 查询将由 JavaScript 运行时进行分析并使用 Azure Cosmos DB 索引高效执行。Queries are parsed by the JavaScript runtime and efficiently executed using Azure Cosmos DB indices.

支持的 JavaScript 函数Supported JavaScript functions

FunctionFunction 说明Description
chain() ... .value([callback] [, options]) 发起一个必须用 value() 终止的连锁调用。Starts a chained call that must be terminated with value().
filter(predicateFunction [, options] [, callback]) 使用返回 true/false 的谓词函数对输入进行筛选,以便将输入文档筛选出或筛选到结果集。Filters the input using a predicate function that returns true/false in order to filter in/out input documents into the resulting set. 此函数与 SQL 中的 WHERE 子句行为相似。This function behaves similar to a WHERE clause in SQL.
flatten([isShallow] [, options] [, callback]) 将每个输入项合且并平展到单个数组。Combines and flattens arrays from each input item into a single array. 此函数与 LINQ 中的 SelectMany 行为相似。This function behaves similar to SelectMany in LINQ.
map(transformationFunction [, options] [, callback]) 应用给定一个转换函数的投影,该函数将每个输入项映射到 JavaScript 对象或值。Applies a projection given a transformation function that maps each input item to a JavaScript object or value. 此函数与 SQL 中的 SELECT 子句行为相似。This function behaves similar to a SELECT clause in SQL.
pluck([propertyName] [, options] [, callback]) 此函数是特定映射的快捷方式,该映射用于从每个输入项提取单个属性的值。This function is a shortcut for a map that extracts the value of a single property from each input item.
sortBy([predicate] [, options] [, callback]) 通过使用给定的谓词在输入文档流中按升序方式对文档进行排序来生成新的一组文档。Produces a new set of documents by sorting the documents in the input document stream in ascending order by using the given predicate. 此函数与 SQL 中的 ORDER BY 子句行为相似。This function behaves similar to an ORDER BY clause in SQL.
sortByDescending([predicate] [, options] [, callback]) 通过使用给定的谓词在输入文档流中按降序方式对文档进行排序来生成新的一组文档。Produces a new set of documents by sorting the documents in the input document stream in descending order using the given predicate. 此函数与 SQL 中的 ORDER BY x DESC 子句行为相似。This function behaves similar to an ORDER BY x DESC clause in SQL.
unwind(collectionSelector, [resultSelector], [options], [callback]) 执行与内层数组的自联接,并将来自双方的结果作为元组添加到结果投影。Performs a self-join with inner array and adds results from both sides as tuples to the result projection. 例如,将 person 文档与 person.pets 进行联接将生成 [person, pet] 元组。For instance, joining a person document with person.pets would produce [person, pet] tuples. 这类似于 .NET LINK 中的 SelectMany。This is similar to SelectMany in .NET LINK.

当其中包含谓词和/或选择器函数时,以下 JavaScript 构造将自动优化以在 Azure Cosmos DB 索引上直接运行:When included inside predicate and/or selector functions, the following JavaScript constructs get automatically optimized to run directly on Azure Cosmos DB indices:

  • 简单运算符:= + - * / % | ^ & == != === !=== < > <= >= || && << >> >>>! ~Simple operators: = + - * / % | ^ & == != === !=== < > <= >= || && << >> >>>! ~
  • 文本(包括对象文本):{}Literals, including the object literal: {}
  • var, returnvar, return

以下 JavaScript 构造不会针对 Azure Cosmos DB 索引进行优化:The following JavaScript constructs do not get optimized for Azure Cosmos DB indices:

  • 控制流(例如,if、for、while)Control flow (for example, if, for, while)
  • 函数调用Function calls

有关详细信息,请参阅 Cosmos DB 服务器端 JavaScript 文档For more information, see the Cosmos DB Server Side JavaScript Documentation.

SQL 到 JavaScript 备忘单SQL to JavaScript cheat sheet

下表表示各种不同的 SQL 查询和对应的 JavaScript 查询。The following table presents various SQL queries and the corresponding JavaScript queries. 与 SQL 查询一样,属性(例如 item.id)区分大小写。As with SQL queries, properties (for example, item.id) are case-sensitive.

备注

使用 JavaScript 查询 API 时,__(双下划线)是 getContext().getCollection() 的别名。__ (double-underscore) is an alias to getContext().getCollection() when using the JavaScript query API.

SQLSQL JavaScript 查询 APIJavaScript Query API 说明Description
SELECT *SELECT *
FROM docsFROM docs
.map(function(doc) {.map(function(doc) {
    return doc;    return doc;
});});
结果为所有文档(使用延续令牌分页)保持原样。Results in all documents (paginated with continuation token) as is.
SELECTSELECT
   docs.id,   docs.id,
   docs.message AS msg,   docs.message AS msg,
   docs.actions   docs.actions
FROM docsFROM docs
.map(function(doc) {.map(function(doc) {
    return {    return {
        id: doc.id,        id: doc.id,
        msg: doc.message,        msg: doc.message,
        actions:doc.actions        actions:doc.actions
    };    };
});});
从所有文档投影 ID、消息(别名为 msg)和操作。Projects the id, message (aliased to msg), and action from all documents.
SELECT *SELECT *
FROM docsFROM docs
WHEREWHERE
   docs.id="X998_Y998"   docs.id="X998_Y998"
.filter(function(doc) {.filter(function(doc) {
    return doc.id ==="X998_Y998";    return doc.id ==="X998_Y998";
});});
查询具有此谓词的文档:id = "X998_Y998"。Queries for documents with the predicate: id = "X998_Y998".
SELECT *SELECT *
FROM docsFROM docs
WHEREWHERE
   ARRAY_CONTAINS(docs.Tags, 123)   ARRAY_CONTAINS(docs.Tags, 123)
.filter(function(x) {.filter(function(x) {
    return x.Tags && x.Tags.indexOf(123) > -1;    return x.Tags && x.Tags.indexOf(123) > -1;
});});
查询具有 Tags 属性且 Tags 为一个包含值 123 的数组的文档。Queries for documents that have a Tags property and Tags is an array containing the value 123.
SELECTSELECT
   docs.id,   docs.id,
   docs.message AS msg   docs.message AS msg
FROM docsFROM docs
WHEREWHERE
   docs.id="X998_Y998"   docs.id="X998_Y998"
.chain().chain()
    .filter(function(doc) {    .filter(function(doc) {
        return doc.id ==="X998_Y998";        return doc.id ==="X998_Y998";
    })    })
    .map(function(doc) {    .map(function(doc) {
       return {       return {
            id: doc.id,            id: doc.id,
            msg: doc.message            msg: doc.message
       };       };
    })    })
.value();.value();
查询具有谓词 id = "X998_Y998" 的文档,并投影 ID 和消息(别名为 msg)。Queries for documents with a predicate, id = "X998_Y998", and then projects the id and message (aliased to msg).
SELECT VALUE tagSELECT VALUE tag
FROM docsFROM docs
JOIN tag IN docs.TagsJOIN tag IN docs.Tags
ORDER BY docs._tsORDER BY docs._ts
.chain().chain()
    .filter(function(doc) {    .filter(function(doc) {
        return doc.Tags && Array.isArray(doc.Tags);        return doc.Tags && Array.isArray(doc.Tags);
    })    })
    .sortBy(function(doc) {    .sortBy(function(doc) {
        return doc._ts;        return doc._ts;
    })    })
    .pluck("Tags")    .pluck("Tags")
    .flatten()    .flatten()
    .value()    .value()
筛选具有数组属性 Tags 的文档,按 _ts 时间戳系统属性对结果文档进行排序,并投影并平展 Tags 数组。Filters for documents that have an array property, Tags, and sorts the resulting documents by the _ts timestamp system property, and then projects + flattens the Tags array.

后续步骤Next steps

详细了解概念以及如何在 Azure Cosmos DB 中编写并使用存储过程、触发器和用户定义的函数:Learn more concepts and how-to write and use stored procedures, triggers, and user-defined functions in Azure Cosmos DB: