You are on page 1of 4

Azure Cosmos DB Query Cheat Sheet

SQL + JavaScript SQL query Sample queries

Example: families collection


-- Find families by ID Comparison SELECT *
SELECT *
(range) FROM Families.children[0] c
FROM Families f
1
{ WHERE f.id = "AndersenFamily" operators WHERE c.grade >= 5
"id":"AndersenFamily",
"lastName":"Andersen",
"parents":[ [{ SELECT *
{ "id": "AndersenFamily", Logical FROM Families.children[0] c
"firstName":"Thomas" "lastName": "Andersen", operators WHERE c.grade >= 5 AND
}, … c.isRegistered = true
{ }]
"firstName":"Mary Kay"
} ORDER BY SELECT f.id, f.address.city
FROM Families f
], keyword
SQL + JSON
"children":[ ORDER BY f.address.city
{
"firstName":"Henriette Thaulow",
-- Find families where City equals State and return SELECT COUNT(1)
"gender":"female",
Name and City Aggregate FROM Families
"grade":5,
"pets":[ functions WHERE c.grade >= 5
{ SELECT {"Name":f.id, "City":f.address.city} AS Family
"givenName":"Fluffy" FROM Families f SELECT *
} WHERE f.address.city = f.address.state FROM Families
] IN keyword WHERE Families.address.state IN
}
[{ ("NY", "WA", "CA", "PA", "OH",
],
"address":{ "Family": { "OR", "MI", "WI")
"state":"WA", "Name": "WakefieldFamily",
"county":"King", "City": "NY" Ternary (?) SELECT (c.grade < 5)? "elementa-
"city":"seattle" } and ry": ((c.grade < 9)? "junior":
}, }] Coalesce (??) "high") AS gradeLevel
"creationDate":"2015-01-03T12:00Z", operators FROM Families.children[0] c
"isRegistered":true,
"location":{
"type":"Point",
SQL + JavaScript UDF
SELECT f["lastName"]
"coordinates":[ Escape/quoted FROM Families f
31.9, accessor WHERE f["id"] = "AndersenFamily"
-4.8
-- Register UDF for REGEX_MATCH with this code
]
} SELECT [f.address.city,
} function (input, pattern) { f.address.state]
return input.match(pattern) !== null; Object/Array AS CityState
} Creation FROM Families f
{
"id":"WakefieldFamily",
"parents":[
2 -- Use JavaScript
SELECT udf.REGEX_MATCH(Families.address.city, ".*eattle")
{ Value SELECT VALUE "Hello World"
"familyName":"Wakefield",
[ keyword
"givenName":"Robin"
}, {
{ "$1": true
"familyName":"Miller", }, SELECT
"givenName":"Ben" { f.id AS familyName,
c.givenName AS childGivenName,
} "$1": false Intra-
], } c.firstName AS childFirstName,
"children":[ ]
document p.givenName AS petName
{ JOINS FROM Families f
"familyName":"Merriam", JOIN c IN f.children
"givenName":"Jesse", JOIN p IN c.pets
"gender":"female",
"grade":1, Built-in functions
"pets":[
{ SELECT *
ABS, CEILING, EXP, FLOOR, LOG,
"givenName":"Goofy" Parameterized FROM Families f
LOG10, POWER, ROUND, SIGN, SQRT,
}, SQL WHERE f.lastName = @lastName AND
{ Mathematical SQUARE, TRUNC, ACOS, ASIN, ATAN, f.address.state = @addressState
"givenName":"Shadow" ATN2, COS, COT, DEGREES, PI,
} RADIANS, SIN, and TAN
] SELECT Families.id, Families.ad-
}, IS_ARRAY, IS_BOOL, IS_NULL,
dress.city
{ Type checking IS_NUMBER, IS_OBJECT, IS_STRING, String Built-in FROM Families
"familyName":"Miller", IS_DEFINED, and IS_PRIMITIVE functions WHERE STARTSWITH(Families.id,
"givenName":"Lisa",
"gender":"female", CONCAT, CONTAINS, ENDSWITH, INDEX_OF, "Wakefield")
"grade":8 LEFT, LENGTH, LOWER, LTRIM, REPLACE,
}
String
REPLICATE, REVERSE, RIGHT, RTRIM,
], SELECT Families.id
STARTSWITH, SUBSTRING, and UPPER
"address":{ Array Built-in FROM Families
"state":"NY", functions WHERE ARRAY_CONTAINS(Families.par-
"county":"Manhattan", Array ARRAY_CONCAT, ARRAY_CONTAINS,
ents, { givenName: "Robin",
ARRAY_LENGTH, and ARRAY_SLICE
"city":"NY" familyName: "Wakefield" })
}, ST_WITHIN, ST_DISTANCE, ST_INTERSECTS,
"creationDate":"2015-07-20T12:00Z", Geospatial ST_ISVALID, and ST_ISVALIDDETAILED
"isRegistered":false
} Math Built-in SELECT VALUE ABS(-4)
functions
Query interfaces Operators
SELECT IS_DEFINED(f.lastName),
Type Built-in
SQL, JavaScript integrated query, Arithmetic +, -, *, /, %
functions
IS_NUMBER(4)
Server-side MongoDB API
FROM Families f

