File: Program.py

package info (click to toggle)
azure-cosmos-python 3.1.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,280 kB
  • sloc: python: 11,653; makefile: 155
file content (701 lines) | stat: -rw-r--r-- 32,192 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import azure.cosmos.documents as documents
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.errors as errors

import requests
import traceback
import urllib3
from requests.utils import DEFAULT_CA_BUNDLE_PATH as CaCertPath

import samples.Shared.config as cfg

HOST = cfg.settings['host']
MASTER_KEY = cfg.settings['master_key']
DATABASE_ID = cfg.settings['database_id']
COLLECTION_ID = "index-samples"

# A typical collection has the following properties within it's indexingPolicy property
#   indexingMode
#   automatic
#   includedPaths
#   excludedPaths
#   
# We can toggle 'automatic' to eiher be True or False depending upon whether we want to have indexing over all columns by default or not.
# indexingMode can be either of consistent, lazy or none
#   
# We can provide options while creating documents. indexingDirective is one such, 
# by which we can tell whether it should be included or excluded in the index of the parent collection.
# indexingDirective can be either 'Include', 'Exclude' or 'Default'


# To run this Demo, please provide your own CA certs file or download one from
#     http://curl.haxx.se/docs/caextract.html
# Setup the certificate file in .pem format. 
# If you still get an SSLError, try disabling certificate verification and suppress warnings

def ObtainClient():
    connection_policy = documents.ConnectionPolicy()
    connection_policy.SSLConfiguration = documents.SSLConfiguration()
    # Try to setup the cacert.pem
    # connection_policy.SSLConfiguration.SSLCaCerts = CaCertPath
    # Else, disable verification
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    connection_policy.SSLConfiguration.SSLCaCerts = False

    return cosmos_client.CosmosClient(HOST, {'masterKey': MASTER_KEY}, connection_policy)

def test_ssl_connection():
    client = ObtainClient()
    # Read databases after creation.
    try:
        databases = list(client.ReadDatabases())
        print(databases)
        return True
    except requests.exceptions.SSLError as e:
        print("SSL error occured. ", e)
    except OSError as e:
        print("OSError occured. ", e)
    except Exception as e:
        print(traceback.format_exc())
    return False

def GetDatabaseLink(database_id):
    return "dbs" + "/" + database_id

def GetContainerLink(database_id, collection_id):
    return GetDatabaseLink(database_id) +  "/" + "colls" + "/" +  collection_id

def GetDocumentLink(database_id, collection_id, document_id):
    return GetContainerLink(database_id, collection_id) + "/" + "docs" + "/" + document_id

# Query for Entity / Entities 
def Query_Entities(client, entity_type, id = None, parent_link = None):
    find_entity_by_id_query = {
            "query": "SELECT * FROM r WHERE r.id=@id",
            "parameters": [
                { "name":"@id", "value": id }
            ]
        }
    entities = None
    try:
        if entity_type == 'database':
            if id == None:
                entities = list(client.ReadDatabases())
            else:
                entities = list(client.QueryDatabases(find_entity_by_id_query))

        elif entity_type == 'collection':
            if parent_link == None:
                raise ValueError('Database link not provided to search collection(s)')
            if id == None:
                entities = list(client.ReadContainers(parent_link))
            else:
                entities = list(client.QueryContainers(parent_link, find_entity_by_id_query))

        elif entity_type == 'document':
            if parent_link == None:
                raise ValueError('Database / Collection link not provided to search document(s)')
            if id == None:
                entities = list(client.ReadItems(parent_link))
            else:
                entities = list(client.QueryItems(parent_link, find_entity_by_id_query))
    except errors.CosmosError as e:
        print("The following error occured while querying for the entity / entities ", entity_type, id if id != None else "")
        print(e)
        raise
    if id == None:
        return entities
    if len(entities) == 1:
        return entities[0]
    return None

def CreateDatabaseIfNotExists(client, database_id):
    try:
        database = Query_Entities(client, 'database', id = database_id)
        if database == None:
            database = client.CreateDatabase({"id": database_id})
        return database
    except errors.HTTPFailure as e:
        if e.status_code == 409: # Move these constants to an enum
            pass
        else: 
            raise errors.HTTPFailure(e.status_code)

