0% found this document useful (0 votes)
232 views2 pages

Azure Cosmos DB 2 Cheat Sheet v4 PDF

Uploaded by

RonaldMartinez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
232 views2 pages

Azure Cosmos DB 2 Cheat Sheet v4 PDF

Uploaded by

RonaldMartinez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Azure Cosmos DB Query Cheat Sheet

SQL + JavaScript MongoDB API


Example: families collection SQL query Sample queries Import to MongoDB API Example: families collection Find a document by property
1 1
{
> db.families.findOne(
"id":"AndersenFamily", -- Find families by ID Comparison SELECT * Example: {
"lastName":"Andersen", SELECT * "id":"AndersenFamily", {lastName: "Wakefield"},
"parents":[ (range) FROM Families.children[0] c Database : your-db
FROM Families f "lastName":"Andersen",
{ WHERE f.id = "AndersenFamily" operators WHERE c.grade >= 5
Collection : your-coll
{id: true, _id: false} )
"parents":[
"firstName":"Thomas"
}, File : C:\users\you\Documents\*.json {
{"id" : "AndersenFamily"}
{ [{ SELECT * "firstName":"Thomas"
"firstName":"Mary Kay" "id": "AndersenFamily", Logical FROM Families.children[0] c },
} "lastName": "Andersen", operators WHERE c.grade >= 5 AND In your terminal: {
Insert a document
], … c.isRegistered = true "firstName":"Mary Kay"
"children":[ }] mongoimport.exe
}
{ -host your-account.documents.azure.com -port 10250 ],
"firstName":"Henriette Thaulow", ORDER BY SELECT f.id, f.address.city > db.families.insert(
FROM Families f "children":[
"gender":"female", keyword -u your-account
{id: "SmithFamily"} )
SQL + JSON
"grade":5, ORDER BY f.address.city {
-p a1b2c3d4e5== --ssl
"pets":[ "firstName":"Henriette Thaulow",
{ --sslAllowInvalidCertificates "gender":"female", WriteResult( {"nInserted" : 1} )
-- Find families where City equals State and return SELECT COUNT(1)
"givenName":"Fluffy"
Name and City Aggregate FROM Families --db your-db --collection your-coll --file "grade":5,
} functions WHERE c.grade >= 5 C:\Users\you\Documents\*.json
"pets":[
]
SELECT {"Name":f.id, "City":f.address.city} AS Family {
Update a document
}
], FROM Families f SELECT * "givenName":"Fluffy"
"address":{ WHERE f.address.city = f.address.state }
Restore to MongoDB API
FROM Families
"state":"WA", IN keyword WHERE Families.address.state IN ]
> db.families.update(
"county":"King", ("NY", "WA", "CA", "PA", "OH", }
"city":"seattle" [{ {id: "SmithFamily"},
}, "Family": { "OR", "MI", "WI") Example: ],
"Name": "WakefieldFamily", "familySize":3, {id: "SmithFamily", city: "New York"} )
"creationDate":"2015-01-03T12:00Z",
Ternary (?) Mongo dump: ./dumps/dump-2016-08-31
"isRegistered":true, "City": "NY" SELECT (c.grade < 5)? "elementa- "address":{
"location":{ } and ry": ((c.grade < 9)? "junior": "state":"WA", WriteResult(
"type":"Point", }] Coalesce (??) "high") AS gradeLevel In your terminal: "county":"King",
{"nMatched" : 1},
"coordinates":[ operators FROM Families.children[0] c "city":"seattle"
31.9, mongorestore.exe }, {"nUpserted": 0},
-4.8 "creationDate":"2015-01-03T12:00Z",
-host your-account.documents.azure.com -port 10250 {"nModified": 1} )
SQL + JavaScript UDF
] SELECT f["lastName"]
} Escape/quoted FROM Families f
"isRegistered":true,
-u your-account
} accessor WHERE f["id"] = "AndersenFamily" "location":{

Update a document property


-p a1b2c3d4e5== --ssl "type":"Point",
-- Register UDF for REGEX_MATCH with this code
--sslAllowInvalidCertificates "coordinates":[
{
2
SELECT [f.address.city, 31.9,
"id":"WakefieldFamily", function (input, pattern) { f.address.state] ./dumps/dump-2016-08-31
"parents":[ return input.match(pattern) !== null; Object/Array AS CityState
-4.8 > db.families.update(
{ } Creation FROM Families f
] {id: "SmithFamily"},
"familyName":"Wakefield", }
"givenName":"Robin" -- Use JavaScript Find request charge } {$set: { city: "Seattle"}} )
}, SELECT udf.REGEX_MATCH(Families.address.city, ".*eattle") )
{ Value SELECT VALUE "Hello World"
First, run the operation you want to find the request charge
"familyName":"Miller", [ keyword
"givenName":"Ben"
{ for in the Mongo Shell. WriteResult(
} {"nMatched" : 1},
], "$1": true
Then run:
2
"children":[ }, SELECT {"nUpserted": 0},
{
{ { f.id AS familyName,
c.givenName AS childGivenName, "id":"WakefieldFamily", {"nModified": 1} )
"familyName":"Merriam", "$1": false Intra- > db.runCommand(
"parents":[
"givenName":"Jesse", } c.firstName AS childFirstName,
"gender":"female", ]
document p.givenName AS petName
{getLastRequestStatistics: 1} ) {
JOINS "familyName":"Wakefield",
Remove a document
"grade":1, FROM Families f
"pets":[ JOIN c IN f.children "givenName":"Robin"
{ JOIN p IN c.pets {"_t" : "GetRequestStatisticsResponse", },

},
"givenName":"Goofy"
Built-in functions "ok": 1, { > db.families.remove(
"familyName":"Miller",
{ "CommandName": "OP_QUERY", {id: "SmithFamily"} )
"givenName":"Shadow" SELECT * "givenName":"Ben"
ABS, CEILING, EXP, FLOOR, LOG,
} Parameterized FROM Families f "RequestCharge": 2.48, }
LOG10, POWER, ROUND, SIGN, SQRT, WriteResult( {"nRemoved" : 1} )
] SQL WHERE f.lastName = @lastName AND ],
}, Mathematical SQUARE, TRUNC, ACOS, ASIN, ATAN, f.address.state = @addressState
"RequestDurationInMilliSeconds":
"children":[
{ ATN2, COS, COT, DEGREES, PI, 4.0048} {
"familyName":"Miller", RADIANS, SIN, and TAN
"givenName":"Lisa", SELECT Families.id, Families.ad-
"familyName":"Merriam",
"givenName":"Jesse",
Aggregate queries
"gender":"female", IS_ARRAY, IS_BOOL, IS_NULL,
dress.city
"grade":8 Type checking IS_NUMBER, IS_OBJECT, IS_STRING, String Built-in FROM Families Example: cars collection "gender":"female", Join family and cars collections to families with the
} IS_DEFINED, and IS_PRIMITIVE functions WHERE STARTSWITH(Families.id,
"grade":1,
], "pets":[ cars they own.
CONCAT, CONTAINS, ENDSWITH, INDEX_OF, "Wakefield") {
"address":{ {
LEFT, LENGTH, LOWER, LTRIM, REPLACE, "make":"Honda", > db.families.aggregate([
"state":"NY", String "owner":"WakefieldFamily", "givenName":"Goofy"
"county":"Manhattan", REPLICATE, REVERSE, RIGHT, RTRIM,
SELECT Families.id }, }, {
"city":"NY" STARTSWITH, SUBSTRING, and UPPER
}, Array Built-in FROM Families { { $lookup:
functions WHERE ARRAY_CONTAINS(Families.par- "givenName":"Shadow"
"creationDate":"2015-07-20T12:00Z", Array ARRAY_CONCAT, ARRAY_CONTAINS,
ents, { givenName: "Robin",
"make":"Toyata",
} {
"isRegistered":false ARRAY_LENGTH, and ARRAY_SLICE "owner":"AndersenFamily",
} familyName: "Wakefield" }) ] from: "cars",
},
ST_WITHIN, ST_DISTANCE, ST_INTERSECTS, },
Geospatial ST_ISVALID, and ST_ISVALIDDETAILED {
localField: "id",

Math Built-in SELECT VALUE ABS(-4) "familyName":"Miller", foreignField: "owner",


Query interfaces functions "givenName":"Lisa", as: "familycars"
Operators "gender":"female",
"grade":8
}
SQL, JavaScript integrated query, SELECT IS_DEFINED(f.lastName),
Server-side Type Built-in } }
MongoDB API IS_NUMBER(4)
Arithmetic +, -, *, /, %
functions FROM Families f ], ])
"familySize":4,
Client-side .NET (LINQ), Java, JavaScript, Node.js, Bitwise |, &, ^, <,>>, >>> (zero-fill right "address":{

Get the number of families with children


shift) "state":"NY",
Python, REST API
TOP SELECT TOP 100 *
"county":"Manhattan",
Logical AND, OR, NOT keyword FROM Families f
"city":"NY"
}, > db.families.aggregate([
Aggregates functions Comparison =, !=, >, >=, <, <=, <>, ??
SELECT *
"creationDate":"2015-07-20T12:00Z", { $lookup: { "children": {$exists: true}} },
"isRegistered":false
{ $group: { _id: null, totoal: {$sum: 1}} },
Geospatial FROM Families f }
] );
String || (concatenate) functions WHERE ST_Distance(f.location,
Mathematical COUNT, MIN, MAX, SUM, and AVG {"type":"Point", "coordi-
nates":[31.9, -4.8]}) < 30000
Ternary ?

© 2018 Microsoft Corporation. All rights reserved. Need help or have questions? Email us at [email protected] to talk to a Cosmos database engineer! www.cosmosdb.com | Tweet: @AzureCosmosDB, #cosmosdb
Azure Cosmos DB Query Cheat Sheet
Table API Gremlin / Graph API
Initialize a CloudTableClient Anatomy of Tinkerpop Graph Select a vertex by property Count number of vertices

Preflight table request Query entities Start with the g.v() selector, and filter using the Use the .count() step at the end of a traversal.
TableconnectionPolicy connectionPolicy =
.has ("key", "value") with any exisiting property
new TableConnectionPolicy() MHTTP Verb OPTIONS Method GET Vertex
{ as the key. Example:
UsedirectMode = true, http://myaccount.table.cosmosdb.azure.com/<table-resource> https://myaccount.table.cosmosdb.azure.com/mytable(Partitio- id: 3
<- Input
UseTcpProtocol = true, Key='<partition-key>',RowKey='<row-key>')?$select=<comma label: “ingredient”
EnableEndpointdiscovery = true Request Headers Example: :> g.V().out().hasLabel(“ingredient")
-separated-property-names> name: “cheese”
}; - Origin .count()
CloudStorageAccount storageAccount = https://myaccount.table.core.windows.net/mytable()?$fil- :> g.V().has("name", "sandwich")
- Access-Control-Request-Method
CloudStorageAccount.Parse(connectionString); ter=<query-expression>&$select=<comma-separated-propert
CloudTableClient = storageAccount.CreateCloudTable - Access-Control-Request-Headers Output ->
Client(connectionPolicy, Microsoft.Azure.Cosmos- y-names>
DB.ConsistencyLevel.BoundedStaleness); Edge Add an edge between two vertices
:> [2]
Request Headers Edge id: 5
Get table service stats
- Authorization - Date or x-ms-date id: 4 label: “has” After selecting a vertex, use the .addE("label") step,
Create a table Method GET
- x-ms-version - Accept label: “has” Vertex followed by any number of properties, then use the Return the path of a traversal
https://myaccount.table.cosmosdb.azure.com/?restype=ser- .to(g.V() …) to select another vertex to point it to.
CloudTable table = tableClient.GetTableRefer-
- x-ms-client-request-id id: 1 Use the .path() step at the end of a traversal,
vice&comp=stats
ence(" "); label: “food” use the .by() step to return values for a
table.CreateIfNotExists(); Request Headers name: “sandwich” Example:
Insert entity specific field.
- Authorization - Date or x-ms-date Vertex isDelicious: true :> g.V().has("name", "sandwich")
Method POST
Create table entity - x-ms-version - x-ms-client-request-id id: 2 .addE("has")
Example:
https://myaccount.table.cosmosdb.azure.com/mytable label: “ingredient” .property("amount", 2)
CustomerEntity item = new CustomerEntity() Request Headers name: “bread” .to(g.V().has("name", "bread")) <- Input
{ Query table
- Authorization - Date or x-ms-date :> g.V().out()
PartitionKey = Guid.NewGuid().ToString(), Method GET
RowKey = Guid.NewGuid().ToString(), - x-ms-version - Content-Type :> g.V().has("name", "sandwich") .path()
https://myaccount.table.cosmosdb.azure.com/Tables
Email = $" ",
PhoneNumber = "",
- Content-Length - Accept Graph object types .addE("has") .by("name")

Bio = GetRandomString(1000) Request Headers - Prefer - x-ms-client-request-id .property("amount", 1)


}; - Authorization - Date or x-ms-date Vertices (also known as nodes): Represent objects. They have .to(g.V().has("name", “cheese")) Output ->
- x-ms-version - x-ms-client-request-id unique ID, a unique label and one ore more properties. :> ["sandwich", "bread"], ["sandwich", “cheese"]
Insert or Merge entity / Insert or Replace entity
Edges: Represent relationships between objects (vertices). They
Insert operation Method MERGE / Method PUT Traverse a graph
have unique Id, a unique label and one or more properties.
Create table
https://myaccount.table.cosmosdb.azure.com/mytable(Partition-
TableOperation = TableOperation.Insert(item);
Method POST
After selecting a vertex, use the .out("label") step Select a specific element from a traversal
table.Execute(insertOperation); Key='myPartitionKey',RowKey='myRowKey')
https://myaccount.table.cosmosdb.azure.com/Tables Graph object attributes to select all adjacent vertices that are connected with
Use the .as() step to name an object, and the
Request Headers edges that have a specific label.
Retrieve operation .select() step to return it at the end of a
Request Headers ID: A property that uniquely identifies each element (vertex or
- Authorization - Date or x-ms-date traversal. After that, you can use the .by() step to
- Authorization - Date or x-ms-date edge) of a graph. Example:
TableOperation retrieveOperation = TableOpera- - x-ms-version - Content-Type get their values.
tion.Retrieve<CustomerEntity>(item.PartitionKey, - x-ms-version - Content-Type - Content-Length - x-ms-client-request-id Labels: A unique string element that can be used to identify <- Input
item.RowKey); - Accept - Prefer types of objects (vertices or edges). This is a required field for :> g.V().has("name", "sandwich")
table.Execute(retrieveOperation);
- Content-Length - x-ms-client-request-id any grapph object. .out("has") Example:
Update entity
Property: A key-value pair that can contain strings, boolean or .properties("name") <- Input
Query Delete table
Method PUT number values. :> g.V().outE().as("e").inV()
https://myaccount.table.cosmosdb.azure.com/mytable(Partition- Output -> .select("e")
TableQuery<CustomerEntity> rangeQuery = new Method DELETE
Key='myPartitionKey',RowKey='myRowKey') :> [cheese, bread] .by("amount")
Gremlin language primer
TableQuery<CustomerEntity>().Where( https://myaccount.table.cosmosdb.azure.com/Tables('mytable')
Request Headers
TableQuery.GenerateFilterCondition("PartitionKey”, Request Headers Output ->
QueryComparisons.Equal, item.PartitionKey); - Authorization - Date or x-ms-date Try this queries with the Gremlin console or the Data
- Authorization - Date or x-ms-date :> [2, 1]
- x-ms-version - Content-Type Explorer on Azure Portal. Loop a traversal
- x-ms-version - x-ms-client-request-id - Content-Length - If-Match
Use the .repeat(out("label")) step, followed by
Table service REST API - x-ms-client-request-id
Traversal variable .until() with a condition.
Get table ACL Drop a vertex or edge
Set table service properties Every query starts with g, the variable that represents
Method GET/HEAD Example: After selecting a vertex or edge, append the
Method PUT Merge entity the graph traversal object. For example, this query will
https://myaccount.table.cosmosdb.azure.com/mytable?com- <- Input .drop() step at the end.
https://myaccount.table.cosmosdb.azure.com/?res- Method MERGE get all the vertices in a graph:
:> g.V().has("name", "sandwich")
type=service&comp=properties Request Headers https://myaccount.table.cosmosdb.azure.com/mytable(Partition-
:> g.V() .repeat(out("has")) Example:
Request Headers - Authorization - Date or x-ms-date Key='myPartitionKey',RowKey='myRowKey')
.until(hasLabel("ingredient")) :> g.V().has("name", "cheese").drop()
- Authorization - Date or x-ms-date - x-ms-version - x-ms-client-request-id
Request Headers .path().by("name")
- x-ms-version - x-ms-client-request-id - Authorization - Date or x-ms-date
Add the vertices
Output ->
Set table ACL - x-ms-version - Content-Type Use the .addV("label") step, followed by any number :> [sandwich, bread], [sandwich, cheese], Drop an entire graph
Get table service properties - Content-Length - If-Match of calls to the .property("key", "value") step.
Method PUT This command will drop all vertices and edges:
- x-ms-client-request-id
Method GET https://myaccount.table.cosmosdb.azure.com/mytable?comp=acl You can also use the .times() step and provide a
Example: number of times it should be repeated: :> g.V().drop()
https://myaccount.table.cosmosdb.azure.com/?restype=ser- Request Headers
:> g.addV("food")
vice&comp=properties - Authorization - Date or x-ms-date Delete entity
.property("name", "sandwich") Example:
Request Headers - x-ms-version - x-ms-client-request-id Method DELETE .property("isDelicious", true) <- Input
- Authorization - Date or x-ms-date https://myaccount.table.cosmosdb.azure.com/mytable(Partition- :> g.V().has("name", "sandwich")
- x-ms-version - x-ms-client-request-id Key='myPartitionKey',RowKey='myRowKey') :> g.addV("ingredient") .repeat(out("has"))
Request Headers .property("name", "cheese") .times(1)
- Authorization - Date or x-ms-date .path().by("name")
- x-ms-version - If-Match :> g.addV("ingredient") Output ->
- x-ms-client-request-id .property("name", “bread") :> [sandwich, bread], [sandwich, cheese]

© 2018 Microsoft Corporation. All rights reserved. Need help or have questions? Email us at [email protected] to talk to a Cosmos database engineer! www.cosmosdb.com | Tweet: @AzureCosmosDB, #cosmosdb

You might also like