Bitwise |, &, ^, <,>>, >>> (zero-fill right


shift)
Client-side .NET (LINQ), Java, JavaScript, Node.js,
TOP SELECT TOP 100 *
Logical AND, OR, NOT keyword FROM Families f
Python, REST API

Comparison =, !=, >, >=, <, <=, <>, ??


SELECT *
Aggregates functions Geospatial FROM Families f
String || (concatenate) functions WHERE ST_Distance(f.location,
{"type":"Point", "coordi-
nates":[31.9, -4.8]}) < 30000
Mathematical COUNT, MIN, MAX, SUM, and AVG Ternary ?

© 2018 Microsoft Corporation. All rights reserved. www.cosmosdb.com | Tweet: @AzureCosmosDB, #cosmosdb
Azure Cosmos DB Query Cheat Sheet
MongoDB API
Example: families collection Find a document by property

Import to MongoDB API {


"id":"AndersenFamily",
1 > db.families.findOne(
{lastName: "Wakefield"},
"lastName":"Andersen", {id: true, _id: false} )
Example: "parents":[
Database : your-db {
{"id" : "AndersenFamily"}
"firstName":"Thomas"
Collection : your-coll
},
File : C:\users\you\Documents\*.json {
"firstName":"Mary Kay" Insert a document
}
In your terminal:
], > db.families.insert(
mongoimport.exe "children":[
{ {id: "SmithFamily"} )
-host your-account.documents.azure.com -port 10250
"firstName":"Henriette Thaulow",
-u your-account "gender":"female", WriteResult( {"nInserted" : 1} )
-p a1b2c3d4e5== --ssl "grade":5,
"pets":[
--sslAllowInvalidCertificates
{
--db your-db --collection your-coll --file "givenName":"Fluffy" Update a document
C:\Users\you\Documents\*.json }
]
> db.families.update(
}
{id: "SmithFamily"},
Restore to MongoDB API
],
"familySize":3, {id: "SmithFamily", city: "New York"} )
"address":{
Example: "state":"WA", WriteResult(
Mongo dump: ./dumps/dump-2016-08-31 "county":"King",
{"nMatched" : 1},
"city":"seattle"
}, {"nUpserted": 0},
In your terminal: "creationDate":"2015-01-03T12:00Z", {"nModified": 1} )
"isRegistered":true,
mongorestore.exe "location":{

Update a document property


-host your-account.documents.azure.com -port 10250 "type":"Point",
-u your-account "coordinates":[
31.9,
-p a1b2c3d4e5== --ssl -4.8 > db.families.update(
--sslAllowInvalidCertificates ] {id: "SmithFamily"},
./dumps/dump-2016-08-31 }
} {$set: { city: "Seattle"}} )
)
Find request charge
WriteResult(
First, run the operation you want to find the request charge {"nMatched" : 1},
for in the Mongo Shell. {
"id":"WakefieldFamily",
2 {"nUpserted": 0},
{"nModified": 1} )
"parents":[
Then run:
{
"familyName":"Wakefield",
Remove a document
> db.runCommand(
"givenName":"Robin"
{getLastRequestStatistics: 1} )
},
{ > db.families.remove(
"familyName":"Miller",
{"_t" : "GetRequestStatisticsResponse", {id: "SmithFamily"} )
"givenName":"Ben"
"ok": 1, }
], WriteResult( {"nRemoved" : 1} )
"CommandName": "OP_QUERY",
"children":[
"RequestCharge": 2.48, {
"RequestDurationInMilliSeconds": "familyName":"Merriam",
"givenName":"Jesse",
Aggregate queries
4.0048}
"gender":"female", Join family and cars collections to families with the
"grade":1,
"pets":[ cars they own.
Example: cars collection {
> db.families.aggregate([
"givenName":"Goofy"
{ }, {
"make":"Honda", { $lookup:
"owner":"WakefieldFamily", "givenName":"Shadow"
}, } {
{ ] from: "cars",
"make":"Toyata", }, localField: "id",
"owner":"AndersenFamily", {
}, "familyName":"Miller", foreignField: "owner",
"givenName":"Lisa", as: "familycars"
"gender":"female", }
"grade":8
} }
], ])
"familySize":4,
"address":{

Get the number of families with children


"state":"NY",
"county":"Manhattan",
"city":"NY"
}, > db.families.aggregate([
"creationDate":"2015-07-20T12:00Z", { $lookup: { "children": {$exists: true}} },
"isRegistered":false
{ $group: { _id: null, totoal: {$sum: 1}} },
}
] );

© 2018 Microsoft Corporation. All rights reserved. www.cosmosdb.com | Tweet: @AzureCosmosDB, #cosmosdb
Azure Cosmos DB Query Cheat Sheet

Table API
Query entities
Initialize a CloudTableClient Method GET
Preflight table request https://myaccount.table.cosmosdb.azure.com/mytable(Partitio-
TableconnectionPolicy connectionPolicy =
Key='<partition-key>',RowKey='<row-key>')?$select=<comma
new TableConnectionPolicy() MHTTP Verb OPTIONS
{ -separated-property-names>
UsedirectMode = true, http://myaccount.table.cosmosdb.azure.com/<table-resource>
https://myaccount.table.core.windows.net/mytable()?$fil-
UseTcpProtocol = true,
EnableEndpointdiscovery = true Request Headers ter=<query-expression>&$select=<comma-separated-propert
}; - Origin y-names>
CloudStorageAccount storageAccount =
- Access-Control-Request-Method
CloudStorageAccount.Parse(connectionString);
- Access-Control-Request-Headers Request Headers
CloudTableClient = storageAccount.CreateCloudTable
Client(connectionPolicy, Microsoft.Azure.Cosmos- - Authorization - Date or x-ms-date
DB.ConsistencyLevel.BoundedStaleness); - x-ms-version - Accept
Get table service stats - x-ms-client-request-id
Create a table Method GET
https://myaccount.table.cosmosdb.azure.com/?restype=ser-
Insert entity
CloudTable table = tableClient.GetTableRefer- vice&comp=stats
ence(" "); Method POST
table.CreateIfNotExists(); Request Headers https://myaccount.table.cosmosdb.azure.com/mytable
- Authorization - Date or x-ms-date
Request Headers
Create table entity - x-ms-version - x-ms-client-request-id
- Authorization - Date or x-ms-date
CustomerEntity item = new CustomerEntity() - x-ms-version - Content-Type
{ Query table
- Content-Length - Accept
PartitionKey = Guid.NewGuid().ToString(), Method GET - Prefer - x-ms-client-request-id
RowKey = Guid.NewGuid().ToString(),
Email = $" ", https://myaccount.table.cosmosdb.azure.com/Tables
PhoneNumber = "",
Bio = GetRandomString(1000) Request Headers Insert or Merge entity / Insert or Replace entity
}; - Authorization - Date or x-ms-date
Method MERGE / Method PUT
- x-ms-version - x-ms-client-request-id
https://myaccount.table.cosmosdb.azure.com/mytable(Partition-
Insert operation Key='myPartitionKey',RowKey='myRowKey')
Create table
TableOperation = TableOperation.Insert(item); Request Headers
table.Execute(insertOperation); Method POST
- Authorization - Date or x-ms-date
https://myaccount.table.cosmosdb.azure.com/Tables
- x-ms-version - Content-Type
Retrieve operation Request Headers - Content-Length - x-ms-client-request-id