def DeleteContainerIfExists(client, database_id, collection_id):
    try:
        collection_link = GetContainerLink(database_id, collection_id)
        
        client.DeleteContainer(collection_link)
        print('Collection with id \'{0}\' was deleted'.format(collection_id))
    except errors.HTTPFailure as e:
        if e.status_code == 404:
            pass
        elif e.status_code == 400:
            print("Bad request for collection link", collection_link)
            raise
        else:
            raise

def print_dictionary_items(dict):
    for k, v in dict.items():
        print("{:<15}".format(k), v)
    print()

def FetchAllDatabases(client):
    databases = Query_Entities(client, 'database')
    print("-" * 41)
    print("-" * 41)
    for db in databases:
        print_dictionary_items(db)
        print("-" * 41)

def QueryDocumentsWithCustomQuery(client, collection_link, query_with_optional_parameters, message = "Document(s) found by query: "):
    try:
        results = list(client.QueryItems(collection_link, query_with_optional_parameters))
        print(message)
        for doc in results:
            print(doc)
        return results
    except errors.HTTPFailure as e:
        if e.status_code == 404:
            print("Document doesn't exist")
        elif e.status_code == 400:
            # Can occur when we are trying to query on excluded paths
            print("Bad Request exception occured: ", e)
            pass
        else:
            raise
    finally:
        print()

