├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── connect.py └── requirements.txt /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | > Please provide us with the following information: 5 | > --------------------------------------------------------------- 6 | 7 | ### This issue is for a: (mark with an `x`) 8 | ``` 9 | - [ ] bug report -> please search issues before submitting 10 | - [ ] feature request 11 | - [ ] documentation issue or request 12 | - [ ] regression (a behavior that used to work and stopped in a new release) 13 | ``` 14 | 15 | ### Minimal steps to reproduce 16 | > 17 | 18 | ### Any log messages given by the failure 19 | > 20 | 21 | ### Expected/desired behavior 22 | > 23 | 24 | ### OS and Version? 25 | > Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?) 26 | 27 | ### Versions 28 | > 29 | 30 | ### Mention any other details that might be useful 31 | 32 | > --------------------------------------------------------------- 33 | > Thanks! We'll be in touch soon. 34 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Purpose 2 | 3 | * ... 4 | 5 | ## Does this introduce a breaking change? 6 | 7 | ``` 8 | [ ] Yes 9 | [ ] No 10 | ``` 11 | 12 | ## Pull Request Type 13 | What kind of change does this Pull Request introduce? 14 | 15 | 16 | ``` 17 | [ ] Bugfix 18 | [ ] Feature 19 | [ ] Code style update (formatting, local variables) 20 | [ ] Refactoring (no functional changes, no api changes) 21 | [ ] Documentation content changes 22 | [ ] Other... Please describe: 23 | ``` 24 | 25 | ## How to Test 26 | * Get the code 27 | 28 | ``` 29 | git clone [repo-address] 30 | cd [repo-name] 31 | git checkout [branch-name] 32 | npm install 33 | ``` 34 | 35 | * Test the code 36 | 37 | ``` 38 | ``` 39 | 40 | ## What to Check 41 | Verify that the following are valid 42 | * ... 43 | 44 | ## Other Information 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [project-title] Changelog 2 | 3 | 4 | # x.y.z (yyyy-mm-dd) 5 | 6 | *Features* 7 | * ... 8 | 9 | *Bug Fixes* 10 | * ... 11 | 12 | *Breaking Changes* 13 | * ... 14 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to [project-title] 2 | 3 | This project welcomes contributions and suggestions. Most contributions require you to agree to a 4 | Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us 5 | the rights to use your contribution. For details, visit https://cla.microsoft.com. 6 | 7 | When you submit a pull request, a CLA-bot will automatically determine whether you need to provide 8 | a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions 9 | provided by the bot. You will only need to do this once across all repos using our CLA. 10 | 11 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 12 | For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or 13 | contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 14 | 15 | - [Code of Conduct](#coc) 16 | - [Issues and Bugs](#issue) 17 | - [Feature Requests](#feature) 18 | - [Submission Guidelines](#submit) 19 | 20 | ## Code of Conduct 21 | Help us keep this project open and inclusive. Please read and follow our [Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 22 | 23 | ## Found an Issue? 24 | If you find a bug in the source code or a mistake in the documentation, you can help us by 25 | [submitting an issue](#submit-issue) to the GitHub Repository. Even better, you can 26 | [submit a Pull Request](#submit-pr) with a fix. 27 | 28 | ## Want a Feature? 29 | You can *request* a new feature by [submitting an issue](#submit-issue) to the GitHub 30 | Repository. If you would like to *implement* a new feature, please submit an issue with 31 | a proposal for your work first, to be sure that we can use it. 32 | 33 | * **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). 34 | 35 | ## Submission Guidelines 36 | 37 | ### Submitting an Issue 38 | Before you submit an issue, search the archive, maybe your question was already answered. 39 | 40 | If your issue appears to be a bug, and hasn't been reported, open a new issue. 41 | Help us to maximize the effort we can spend fixing issues and adding new 42 | features, by not reporting duplicate issues. Providing the following information will increase the 43 | chances of your issue being dealt with quickly: 44 | 45 | * **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps 46 | * **Version** - what version is affected (e.g. 0.1.2) 47 | * **Motivation for or Use Case** - explain what are you trying to do and why the current behavior is a bug for you 48 | * **Browsers and Operating System** - is this a problem with all browsers? 49 | * **Reproduce the Error** - provide a live example or a unambiguous set of steps 50 | * **Related Issues** - has a similar issue been reported before? 51 | * **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be 52 | causing the problem (line of code or commit) 53 | 54 | You can file new issues by providing the above information at the corresponding repository's issues link: https://github.com/[organization-name]/[repository-name]/issues/new]. 55 | 56 | ### Submitting a Pull Request (PR) 57 | Before you submit your Pull Request (PR) consider the following guidelines: 58 | 59 | * Search the repository (https://github.com/[organization-name]/[repository-name]/pulls) for an open or closed PR 60 | that relates to your submission. You don't want to duplicate effort. 61 | 62 | * Make your changes in a new git fork: 63 | 64 | * Commit your changes using a descriptive commit message 65 | * Push your fork to GitHub: 66 | * In GitHub, create a pull request 67 | * If we suggest changes then: 68 | * Make the required updates. 69 | * Rebase your fork and force push to your GitHub repository (this will update your Pull Request): 70 | 71 | ```shell 72 | git rebase master -i 73 | git push -f 74 | ``` 75 | 76 | That's it! Thank you for your contribution! 77 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | --- 2 | page_type: sample 3 | languages: 4 | - python 5 | products: 6 | - azure 7 | description: "Azure Cosmos DB is a globally distributed multi-model database." 8 | urlFragment: azure-cosmos-db-graph-python-getting-started 9 | --- 10 | 11 | # Developing a Python Gremlin app using Azure Cosmos DB 12 | Azure Cosmos DB is a globally distributed multi-model database. One of the supported APIs is the Graph (Gremlin) API, which provides a graph data model with [Gremlin query/traversals](https://tinkerpop.apache.org/gremlin.html). This sample shows you how to use the Azure Cosmos DB with the Graph API to store and access data from a Python application. 13 | 14 | ## Running this sample 15 | 16 | * Before you can run this sample, you must have the following prerequisites: 17 | 18 | * An active Azure account. If you don't have one, you can sign up for a [free account](https://azure.microsoft.com/free/). 19 | * [Python](https://www.python.org/downloads/) version v3.4 or newer. In order for this sample to work with Python 2.7, change all references from `input()` to `raw_input()`. 20 | * [pip package manager](https://pip.pypa.io/en/stable/installing/) 21 | * [Git](http://git-scm.com/) 22 | * [Python Driver for Gremlin](https://github.com/apache/tinkerpop/tree/master/gremlin-python) 23 | 24 | 25 | * Then, clone this repository using `git clone https://github.com/Azure-Samples/azure-cosmos-db-graph-python-getting-started.git` 26 | 27 | * Next, substitute the endpoint and authorization key in the `connect.py`, on line 105, with your Cosmos DB account's values: 28 | 29 | ```python 30 | client = client.Client('wss://:443/','g', 31 | username="/dbs//colls/", 32 | password="", 33 | message_serializer=serializer.GraphSONSerializersV2d0() 34 | ) 35 | ``` 36 | 37 | | Setting | Suggested Value | Description | 38 | | ------- | --------------- | ----------- | 39 | | YOUR_ENDPOINT | [`***.gremlin.cosmos.azure.com:`] | This is the Gremlin URI value on the Overview page of the Azure portal, in square brackets, with the trailing :443/ removed. This value can also be retrieved from the Overview tab, using the Gremlin Endpoint value by replacing https:// with wss://, and removing the trailing :443/. | 40 | | username | `/dbs//colls/` | The resource of the form `/dbs//colls/` where `` is your database name and `` is your collection name. | 41 | | password | Your primary key | This is your primary key, which you can retrieve from the Keys page of the Azure portal, in the Primary Key box. Use the copy button on the left side of the box to copy the value. | 42 | 43 | * From a command prompt or shell, run `pip install -r requirements.txt` to get and resolve dependencies. 44 | 45 | * From a command prompt or shell, run `python connect.py` to run the application. 46 | 47 | ## About the code 48 | The code included in this sample is intended to get you quickly started with a Python application that connects to Azure Cosmos DB with the Graph (Gremlin) API. 49 | 50 | ## More information 51 | 52 | - [Azure Cosmos DB](https://docs.microsoft.com/azure/cosmos-db/introduction) 53 | - [Azure Cosmos DB : Graph API](https://docs.microsoft.com/en-us/azure/cosmos-db/graph-introduction) 54 | - [Gremlin Python](http://tinkerpop.apache.org/docs/current/reference/#gremlin-python) 55 | - [Gremlin-Python driver source code](https://github.com/apache/tinkerpop/tree/master/gremlin-python) 56 | -------------------------------------------------------------------------------- /connect.py: -------------------------------------------------------------------------------- 1 | from gremlin_python.driver import client, serializer, protocol 2 | from gremlin_python.driver.protocol import GremlinServerError 3 | import sys 4 | import traceback 5 | import asyncio 6 | 7 | if sys.platform == 'win32': 8 | asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) 9 | 10 | _gremlin_cleanup_graph = "g.V().drop()" 11 | 12 | _gremlin_insert_vertices = [ 13 | "g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44).property('pk', 'pk')", 14 | "g.addV('person').property('id', 'mary').property('firstName', 'Mary').property('lastName', 'Andersen').property('age', 39).property('pk', 'pk')", 15 | "g.addV('person').property('id', 'ben').property('firstName', 'Ben').property('lastName', 'Miller').property('pk', 'pk')", 16 | "g.addV('person').property('id', 'robin').property('firstName', 'Robin').property('lastName', 'Wakefield').property('pk', 'pk')" 17 | ] 18 | 19 | _gremlin_insert_edges = [ 20 | "g.V('thomas').addE('knows').to(g.V('mary'))", 21 | "g.V('thomas').addE('knows').to(g.V('ben'))", 22 | "g.V('ben').addE('knows').to(g.V('robin'))" 23 | ] 24 | 25 | _gremlin_update_vertices = [ 26 | "g.V('thomas').property('age', 45)" 27 | ] 28 | 29 | _gremlin_count_vertices = "g.V().count()" 30 | 31 | _gremlin_traversals = { 32 | "Get all persons older than 40": "g.V().hasLabel('person').has('age', gt(40)).values('firstName', 'age')", 33 | "Get all persons and their first name": "g.V().hasLabel('person').values('firstName')", 34 | "Get all persons sorted by first name": "g.V().hasLabel('person').order().by('firstName', incr).values('firstName')", 35 | "Get all persons that Thomas knows": "g.V('thomas').out('knows').hasLabel('person').values('firstName')", 36 | "People known by those who Thomas knows": "g.V('thomas').out('knows').hasLabel('person').out('knows').hasLabel('person').values('firstName')", 37 | "Get the path from Thomas to Robin": "g.V('thomas').repeat(out()).until(has('id', 'robin')).path().by('firstName')" 38 | } 39 | 40 | _gremlin_drop_operations = { 41 | "Drop Edge - Thomas no longer knows Mary": "g.V('thomas').outE('knows').where(inV().has('id', 'mary')).drop()", 42 | "Drop Vertex - Drop Thomas": "g.V('thomas').drop()" 43 | } 44 | 45 | def print_status_attributes(result): 46 | # This logs the status attributes returned for successful requests. 47 | # See list of available response status attributes (headers) that Gremlin API can return: 48 | # https://docs.microsoft.com/en-us/azure/cosmos-db/gremlin-headers#headers 49 | # 50 | # These responses includes total request units charged and total server latency time. 51 | # 52 | # IMPORTANT: Make sure to consume ALL results returend by cliient tothe final status attributes 53 | # for a request. Gremlin result are stream as a sequence of partial response messages 54 | # where the last response contents the complete status attributes set. 55 | # 56 | # This can be 57 | print("\tResponse status_attributes:\n\t{0}".format(result.status_attributes)) 58 | 59 | def cleanup_graph(client): 60 | print("\n> {0}".format( 61 | _gremlin_cleanup_graph)) 62 | callback = client.submitAsync(_gremlin_cleanup_graph) 63 | if callback.result() is not None: 64 | callback.result().all().result() 65 | print("\n") 66 | print_status_attributes(callback.result()) 67 | print("\n") 68 | 69 | 70 | def insert_vertices(client): 71 | for query in _gremlin_insert_vertices: 72 | print("\n> {0}\n".format(query)) 73 | callback = client.submitAsync(query) 74 | if callback.result() is not None: 75 | print("\tInserted this vertex:\n\t{0}".format( 76 | callback.result().all().result())) 77 | else: 78 | print("Something went wrong with this query: {0}".format(query)) 79 | print("\n") 80 | print_status_attributes(callback.result()) 81 | print("\n") 82 | 83 | print("\n") 84 | 85 | 86 | def insert_edges(client): 87 | for query in _gremlin_insert_edges: 88 | print("\n> {0}\n".format(query)) 89 | callback = client.submitAsync(query) 90 | if callback.result() is not None: 91 | print("\tInserted this edge:\n\t{0}\n".format( 92 | callback.result().all().result())) 93 | else: 94 | print("Something went wrong with this query:\n\t{0}".format(query)) 95 | print_status_attributes(callback.result()) 96 | print("\n") 97 | 98 | print("\n") 99 | 100 | 101 | def update_vertices(client): 102 | for query in _gremlin_update_vertices: 103 | print("\n> {0}\n".format(query)) 104 | callback = client.submitAsync(query) 105 | if callback.result() is not None: 106 | print("\tUpdated this vertex:\n\t{0}\n".format( 107 | callback.result().all().result())) 108 | else: 109 | print("Something went wrong with this query:\n\t{0}".format(query)) 110 | 111 | print_status_attributes(callback.result()) 112 | print("\n") 113 | 114 | print("\n") 115 | 116 | 117 | def count_vertices(client): 118 | print("\n> {0}".format( 119 | _gremlin_count_vertices)) 120 | callback = client.submitAsync(_gremlin_count_vertices) 121 | if callback.result() is not None: 122 | print("\tCount of vertices: {0}".format(callback.result().all().result())) 123 | else: 124 | print("Something went wrong with this query: {0}".format( 125 | _gremlin_count_vertices)) 126 | 127 | print("\n") 128 | print_status_attributes(callback.result()) 129 | print("\n") 130 | 131 | 132 | def execute_traversals(client): 133 | for key in _gremlin_traversals: 134 | print("{0}:".format(key)) 135 | print("> {0}\n".format( 136 | _gremlin_traversals[key])) 137 | callback = client.submitAsync(_gremlin_traversals[key]) 138 | for result in callback.result(): 139 | print("\t{0}".format(str(result))) 140 | 141 | print("\n") 142 | print_status_attributes(callback.result()) 143 | print("\n") 144 | 145 | 146 | def execute_drop_operations(client): 147 | for key in _gremlin_drop_operations: 148 | print("{0}:".format(key)) 149 | print("\n> {0}".format( 150 | _gremlin_drop_operations[key])) 151 | callback = client.submitAsync(_gremlin_drop_operations[key]) 152 | for result in callback.result(): 153 | print(result) 154 | print_status_attributes(callback.result()) 155 | print("\n") 156 | 157 | 158 | try: 159 | client = client.Client('wss://.gremlin.cosmos.azure.com:443/', 'g', 160 | username="/dbs//colls/", 161 | password="", 162 | message_serializer=serializer.GraphSONSerializersV2d0() 163 | ) 164 | 165 | print("Welcome to Azure Cosmos DB + Gremlin on Python!") 166 | 167 | # Drop the entire Graph 168 | input("We're about to drop whatever graph is on the server. Press any key to continue...") 169 | cleanup_graph(client) 170 | 171 | # Insert all vertices 172 | input("Let's insert some vertices into the graph. Press any key to continue...") 173 | insert_vertices(client) 174 | 175 | # Create edges between vertices 176 | input("Now, let's add some edges between the vertices. Press any key to continue...") 177 | insert_edges(client) 178 | 179 | # Update a vertex 180 | input("Ah, sorry. I made a mistake. Let's change the age of this vertex. Press any key to continue...") 181 | update_vertices(client) 182 | 183 | # Count all vertices 184 | input("Okay. Let's count how many vertices we have. Press any key to continue...") 185 | count_vertices(client) 186 | 187 | # Execute traversals and get results 188 | input("Cool! Let's run some traversals on our graph. Press any key to continue...") 189 | execute_traversals(client) 190 | 191 | # Drop a few vertices and edges 192 | input("So, life happens and now we will make some changes to the graph. Press any key to continue...") 193 | execute_drop_operations(client) 194 | 195 | # Count all vertices again 196 | input("How many vertices do we have left? Press any key to continue...") 197 | count_vertices(client) 198 | 199 | except GremlinServerError as e: 200 | print('Code: {0}, Attributes: {1}'.format(e.status_code, e.status_attributes)) 201 | 202 | # GremlinServerError.status_code returns the Gremlin protocol status code 203 | # These are broad status codes which can cover various scenaios, so for more specific 204 | # error handling we recommend using GremlinServerError.status_attributes['x-ms-status-code'] 205 | # 206 | # Below shows how to capture the Cosmos DB specific status code and perform specific error handling. 207 | # See detailed set status codes than can be returned here: https://docs.microsoft.com/en-us/azure/cosmos-db/gremlin-headers#status-codes 208 | # 209 | # See also list of available response status attributes that Gremlin API can return: 210 | # https://docs.microsoft.com/en-us/azure/cosmos-db/gremlin-headers#headers 211 | cosmos_status_code = e.status_attributes["x-ms-status-code"] 212 | if cosmos_status_code == 409: 213 | print('Conflict error!') 214 | elif cosmos_status_code == 412: 215 | print('Precondition error!') 216 | elif cosmos_status_code == 429: 217 | print('Throttling error!'); 218 | elif cosmos_status_code == 1009: 219 | print('Request timeout error!') 220 | else: 221 | print("Default error handling") 222 | 223 | traceback.print_exc(file=sys.stdout) 224 | sys.exit(1) 225 | 226 | print("\nAnd that's all! Sample complete") 227 | input("Press Enter to continue...") 228 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | gremlinpython==3.4.13 2 | futures 3 | --------------------------------------------------------------------------------