TableOperation retrieveOperation = TableOpera- - Authorization - Date or x-ms-date


tion.Retrieve<CustomerEntity>(item.PartitionKey, - x-ms-version - Content-Type Update entity
item.RowKey); - Accept - Prefer
table.Execute(retrieveOperation); Method PUT
- Content-Length - x-ms-client-request-id
https://myaccount.table.cosmosdb.azure.com/mytable(Partition-
Key='myPartitionKey',RowKey='myRowKey')
Query Delete table
Request Headers
TableQuery<CustomerEntity> rangeQuery = new Method DELETE - Authorization - Date or x-ms-date
TableQuery<CustomerEntity>().Where( https://myaccount.table.cosmosdb.azure.com/Tables('mytable') - x-ms-version - Content-Type
TableQuery.GenerateFilterCondition("PartitionKey”, Request Headers - Content-Length - If-Match
QueryComparisons.Equal, item.PartitionKey);
- Authorization - Date or x-ms-date - x-ms-client-request-id
- x-ms-version - x-ms-client-request-id
Table service REST API Merge entity
Set table service properties Get table ACL
Method MERGE
Method GET/HEAD https://myaccount.table.cosmosdb.azure.com/mytable(Partition-
Method PUT
https://myaccount.table.cosmosdb.azure.com/mytable?com- Key='myPartitionKey',RowKey='myRowKey')
https://myaccount.table.cosmosdb.azure.com/?res-
type=service&comp=properties Request Headers Request Headers
Request Headers - Authorization - Date or x-ms-date - Authorization - Date or x-ms-date
- Authorization - Date or x-ms-date - x-ms-version - x-ms-client-request-id - x-ms-version - Content-Type
- x-ms-version - x-ms-client-request-id - Content-Length - If-Match
- x-ms-client-request-id
Set table ACL
Get table service properties Method PUT
https://myaccount.table.cosmosdb.azure.com/mytable?comp=acl Delete entity
Method GET
https://myaccount.table.cosmosdb.azure.com/?restype=ser- Request Headers Method DELETE
vice&comp=properties - Authorization - Date or x-ms-date https://myaccount.table.cosmosdb.azure.com/mytable(Partition-

- x-ms-version - x-ms-client-request-id Key='myPartitionKey',RowKey='myRowKey')