def ExplicitlyExcludeFromIndex(client, database_id):
    """ The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added.
        There may be scenarios where you want to exclude a specific doc from the index even though all other 
        documents are being indexed automatically. 
        This method demonstrates how to use an index directive to control this

    """
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)
        # collections = Query_Entities(client, 'collection', parent_link = database_link)
        # print(collections)

        # Create a collection with default index policy (i.e. automatic = true)
        created_Container = client.CreateContainer(database_link, {"id" : COLLECTION_ID})
        print(created_Container)

        print("\n" + "-" * 25 + "\n1. Collection created with index policy")
        print_dictionary_items(created_Container["indexingPolicy"])

        # Create a document and query on it immediately.
        # Will work as automatic indexing is still True
        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        doc = client.CreateItem(collection_link, { "id" : "doc1", "orderId" : "order1" })
        print("\n" + "-" * 25 + "Document doc1 created with order1" +  "-" * 25)
        print(doc)

        query = {
                "query": "SELECT * FROM r WHERE r.orderId=@orderNo",
                "parameters": [ { "name":"@orderNo", "value": "order1" } ]
            }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        # Now, create a document but this time explictly exclude it from the collection using IndexingDirective
        # Then query for that document
        # Shoud NOT find it, because we excluded it from the index
        # BUT, the document is there and doing a ReadDocument by Id will prove it
        doc2 = client.CreateItem(collection_link, { "id" : "doc2", "orderId" : "order2" }, {'indexingDirective' : documents.IndexingDirective.Exclude})
        print("\n" + "-" * 25 + "Document doc2 created with order2" +  "-" * 25)
        print(doc2)

        query = {
                "query": "SELECT * FROM r WHERE r.orderId=@orderNo",
                "parameters": [ { "name":"@orderNo", "value": "order2" } ]
                }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        docRead = client.ReadItem(GetDocumentLink(database_id, COLLECTION_ID, "doc2"))
        print("Document read by ID: \n", docRead["id"])

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")
    
    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def UseManualIndexing(client, database_id):
    """The default index policy on a DocumentContainer will AUTOMATICALLY index ALL documents added.
       There may be cases where you can want to turn-off automatic indexing and only selectively add only specific documents to the index. 
       This method demonstrates how to control this by setting the value of automatic within indexingPolicy to False

    """
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)
        # collections = Query_Entities(client, 'collection', parent_link = database_link)
        # print(collections)
        
        # Create a collection with manual (instead of automatic) indexing
        created_Container = client.CreateContainer(database_link, {"id" : COLLECTION_ID, "indexingPolicy" : { "automatic" : False} })
        print(created_Container)

        print("\n" + "-" * 25 + "\n2. Collection created with index policy")
        print_dictionary_items(created_Container["indexingPolicy"])

        # Create a document
        # Then query for that document
        # We should find nothing, because automatic indexing on the collection level is False
        # BUT, the document is there and doing a ReadDocument by Id will prove it
        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        doc = client.CreateItem(collection_link, { "id" : "doc1", "orderId" : "order1" })
        print("\n" + "-" * 25 + "Document doc1 created with order1" +  "-" * 25)
        print(doc)

        query = {
                "query": "SELECT * FROM r WHERE r.orderId=@orderNo",
                "parameters": [ { "name":"@orderNo", "value": "order1" } ]
            }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        docRead = client.ReadItem(GetDocumentLink(database_id, COLLECTION_ID, "doc1"))
        print("Document read by ID: \n", docRead["id"])

        # Now create a document, passing in an IndexingDirective saying we want to specifically index this document
        # Query for the document again and this time we should find it because we manually included the document in the index
        doc2 = client.CreateItem(collection_link, { "id" : "doc2", "orderId" : "order2" }, {'indexingDirective' : documents.IndexingDirective.Include})
        print("\n" + "-" * 25 + "Document doc2 created with order2" +  "-" * 25)
        print(doc2)

        query = {
                "query": "SELECT * FROM r WHERE r.orderId=@orderNo",
                "parameters": [ { "name":"@orderNo", "value": "order2" } ]
            }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")

    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def ExcludePathsFromIndex(client, database_id):
    """The default behavior is for Cosmos to index every attribute in every document automatically.
       There are times when a document contains large amounts of information, in deeply nested structures
       that you know you will never search on. In extreme cases like this, you can exclude paths from the 
       index to save on storage cost, improve write performance and also improve read performance because the index is smaller
       
       This method demonstrates how to set excludedPaths within indexingPolicy
    """
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)
        # collections = Query_Entities(client, 'collection', parent_link = database_link)
        # print(collections)

        doc_with_nested_structures = {
            "id" : "doc1",
            "foo" : "bar",
            "metaData" : "meta",
            "subDoc" : { "searchable" : "searchable", "nonSearchable" : "value" },
            "excludedNode" : { "subExcluded" : "something",  "subExcludedNode" : { "someProperty" : "value" } }
            }
        collection_to_create = { "id" : COLLECTION_ID ,
                                "indexingPolicy" : 
                                { 
                                    "includedPaths" : [ {'path' : "/*"} ], # Special mandatory path of "/*" required to denote include entire tree
                                    "excludedPaths" : [ {'path' : "/metaData/*"}, # exclude metaData node, and anything under it
                                                        {'path' : "/subDoc/nonSearchable/*"}, # exclude ONLY a part of subDoc    
                                                        {'path' : "/\"excludedNode\"/*"} # exclude excludedNode node, and anything under it
                                                      ]
                                    } 
                                }
        print(collection_to_create)
        print(doc_with_nested_structures)
        # Create a collection with the defined properties
        # The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed
        created_Container = client.CreateContainer(database_link, collection_to_create)
        print(created_Container)
        print("\n" + "-" * 25 + "\n4. Collection created with index policy")
        print_dictionary_items(created_Container["indexingPolicy"])

        # The effect of the above IndexingPolicy is that only id, foo, and the subDoc/searchable are indexed
        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        doc = client.CreateItem(collection_link, doc_with_nested_structures)
        print("\n" + "-" * 25 + "Document doc1 created with nested structures" +  "-" * 25)
        print(doc)

        # Querying for a document on either metaData or /subDoc/subSubDoc/someProperty > fail because these paths were excluded and they raise a BadRequest(400) Exception
        query = {"query": "SELECT * FROM r WHERE r.metaData=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "meta" }]}
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        query = {"query": "SELECT * FROM r WHERE r.subDoc.nonSearchable=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "value" }]}
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        query = {"query": "SELECT * FROM r WHERE r.excludedNode.subExcludedNode.someProperty=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "value" }]}
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        # Querying for a document using foo, or even subDoc/searchable > succeed because they were not excluded
        query = {"query": "SELECT * FROM r WHERE r.foo=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "bar" }]}
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        query = {"query": "SELECT * FROM r WHERE r.subDoc.searchable=@desiredValue", "parameters" : [{ "name":"@desiredValue", "value": "searchable" }]}
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")

    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def RangeScanOnHashIndex(client, database_id):
    """When a range index is not available (i.e. Only hash or no index found on the path), comparisons queries can still 
       be performed as scans using Allow scan request headers passed through options

       This method demonstrates how to force a scan when only hash indexes exist on the path

       ===== Warning=====
       This was made an opt-in model by design. 
       Scanning is an expensive operation and doing this will have a large impact 
       on RequstUnits charged for an operation and will likely result in queries being throttled sooner.
    """
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)
        # collections = Query_Entities(client, 'collection', parent_link = database_link)
        # print(collections)

        # Force a range scan operation on a hash indexed path
        collection_to_create = { "id" : COLLECTION_ID ,
                                "indexingPolicy" : 
                                { 
                                    "includedPaths" : [ {'path' : "/"} ],
                                    "excludedPaths" : [ {'path' : "/length/*"} ] # exclude length
                                    } 
                                }
        created_Container = client.CreateContainer(database_link, collection_to_create)
        print(created_Container)
        print("\n" + "-" * 25 + "\n5. Collection created with index policy")
        print_dictionary_items(created_Container["indexingPolicy"])

        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        doc1 = client.CreateItem(collection_link, { "id" : "dyn1", "length" : 10, "width" : 5, "height" : 15 })
        doc2 = client.CreateItem(collection_link, { "id" : "dyn2", "length" : 7, "width" : 15 })
        doc3 = client.CreateItem(collection_link, { "id" : "dyn3", "length" : 2 })
        print("Three docs created with ids : ", doc1["id"], doc2["id"], doc3["id"])

        # Query for length > 5 - fail, this is a range based query on a Hash index only document
        query = { "query": "SELECT * FROM r WHERE r.length > 5" }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        # Now add IndexingDirective and repeat query
        # expect 200 OK because now we are explicitly allowing scans in a query
        # using the enableScanInQuery directive
        QueryDocumentsWithCustomQuery(client, collection_link, query)
        results = list(client.QueryItems(collection_link, query, {"enableScanInQuery" : True}))
        print("Printing documents queried by range by providing enableScanInQuery = True")
        for doc in results: print(doc["id"])

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")
    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def UseRangeIndexesOnStrings(client, database_id):
    """Showing how range queries can be performed even on strings.

    """
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)
        # collections = Query_Entities(client, 'collection', parent_link = database_link)
        # print(collections)

        # Use range indexes on strings
        
        # This is how you can specify a range index on strings (and numbers) for all properties.
        # This is the recommended indexing policy for collections. i.e. precision -1
        #indexingPolicy = { 
        #    'indexingPolicy': {
        #        'includedPaths': [
        #            {
        #                'indexes': [
        #                    {
        #                        'kind': documents.IndexKind.Range,
        #                        'dataType': documents.DataType.String,
        #                        'precision': -1
        #                    }
        #                ]
        #            }
        #        ]
        #    }
        #}

        # For demo purposes, we are going to use the default (range on numbers, hash on strings) for the whole document (/* )
        # and just include a range index on strings for the "region".
        collection_definition = {
            'id': COLLECTION_ID,
            'indexingPolicy': {
                'includedPaths': [
                    {
                        'path': '/region/?',
                        'indexes': [
                            {
                                'kind': documents.IndexKind.Range,
                                'dataType': documents.DataType.String,
                                'precision': -1
                            }
                        ]
                    },
                    {
                        'path': '/*'
                    }
                ]
            }
        }

        created_Container = client.CreateContainer(database_link, collection_definition)
        print(created_Container)
        print("\n" + "-" * 25 + "\n6. Collection created with index policy")
        print_dictionary_items(created_Container["indexingPolicy"])

        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        client.CreateItem(collection_link, { "id" : "doc1", "region" : "USA" })
        client.CreateItem(collection_link, { "id" : "doc2", "region" : "UK" })
        client.CreateItem(collection_link, { "id" : "doc3", "region" : "Armenia" })
        client.CreateItem(collection_link, { "id" : "doc4", "region" : "Egypt" })

        # Now ordering against region is allowed. You can run the following query
        query = { "query" : "SELECT * FROM r ORDER BY r.region" }
        message = "Documents ordered by region"
        QueryDocumentsWithCustomQuery(client, collection_link, query, message)

        # You can also perform filters against string comparison like >= 'UK'. Note that you can perform a prefix query, 
        # the equivalent of LIKE 'U%' (is >= 'U' AND < 'U')
        query = { "query" : "SELECT * FROM r WHERE r.region >= 'U'" }
        message = "Documents with region begining with U"
        QueryDocumentsWithCustomQuery(client, collection_link, query, message)

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")
    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def PerformIndexTransformations(client, database_id):
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)
        # collections = Query_Entities(client, 'collection', parent_link = database_link)
        # print(collections)

        # Create a collection with default indexing policy
        created_Container = client.CreateContainer(database_link, {"id" : COLLECTION_ID})
        print(created_Container)

        print("\n" + "-" * 25 + "\n7. Collection created with index policy")
        print_dictionary_items(created_Container["indexingPolicy"])

        # Insert some documents
        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        doc1 = client.CreateItem(collection_link, { "id" : "dyn1", "length" : 10, "width" : 5, "height" : 15 })
        doc2 = client.CreateItem(collection_link, { "id" : "dyn2", "length" : 7, "width" : 15 })
        doc3 = client.CreateItem(collection_link, { "id" : "dyn3", "length" : 2 })
        print("Three docs created with ids : ", doc1["id"], doc2["id"], doc3["id"], " with indexing mode", created_Container['indexingPolicy']['indexingMode'])

        # Switch to use string & number range indexing with maximum precision.
        print("Changing to string & number range indexing with maximum precision (needed for Order By).")

        created_Container['indexingPolicy']['includedPaths'][0]['indexes'] = [{
            'kind': documents.IndexKind.Range, 
            'dataType': documents.DataType.String, 
            'precision': -1
        }]

        created_Container = client.ReplaceContainer(collection_link, created_Container)

        # Check progress and wait for completion - should be instantaneous since we have only a few documents, but larger
        # collections will take time.
        print_dictionary_items(created_Container["indexingPolicy"])

        # Now exclude a path from indexing to save on storage space.
        print("Now excluding the path /length/ to save on storage space")
        created_Container['indexingPolicy']['excludedPaths'] = [{"path" : "/length/*"}]

        created_Container = client.ReplaceContainer(collection_link, created_Container)
        print_dictionary_items(created_Container["indexingPolicy"])

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")
    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def PerformMultiOrderbyQuery(client, database_id):
    try:
        DeleteContainerIfExists(client, database_id, COLLECTION_ID)
        database_link = GetDatabaseLink(database_id)

        # Create a collection with composite indexes
        indexingPolicy = {
            "compositeIndexes": [
                [
                    {
                        "path": "/numberField",
                        "order": "ascending"
                    },
                    {
                        "path": "/stringField",
                        "order": "descending"
                    }
                ],
                [
                    {
                        "path": "/numberField",
                        "order": "descending"
                    },
                    {
                        "path": "/stringField",
                        "order": "ascending"
                    },
                    {
                        "path": "/numberField2",
                        "order": "descending"
                    },
                    {
                        "path": "/stringField2",
                        "order": "ascending"
                    }
                ]
            ]
        }

        container_definition = {
            'id': COLLECTION_ID,
            'indexingPolicy': indexingPolicy
        }

        created_container = client.CreateContainer(database_link, container_definition)

        print(created_container)

        print("\n" + "-" * 25 + "\n8. Collection created with index policy")
        print_dictionary_items(created_container["indexingPolicy"])

        # Insert some documents
        collection_link = GetContainerLink(database_id, COLLECTION_ID)
        doc1 = client.CreateItem(collection_link, {"id": "doc1", "numberField": 1, "stringField": "1", "numberField2": 1, "stringField2": "1"})
        doc2 = client.CreateItem(collection_link, {"id": "doc2", "numberField": 1, "stringField": "1", "numberField2": 1, "stringField2": "2"})
        doc3 = client.CreateItem(collection_link, {"id": "doc3", "numberField": 1, "stringField": "1", "numberField2": 2, "stringField2": "1"})
        doc4 = client.CreateItem(collection_link, {"id": "doc4", "numberField": 1, "stringField": "1", "numberField2": 2, "stringField2": "2"})
        doc5 = client.CreateItem(collection_link, {"id": "doc5", "numberField": 1, "stringField": "2", "numberField2": 1, "stringField2": "1"})
        doc6 = client.CreateItem(collection_link, {"id": "doc6", "numberField": 1, "stringField": "2", "numberField2": 1, "stringField2": "2"})
        doc7 = client.CreateItem(collection_link, {"id": "doc7", "numberField": 1, "stringField": "2", "numberField2": 2, "stringField2": "1"})
        doc8 = client.CreateItem(collection_link, {"id": "doc8", "numberField": 1, "stringField": "2", "numberField2": 2, "stringField2": "2"})
        doc9 = client.CreateItem(collection_link, {"id": "doc9", "numberField": 2, "stringField": "1", "numberField2": 1, "stringField2": "1"})
        doc10 = client.CreateItem(collection_link, {"id": "doc10", "numberField": 2, "stringField": "1", "numberField2": 1, "stringField2": "2"})
        doc11 = client.CreateItem(collection_link, {"id": "doc11", "numberField": 2, "stringField": "1", "numberField2": 2, "stringField2": "1"})
        doc12 = client.CreateItem(collection_link, {"id": "doc12", "numberField": 2, "stringField": "1", "numberField2": 2, "stringField2": "2"})
        doc13 = client.CreateItem(collection_link, {"id": "doc13", "numberField": 2, "stringField": "2", "numberField2": 1, "stringField2": "1"})
        doc14 = client.CreateItem(collection_link, {"id": "doc14", "numberField": 2, "stringField": "2", "numberField2": 1, "stringField2": "2"})
        doc15 = client.CreateItem(collection_link, {"id": "doc15", "numberField": 2, "stringField": "2", "numberField2": 2, "stringField2": "1"})
        doc16 = client.CreateItem(collection_link, {"id": "doc16", "numberField": 2, "stringField": "2", "numberField2": 2, "stringField2": "2"})

        print("Query documents and Order by 1st composite index: Ascending numberField and Descending stringField:")

        query = {
                "query": "SELECT * FROM r ORDER BY r.numberField ASC, r.stringField DESC",
                }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        print("Query documents and Order by inverted 2nd composite index -")
        print("Ascending numberField, Descending stringField, Ascending numberField2, Descending stringField2")

        query = {
                "query": "SELECT * FROM r ORDER BY r.numberField ASC, r.stringField DESC, r.numberField2 ASC, r.stringField2 DESC",
                }
        QueryDocumentsWithCustomQuery(client, collection_link, query)

        # Cleanup
        client.DeleteContainer(collection_link)
        print("\n")
    except errors.HTTPFailure as e:
        if e.status_code == 409:
            print("Entity already exists")
        elif e.status_code == 404:
            print("Entity doesn't exist")
        else:
            raise

def RunIndexDemo():
    try:
        client = ObtainClient()
        FetchAllDatabases(client)

        # Create database if doesn't exist already.
        created_db = CreateDatabaseIfNotExists(client, DATABASE_ID)
        print(created_db)

        # 1. Exclude a document from the index
        ExplicitlyExcludeFromIndex(client, DATABASE_ID)

        # 2. Use manual (instead of automatic) indexing
        UseManualIndexing(client, DATABASE_ID)

        # 4. Exclude specified document paths from the index
        ExcludePathsFromIndex(client, DATABASE_ID)

        # 5. Force a range scan operation on a hash indexed path
        RangeScanOnHashIndex(client, DATABASE_ID)

        # 6. Use range indexes on strings
        UseRangeIndexesOnStrings(client, DATABASE_ID)

        # 7. Perform an index transform
        PerformIndexTransformations(client, DATABASE_ID)

        # 8. Perform Multi Orderby queries using composite indexes
        PerformMultiOrderbyQuery(client, DATABASE_ID)

    except errors.CosmosError as e:
        raise e

if __name__ == '__main__':
    print("Hello!")
    for i in [HOST, MASTER_KEY, DATABASE_ID, COLLECTION_ID] : print(i)
    if test_ssl_connection() == True:
        RunIndexDemo()