Request Headers
- Authorization - Date or x-ms-date Request Headers
- x-ms-version - x-ms-client-request-id - Authorization - Date or x-ms-date
- x-ms-version - If-Match
- x-ms-client-request-id

© 2018 Microsoft Corporation. All rights reserved. www.cosmosdb.com | Tweet: @AzureCosmosDB, #cosmosdb
Azure Cosmos DB Query Cheat Sheet
Gremlin / Graph API
Anatomy of Tinkerpop Graph Select a vertex by property Count number of vertices

Start with the g.v() selector, and filter using the Use the .count() step at the end of a traversal.
.has ("key", "value") with any exisiting property
Vertex
as the key. Example:
id: 3
<- Input
label: “ingredient”
name: “cheese” Example: :> g.V().out().hasLabel(“ingredient")

:> g.V().has("name", "sandwich") .count()

Output ->

Edge Add an edge between two vertices


:> [2]

Edge id: 5
id: 4 label: “has” After selecting a vertex, use the .addE("label") step,
label: “has” Vertex followed by any number of properties, then use the Return the path of a traversal
id: 1 .to(g.V() …) to select another vertex to point it to.
Use the .path() step at the end of a traversal,
label: “food” use the .by() step to return values for a
name: “sandwich” Example:
specific field.
Vertex isDelicious: true :> g.V().has("name", "sandwich")
id: 2 .addE("has")
label: “ingredient”
Example:
.property("amount", 2)
name: “bread” .to(g.V().has("name", "bread")) <- Input
:> g.V().out()

:> g.V().has("name", "sandwich") .path()

Graph object types .addE("has") .by("name")

.property("amount", 1)
Vertices (also known as nodes): Represent objects. They have .to(g.V().has("name", “cheese")) Output ->
unique ID, a unique label and one ore more properties. :> ["sandwich", "bread"], ["sandwich", “cheese"]
Edges: Represent relationships between objects (vertices). They
have unique Id, a unique label and one or more properties. Traverse a graph

After selecting a vertex, use the .out("label") step Select a specific element from a traversal
Graph object attributes to select all adjacent vertices that are connected with
Use the .as() step to name an object, and the
edges that have a specific label.
.select() step to return it at the end of a
ID: A property that uniquely identifies each element (vertex or
traversal. After that, you can use the .by() step to
edge) of a graph. Example:
get their values.
Labels: A unique string element that can be used to identify <- Input
types of objects (vertices or edges). This is a required field for :> g.V().has("name", "sandwich")
any grapph object. .out("has") Example:
Property: A key-value pair that can contain strings, boolean or .properties("name") <- Input
number values. :> g.V().outE().as("e").inV()
Output -> .select("e")
:> [cheese, bread] .by("amount")
Gremlin language primer
Output ->
Try this queries with the Gremlin console or the Data
:> [2, 1]
Explorer on Azure Portal. Loop a traversal

Use the .repeat(out("label")) step, followed by


Traversal variable .until() with a condition.
Drop a vertex or edge
Every query starts with g, the variable that represents
Example: After selecting a vertex or edge, append the
the graph traversal object. For example, this query will
<- Input .drop() step at the end.
get all the vertices in a graph:
:> g.V().has("name", "sandwich")
:> g.V() .repeat(out("has")) Example:
.until(hasLabel("ingredient")) :> g.V().has("name", "cheese").drop()
.path().by("name")
Add the vertices
Output ->
Use the .addV("label") step, followed by any number :> [sandwich, bread], [sandwich, cheese], Drop an entire graph
of calls to the .property("key", "value") step.
This command will drop all vertices and edges:
You can also use the .times() step and provide a
Example: number of times it should be repeated: :> g.V().drop()
:> g.addV("food")
.property("name", "sandwich") Example:
.property("isDelicious", true) <- Input
:> g.V().has("name", "sandwich")
:> g.addV("ingredient") .repeat(out("has"))
.property("name", "cheese") .times(1)
.path().by("name")
:> g.addV("ingredient") Output ->
.property("name", “bread") :> [sandwich, bread], [sandwich, cheese]

© 2018 Microsoft Corporation. All rights reserved. www.cosmosdb.com | Tweet: @AzureCosmosDB, #cosmosdb

You might also like