├── ACKNOWLEDGEMENTS.md ├── CONTRIBUTING.md ├── DEVELOPING.md ├── LICENSE ├── MAINTAINERS.md ├── README.md ├── configuration └── config.json ├── data └── README.md ├── doc └── source │ └── images │ ├── Architecture.png │ ├── THUMBNAILFORVIDEO.jpg │ ├── add_file.png │ ├── clustering_notebook.png │ ├── config.png │ ├── create_notebook.png │ ├── most_mentioned.png │ ├── most_mentioned_json.png │ ├── most_mentioned_notebook.png │ ├── movie_rating.png │ ├── pandas.png │ └── worked_With.png └── notebooks └── graphdb-insights.ipynb /ACKNOWLEDGEMENTS.md: -------------------------------------------------------------------------------- 1 | # Acknowledgement 2 | 3 | I would like to express my sincere thanks to [Balaji Kadambi](https://www.linkedin.com/in/balaji-kadambi-1519223/), [Shikha Maheshwari](https://www.linkedin.com/in/shikha-maheshwari-b2352921) for guiding me thoroughly right from the code design to Documentation of the Journey. The Journey has been great learning under their mentorship. 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing In General 2 | 3 | Our project welcomes external contributions! If you have an itch, please 4 | feel free to scratch it. 5 | 6 | To contribute code or documentation, please submit a pull request to the [GitHub 7 | repository](https://github.com/IBM/graph-db-insights). 8 | 9 | A good way to familiarize yourself with the codebase and contribution process is 10 | to look for and tackle low-hanging fruit in the [issue 11 | tracker](https://github.com/IBM/graph-db-insights/issues). Before embarking on 12 | a more ambitious contribution, please quickly [get in touch](#communication) 13 | with us. 14 | 15 | **We appreciate your effort, and want to avoid a situation where a contribution 16 | requires extensive rework (by you or by us), sits in the queue for a long time, 17 | or cannot be accepted at all!** 18 | 19 | ### Proposing new features 20 | 21 | If you would like to implement a new feature, please [raise an 22 | issue](https://github.com/IBM/graph-db-insights/issues) before sending a pull 23 | request so the feature can be discussed. This is to avoid you spending your 24 | valuable time working on a feature that the project developers are not willing 25 | to accept into the code base. 26 | 27 | ### Fixing bugs 28 | 29 | If you would like to fix a bug, please [raise an 30 | issue](https://github.com/IBM/graph-db-insights/issues) before sending a pull 31 | request so it can be discussed. If the fix is trivial or non controversial then 32 | this is not usually necessary. 33 | 34 | ### Merge approval 35 | 36 | The project maintainers use LGTM (Looks Good To Me) in comments on the code 37 | review to indicate acceptance. A change requires LGTMs from two of the 38 | maintainers of each component affected. 39 | 40 | For more details, see the [MAINTAINERS](MAINTAINERS.md) page. 41 | 42 | ## Communication 43 | 44 | Please feel free to connect with us [here](https://github.com/IBM/graph-db-insights/issues). 45 | 46 | ## Setup 47 | 48 | Please add any special setup instructions for your project to help the 49 | developer become productive quickly. 50 | 51 | ## Testing 52 | 53 | Please provide information that helps the developer test any changes they 54 | make before submitting. 55 | 56 | ## Coding style guidelines 57 | 58 | Beautiful code rocks! Please share any specific style guidelines you might 59 | have for your project. 60 | -------------------------------------------------------------------------------- /DEVELOPING.md: -------------------------------------------------------------------------------- 1 | Tips for Developers 2 | =================== 3 | 4 | The notebook is designed to be run top-down. Settings in early cells are used 5 | in later cells. Some variables are also cleared to free up memory. So, although 6 | you can often run single cell repeatedly while testing changes, you may want 7 | to start over from the top if anything seems to be missing. 8 | 9 | Setting credentials 10 | ------------------- 11 | Credentials need to be added to the notebook to access some Bluemix services. 12 | The credentials are set near the top of the notebook to make it 13 | more obvious that they need to be set and also to make it more obvious that 14 | you will be saving a notebook with credentials. You should not share your 15 | notebook with anyone that you would not share your credentials with 16 | unless you use the ``share`` feature with the ``Only text and output`` or 17 | ``All content excluding sensitive code cells`` option. 18 | 19 | The ```@hidden_cell``` magic is used to mark the credentials cells as 20 | "sensitive". If you do any rearranging of sensitive code, remember to identify 21 | sensitive cells with ``@hidden_cell``. 22 | 23 | Installing Python packages 24 | -------------------------- 25 | A notebook can use ```!pip install``` to install the Python packages 26 | from PyPI. You can follow this example if you decide to use additional Python 27 | packages in your notebook. Check the output to see that the install was 28 | successful. See the "Controlling output" section below for more information on 29 | how to suppress/show the output. You might want to use ``DEBUG = True`` until 30 | you've verified that the pip install was successful. 31 | 32 | > **Note**: After running a cell with pip install, you may need to restart 33 | the kernel and then run the cells again from the top. 34 | 35 | Importing libraries 36 | ------------------- 37 | Import and some setup of libraries is done near the top. This is another 38 | example of why cells need to run top-down. Keeping the imports near the top 39 | is a Python PEP8 style convention. Python does not require this convention, 40 | but Python developers are used to looking for imports at the top. 41 | 42 | Defining global variables and helper functions 43 | ---------------------------------------------- 44 | After the imports, a few global variables and helper functions are defined. 45 | These allow for code re-use. These cells need to run before other cells can 46 | use the functions and globals. These values do not change. You can change 47 | and run the later cells over and over without always restarting from the top. 48 | 49 | Controlling output 50 | ------------------ 51 | One of the great things about notebooks is that you can use them to document 52 | what you are doing, show your work, show the results, and document your 53 | conclusion -- all in one place. Sharing "your work" (the code) is a great 54 | feature, but to make the "only text and output" web page look nice and clean 55 | you can use the following tips. 56 | 57 | #### @hidden_cell magic 58 | 59 | The @hidden_cell magic is used to mark the credentials cells as "sensitive". 60 | If you do any rearranging of sensitive code, remember to identify sensitive 61 | cells with @hidden_cell. 62 | 63 | #### Ending with a semi-colon 64 | 65 | Statements in a notebook can end with a semi-colon. It looks like 66 | bad Python, but it is actually a trick to prevent these statements from 67 | showing their result in the output. 68 | 69 | #### if DEBUG 70 | 71 | A DEBUG boolean and 'if' statements can be used throughout the notebook 72 | wherever some print statements are handy during development and might be 73 | handy in the future, but are not something you want to share in the final 74 | output. 75 | 76 | #### %%capture captured_io 77 | 78 | "%%capture captured_io" magic can be used to capture the output when nothing 79 | else works. You can use that to hide the "!pip install" output and add a cell 80 | right after it that will print the captured output if DEBUG is True. 81 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | ## Maintainers Guide 2 | 3 | This guide is intended for maintainers — anybody with commit access to one or 4 | more Developer Journey repositories. 5 | 6 | ## Methodology: 7 | 8 | A master branch. This branch MUST be releasable at all times. Commits and 9 | merges against this branch MUST contain only bugfixes and/or security fixes. 10 | Maintenance releases are tagged against master. 11 | 12 | A develop branch. This branch contains your proposed changes. 13 | 14 | The remainder of this document details how to merge pull requests to the 15 | repositories. 16 | 17 | ## Merge approval 18 | 19 | The project maintainers use LGTM (Looks Good To Me) in comments on the code 20 | review to indicate acceptance. A change requires LGTMs from two of the members 21 | of the [watson-journey-dev-admins](https://github.com/orgs/IBM/teams/watson-journey-dev-admins) 22 | team. If the code is written by a member, the change only requires one more 23 | LGTM. 24 | 25 | ## Reviewing Pull Requests 26 | 27 | We recommend reviewing pull requests directly within GitHub. This allows a 28 | public commentary on changes, providing transparency for all users. When 29 | providing feedback be civil, courteous, and kind. Disagreement is fine, so 30 | long as the discourse is carried out politely. If we see a record of uncivil 31 | or abusive comments, we will revoke your commit privileges and invite you to 32 | leave the project. 33 | 34 | During your review, consider the following points: 35 | 36 | ### Does the change have impact? 37 | 38 | While fixing typos is nice as it adds to the overall quality of the project, 39 | merging a typo fix at a time can be a waste of effort. 40 | (Merging many typo fixes because somebody reviewed the entire component, 41 | however, is useful!) Other examples to be wary of: 42 | 43 | Changes in variable names. Ask whether or not the change will make 44 | understanding the code easier, or if it could simply a personal preference 45 | on the part of the author. 46 | 47 | Essentially: feel free to close issues that do not have impact. 48 | 49 | ### Do the changes make sense? 50 | 51 | If you do not understand what the changes are or what they accomplish, 52 | ask the author for clarification. Ask the author to add comments and/or 53 | clarify test case names to make the intentions clear. 54 | 55 | At times, such clarification will reveal that the author may not be using 56 | the code correctly, or is unaware of features that accommodate their needs. 57 | If you feel this is the case, work up a code sample that would address the 58 | issue for them, and feel free to close the issue once they confirm. 59 | 60 | ### Is this a new feature? If so: 61 | 62 | Does the issue contain narrative indicating the need for the feature? If not, 63 | ask them to provide that information. Since the issue will be linked in the 64 | changelog, this will often be a user's first introduction to it. 65 | 66 | Are new unit tests in place that test all new behaviors introduced? If not, do 67 | not merge the feature until they are! 68 | Is documentation in place for the new feature? (See the documentation 69 | guidelines). If not do not merge the feature until it is! 70 | Is the feature necessary for general use cases? Try and keep the scope of any 71 | given component narrow. If a proposed feature does not fit that scope, 72 | recommend to the user that they maintain the feature on their own, and close 73 | the request. You may also recommend that they see if the feature gains traction 74 | amongst other users, and suggest they re-submit when they can show such support. 75 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Get Insights from OrientDB database using PyOrient through IBM Watson Studio 2 | 3 | > Data Science Experience is now Watson Studio. Although some images in this code pattern may show the service as Data Science Experience, the steps and processes will still work. 4 | 5 | This journey gives you a head start on how to work with graphs in OrientDB through IBM Watson Studio using PyOrient module - a python driver for OrientDB to operate on data and to get insights from OrientDB. IBM Watson Studio can be used to analyze data using Jupyter notebooks. 6 | 7 | OrientDB is a multi-model database, supporting graph, document, key/value, and object models, but the relationships are managed as in graph databases with direct connections between records. Graph databases are well-suited for analysing interconnections like to mine data from social media. It is also useful for working with data in business disciplines that involve complex relationships and dynamic schema and creating recommendations like "customers who bought this also looked at...". This journey will help you to understand end-to-end flow starting from downloading the data-set, cleansing of data, extract entities and relations from the data-set, connect with OrientDB, create a new OrientDB database, populate database with node classes, edge classes, vertices, relations and then execute queries to get insights from the data in OrientDB database. OrientDB have extended SQL to provide support for graph traversal in graph database making it easy for developers familiar with SQL to start exploring graph database for their business needs. 8 | 9 | In this journey we will demonstrate: 10 | * Setting up ipython notebook on Watson Studio connecting to OrientDB using PyOrient. 11 | * To perform the CRUD operations and extracting insights from OrientDB database. 12 | 13 | To achieve this, OrientDB instance is created on the Kubernetes Cluster and then it is accessed through IBM Watson Studio. This journey will help developers to get started with various OrientDB operations like CRUD, basic traversal and extracting insights using PyOrient on IBM Watson Studio. 14 | 15 | When the reader has completed this journey, they will understand how to: 16 | - Create Kubernetes Cluster and deploy OrientDB on it. 17 | - Create and Run a Jupyter Notebook in IBM Watson Studio. 18 | - Run OrientDB queries using PyOrient module in IBM Watson Studio. 19 | - Visualise the OrientDB result in OrientDB Studio. 20 | 21 | ![](doc/source/images/Architecture.png) 22 | 23 | 1. The developer sets up the Kubernetes cluster using Kubernetes service on IBM Cloud. 24 | 2. The OrientDB instance is deployed on the Kubernetes cluster created by the developer in the first step with persistent volume, exposing the ports(2424, 2480) used by OrientDB on bluemix. 25 | 3. The developer creates a Jupyter notebook on the IBM Watson Studio powered by spark. While creation of notebook, an instance of Object Storage is attached to the notebook for storing the data used by the notebook. 26 | 4. The developer uploads the configuration file (config.json) and the dataset (graph-insights.csv) in the object storage. 27 | 5. The credentials of Object Storage are updated in the notebook and the files from Object Storage are loaded to create graph from them in OrientDB. 28 | 6. The notebook communicates with the OrientDB through PyOrient driver. And various operations are performed on the OrientDB using functions written in the Jupyter notebook. 29 | 30 | ## Included components 31 | 32 | * [OrientDB](https://orientdb.com/why-orientdb/): A Multi-Model Open Source NoSQL DBMS. 33 | 34 | * [IBM Watson Studio](https://dataplatform.cloud.ibm.com/): Analyze data using RStudio, Jupyter, and Python in a configured, collaborative environment that includes IBM value-adds, such as managed Spark. 35 | 36 | * [IBM Cloud Object Storage](https://cloud.ibm.com/catalog/services/cloud-object-storage/): An IBM Cloud service that provides an unstructured cloud data store to build and deliver cost effective apps and services with high reliability and fast speed to market. 37 | 38 | * [Jupyter Notebooks](https://jupyter.org/): An open-source web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. 39 | 40 | * [Kubernetes Clusters](https://console.bluemix.net/containers-kubernetes/catalog/cluster/create): an open-source system for automating deployment, scaling, and management of containerized applications. 41 | 42 | ## Featured technologies 43 | 44 | * [Data Science](https://medium.com/ibm-data-science-experience/): Systems and scientific methods to analyze structured and unstructured data in order to extract knowledge and insights. 45 | 46 | * [Graph Database](https://en.wikipedia.org/wiki/Graph_database): A graph database is a database that uses graph structures for semantic queries with nodes, edges and properties to represent and store data. A key concept of the system is the graph (or edge or relationship), which directly relates data items in the store. The relationships allow data in the store to be linked together directly, and in many cases retrieved with one operation. 47 | 48 | ## Prerequisite 49 | 50 | Create a Kubernetes cluster with [IBM Cloud Container Service](https://console.bluemix.net/containers-kubernetes/catalog/cluster/create) to deploy in cloud. Deploy OrientDB on Kubernetes Cluster using [Deploy OrientDB on Kubernetes](https://github.com/IBM/deploy-graph-db-container). 51 | 52 | # Watch the Video 53 | Watch this video to get an overview of this developer Journey. 54 | [![](doc/source/images/THUMBNAILFORVIDEO.jpg)](https://www.youtube.com/watch?v=oGj2Bi_Viqo&t=15s) 55 | 56 | # Steps 57 | 58 | Follow these steps to setup and run this developer journey. The steps are 59 | described in detail below. 60 | 61 | 62 | 1. [Deploy OrientDB on Kubernetes Cluster](#1-deploy-orientdb-on-kubernetes-cluster) 63 | 1. [Sign up for Watson Studio](#2-sign-up-for-watson-studio) 64 | 1. [Create the notebook](#3-create-the-notebook) 65 | 1. [Add the data](#4-add-the-data) 66 | 1. [Update the notebook with service credentials](#5-update-the-notebook-with-service-credentials) 67 | 1. [Flow of the notebook](#6-flow-of-the-notebook) 68 | 1. [Run the notebook](#7-run-the-notebook) 69 | 1. [Analyze the results](#8-analyze-the-results) 70 | 71 | 72 | 73 | ## 1. Deploy OrientDB on Kubernetes Cluster 74 | Deploy OrientDB on Kubernetes cluster using [Deploy OrientDB on Kubernetes](https://github.com/IBM/deploy-graph-db-container). It will expose the ports on IBM Cloud through which OrientDB can be accessed from the Jupyter notebook on IBM Watson Studio. Use the `ip-address of your cluster` and node port `port 2424` on which the OrientDB console is mapped, to access that OrientDB through Jupyter notebook. 75 | 76 | ## 2. Sign up for Watson Studio 77 | 78 | Sign up for IBM's [Watson Studio](https://www.ibm.com/cloud/watson-studio). By creating a project in Watson Studio a free tier ``Object Storage`` service will be created in your IBM Cloud account. 79 | 80 | ## 3. Create the notebook 81 | 82 | * In [Watson Studio](https://dataplatform.cloud.ibm.com/), click on `Create notebook` to create a notebook. 83 | * Create a project if necessary, provisioning an object storage service if required. 84 | * In the `Assets` tab, select the `Create notebook` option. 85 | * Select the `From URL` tab. 86 | * Enter a name for the notebook. 87 | * Optionally, enter a description for the notebook. 88 | * Enter this Notebook URL: https://github.com/IBM/graph-db-insights/blob/master/notebooks/graphdb-insights.ipynb 89 | * Select the free Anaconda runtime. 90 | * Click the `Create` button. 91 | 92 | ### 3.1. Additional notes for the notebook. 93 | * Before uploading the `config.json` configuration file to Object storage, make sure you update the config file with 94 | username and password that you have setup for orientdb in the first step `1. Deploy OrientDB on Kubernetes Cluster` 95 | 96 | ## 4. Add the data 97 | 98 | ##### Add the data to the notebook 99 | * Please download the files from : 100 | https://www.kaggle.com/deepmatrix/imdb-5000-movie-dataset . 101 | * Trim the data to 600 rows for the purpose of this tutorial and Rename the file  `Graphdb-Insights.csv` 102 | * From your project page in Watson Studio, click `Find and Add Data` (look for the `10/01` icon) 103 | and its `Files` tab. 104 | * Click `browse` and navigate to `Graphdb-Insights.csv` on your computer. 105 | * Add the files to Object storage. 106 | 107 | ![](doc/source/images/add_file.png) 108 | 109 | * Repeat the above steps to upload `config.json` Watson Studio configuration file to Object storage from URL: 110 | https://github.com/IBM/graph-db-insights/blob/master/configuration/config.json 111 | 112 | 113 | ## 5. Update the notebook with service credentials 114 | 115 | ##### Add the Object Storage credentials to the notebook 116 | * Use `Find and Add Data` (look for the `10/01` icon) and its `Files` tab. You should see the file names uploaded earlier. Make sure your active cell is the empty one created earlier. 117 | * Select `Insert to code` below config.json and click insert credentials from the dropdown. Please rename the variable to `credentials_1` if the name is different. 118 | * Select the cell below `3. Add your service credentials for Object Storage` section in the notebook to update the credentials for Object Store. 119 | 120 | ![](doc/source/images/config.png) 121 | 122 | * Select `Insert to code` below Graphdb-Insights.csv(movie dataset) and click Insert Pandas Dataframe from the dropdown in the empty cell below `4.2. Loading the IMDb movie data`. 123 | 124 | ![](doc/source/images/pandas.png) 125 | 126 | 127 | ## 6. Flow of the notebook 128 | The notebook has been divided into various sections with each section performing a specific task on the OrientDB. 129 | * `Setup` which deals with the installation of the OrientDB, importing the packages and libraries, adding the credentials of the files from object storage and loading them in the notebook for use. 130 | * `Utility Functions and Core functions` The notebook creates a graph with two node classes- `person` class and `movie` class. With person class as its attributes as: `name`, `fblikes`, `role(actor/ director)` and movie class as its attributes as: `title`, `year`, `durationInMins`, `imdbRating`, `genre`, `plotKeywords`, `numCriticForReviews`, `movieFacebookLikes`. There are two types of relationships involved in connecting the nodes, one is `worked_with`, which is between the two person nodes who have worked togther in the same movie and another one is `acted_in`, which between a person node and movie node for a person who have acted in a particular movie. The utility functions are written to keep a check on the duplicacy as `IF NOT EXISTS` is only valid for creating the properties in the OrientDB. Unlike in SQL, `IF NOT EXISTS` doesn't work with `create class` or `insert` statements in OrientDB. The core functions are for creating database, creating graph as discussed, and get insights from the graph created. 131 | * `Insights and Visualization` which focuses on performing various operations on and get insights from the OrientDB database. 132 | 133 | 134 | ## 7. Run the notebook 135 | 136 | When a notebook is executed, what is actually happening is that each code cell in 137 | the notebook is executed, in order, from top to bottom. 138 | 139 | Each code cell is selectable and is preceded by a tag in the left margin. The tag 140 | format is `In [x]:`. Depending on the state of the notebook, the `x` can be: 141 | 142 | * A blank, this indicates that the cell has never been executed. 143 | * A number, this number represents the relative order this code step was executed. 144 | * A `*`, this indicates that the cell is currently executing. 145 | 146 | There are several ways to execute the code cells in your notebook: 147 | 148 | * One cell at a time. 149 | * Select the cell, and then press the `Play` button in the toolbar. 150 | * Batch mode, in sequential order. 151 | * From the `Cell` menu bar, there are several options available. For example, you 152 | can `Run All` cells in your notebook, or you can `Run All Below`, that will 153 | start executing from the first cell under the currently selected cell, and then 154 | continue executing all cells that follow. 155 | * At a scheduled time. 156 | * Press the `Schedule` button located in the top right section of your notebook 157 | panel. Here you can schedule your notebook to be executed once at some future 158 | time, or repeatedly at your specified interval. 159 | 160 | For this Notebook, to run every cell one by one is recommended so as to understand the flow of the notebook and also to comprehend the operation performed by each cell on OrientDB better. 161 | 162 | ## 8. Analyze the results 163 | 164 | The notebook uses two use cases to demonstrate how to get insights from the OrientDB like `the most mentioned movie` and the `clustering of the movies with IMDb rating greater than 7`. Each insight has its own function in the notebook. Check the cell `Core Functions` in notebook, you will find the functions for the same. Call those functions to get the results. The following image shows the functions and its results. 165 | 166 | ![](doc/source/images/most_mentioned_notebook.png) 167 | 168 | OrientDB also provides an interactive dashboard OrientDB studio for visualization of the graph and to view the results of the queries. You can run the queries in the browse section of the OrientDB studio to get the desired insights or to create the node and Edges. The same two queries which the notebook uses i.e. `to get the most mentioned movie and the clustering of the movies with IMDb rating greater than 7` can be executed in the browse section of the OrientDB to analyze the results, check the screenshot of the OrientDB Studio below for the same. The results of the query executed are available in the form of table and JSON. And the results can also be downloaded as CSV for further analysis. 169 | 170 | #### * run the Query to `cluster the movies with IMDb rating greater than 7` and view the results in table format 171 | 172 | ![](doc/source/images/movie_rating.png) 173 | 174 | 175 | #### * run both the Queries to get the `most_mentioned` movie and view results in the form of the table 176 | 177 | ![](doc/source/images/most_mentioned.png) 178 | 179 | 180 | #### * run the Query for `most_mentioned` and view the results in the json format 181 | 182 | ![](doc/source/images/most_mentioned_json.png) 183 | 184 | To visualize the graph created by using the functions written in the notebook, 185 | * open the graph editor of the OrientDB Studio 186 | * execute the graph query in the graph editor. 187 | * results of the query will be in the form of the graph. For example, to find the connections of a node in the graphdb i.e. `to find the coworkers of the actor Tom Hanks `. 188 | 189 | ![](doc/source/images/worked_With.png) 190 | 191 | * You can follow this video tutorial on [OrientDB studio](https://www.youtube.com/watch?v=l-OVSjf-vk0&t=7s) created for the purpose of this notebook to demonstrate the results of the queries used in the tutorial. 192 | 193 | ## License 194 | 195 | This code pattern is licensed under the Apache Software License, Version 2. Separate third party code objects invoked within this code pattern are licensed by their respective providers pursuant to their own separate licenses. Contributions are subject to the [Developer Certificate of Origin, Version 1.1 (DCO)](https://developercertificate.org/) and the [Apache Software License, Version 2](https://www.apache.org/licenses/LICENSE-2.0.txt). 196 | 197 | [Apache Software License (ASL) FAQ](https://www.apache.org/foundation/license-faq.html#WhatDoesItMEAN) 198 | -------------------------------------------------------------------------------- /configuration/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "Database_name": "demo", 3 | "username": "root", 4 | "password": "rootpwd", 5 | "host": "localhost", 6 | "port": 2424, 7 | "vertex_class": { 8 | "person": { 9 | "name": "String", 10 | "role": "String", 11 | "fblikes": "Float" 12 | }, 13 | "movie": { 14 | "title": "String", 15 | "year": "Integer", 16 | "imdbRating": "Float", 17 | "durationInMins": "Integer", 18 | "genre": "String", 19 | "plotKeywords": "String", 20 | "numCriticForReviews": "Integer", 21 | "movieFacebookLikes": "Float" 22 | } 23 | }, 24 | "edge_class": { 25 | "acted_in": { 26 | "in":{ 27 | "Type": "Link", 28 | "Linked_Class": "movie" 29 | }, 30 | "out" :{ 31 | "Type": "Link", 32 | "Linked_Class": "person" 33 | } 34 | }, 35 | "worked_with": { 36 | "in":{ 37 | "Type": "Link", 38 | "Linked_Class": "person" 39 | }, 40 | "out" :{ 41 | "Type": "Link", 42 | "Linked_Class": "person" 43 | } 44 | 45 | } 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /data/README.md: -------------------------------------------------------------------------------- 1 | # Note 2 | 3 | Please download the data from - 4 | https://www.kaggle.com/deepmatrix/imdb-5000-movie-dataset 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /doc/source/images/Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/Architecture.png -------------------------------------------------------------------------------- /doc/source/images/THUMBNAILFORVIDEO.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/THUMBNAILFORVIDEO.jpg -------------------------------------------------------------------------------- /doc/source/images/add_file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/add_file.png -------------------------------------------------------------------------------- /doc/source/images/clustering_notebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/clustering_notebook.png -------------------------------------------------------------------------------- /doc/source/images/config.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/config.png -------------------------------------------------------------------------------- /doc/source/images/create_notebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/create_notebook.png -------------------------------------------------------------------------------- /doc/source/images/most_mentioned.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/most_mentioned.png -------------------------------------------------------------------------------- /doc/source/images/most_mentioned_json.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/most_mentioned_json.png -------------------------------------------------------------------------------- /doc/source/images/most_mentioned_notebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/most_mentioned_notebook.png -------------------------------------------------------------------------------- /doc/source/images/movie_rating.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/movie_rating.png -------------------------------------------------------------------------------- /doc/source/images/pandas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/pandas.png -------------------------------------------------------------------------------- /doc/source/images/worked_With.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IBM/graph-db-insights/632847b9144394baa4b711f6daec799ed2b9752e/doc/source/images/worked_With.png -------------------------------------------------------------------------------- /notebooks/graphdb-insights.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "## Add, Modify and Retrieve data from OrientDB\n" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## 1. Install the PyOrient package" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "! pip install pyorient --user " 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": {}, 29 | "source": [ 30 | "** Now restart the kernel by choosing Kernel > Restart. **" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "metadata": {}, 36 | "source": [ 37 | "## 2. Import packages and libraries" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "import pyorient, json, pandas as pd\n", 47 | "import sys" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "metadata": {}, 53 | "source": [ 54 | "## 3. Add your service credentials for Object Storage\n", 55 | "* You must create Object Storage service on Bluemix. To access data in a file in Object Storage, you need the Object Storage authentication credentials. Insert the Object Storage authentication credentials as credentials_1 in the following cell after removing the current contents in the cell. Rename the variable to credentials_1 if the variable name is different. " 56 | ] 57 | }, 58 | { 59 | "cell_type": "code", 60 | "execution_count": null, 61 | "metadata": {}, 62 | "outputs": [], 63 | "source": [ 64 | "\n", 65 | "# @hidden_cell\n", 66 | "# The following code contains the credentials for a file in your IBM Cloud Object Storage.\n", 67 | "# You might want to remove those credentials before you share your notebook.\n", 68 | "credentials_1 = {\n", 69 | " 'IBM_API_KEY_ID': '',\n", 70 | " 'IAM_SERVICE_ID': '',\n", 71 | " 'ENDPOINT': '',\n", 72 | " 'IBM_AUTH_ENDPOINT': '',\n", 73 | " 'BUCKET': '',\n", 74 | " 'FILE': ''\n", 75 | "}\n" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [ 82 | "## 4. Loading the Configuration and Data Files" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": {}, 88 | "source": [ 89 | "### 4.1 Load the config.json from Object Storage" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "from botocore.client import Config\n", 99 | "import ibm_boto3\n", 100 | "\n", 101 | "cos = ibm_boto3.client('s3',\n", 102 | " ibm_api_key_id=credentials_1['IBM_API_KEY_ID'],\n", 103 | " ibm_service_instance_id=credentials_1['IAM_SERVICE_ID'],\n", 104 | " ibm_auth_endpoint=credentials_1['IBM_AUTH_ENDPOINT'],\n", 105 | " config=Config(signature_version='oauth'),\n", 106 | " endpoint_url=credentials_1['ENDPOINT'])\n", 107 | "\n", 108 | "\n", 109 | "'''Retrieve file from Cloud Object Storage'''\n", 110 | "fileobject = cos.get_object(Bucket=credentials_1['BUCKET'], Key=credentials_1['FILE'])['Body']\n", 111 | " \n", 112 | "\n", 113 | "'''Load the file contents into a Python string'''\n", 114 | "\n", 115 | "\n", 116 | "text = fileobject.read()\n", 117 | "\n", 118 | "# Decode UTF-8 bytes to Unicode, and convert single quotes \n", 119 | "# to double quotes to make it valid JSON\n", 120 | "text_json = text.decode('utf8').replace(\"'\", '\"')\n", 121 | "# print(text_json)\n", 122 | "# print('- ' * 20)\n", 123 | "\n", 124 | "# Load the JSON to a Python list & dump it back out as formatted JSON\n", 125 | "data = json.loads(text_json)\n", 126 | "node_data = json.dumps(data, indent=4, sort_keys=True)\n", 127 | "print(node_data)\n", 128 | "\n", 129 | "\n", 130 | "\n", 131 | "\n" 132 | ] 133 | }, 134 | { 135 | "cell_type": "markdown", 136 | "metadata": {}, 137 | "source": [ 138 | "### 4.2. Load the IMDb movie data from Object Storage" 139 | ] 140 | }, 141 | { 142 | "cell_type": "markdown", 143 | "metadata": {}, 144 | "source": [ 145 | "Insert the csv file as `Insert as pandas dataframe` and change the name of the dataframe df_data to imdb_df in the cell below" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": null, 151 | "metadata": {}, 152 | "outputs": [], 153 | "source": [] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "metadata": {}, 159 | "outputs": [], 160 | "source": [ 161 | "''' There are many rows and columns in the data that are empty. Hence, It is important to clean the data.\n", 162 | "All the empty rows and columns are dropped from the dataframe using dropna() function of pandas.'''\n", 163 | "\n", 164 | "imdb_df = imdb_df.dropna()\n", 165 | "imdb_df.head(10)" 166 | ] 167 | }, 168 | { 169 | "cell_type": "markdown", 170 | "metadata": {}, 171 | "source": [ 172 | "# 5. Connect to OrientDB\n", 173 | "* Uncomment the first line after entering the IP address of the Kubernetes cluster and the port. Make sure to put the IP address in the double quotes and replace the content in the angular brackets with node-port to avoid any syntax errors.\n" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": null, 179 | "metadata": { 180 | "scrolled": true 181 | }, 182 | "outputs": [], 183 | "source": [ 184 | "#client = pyorient.OrientDB(\"ip-address-of-the-kubernetes-cluster\",)\n", 185 | "print(client)\n", 186 | "\n", 187 | "# The session id username and password is global password that was set for orientDB\n", 188 | "session_id = client.connect(node_data['username'], node_data['password'])" 189 | ] 190 | }, 191 | { 192 | "cell_type": "markdown", 193 | "metadata": {}, 194 | "source": [ 195 | "## 6. Utility functions\n", 196 | "These methods return dataframes containing the existing information of the database based on a condition.\n", 197 | "* check_if_class_present_or_not.\n", 198 | "* check_if_person_already_present.\n", 199 | "* check_if_already_present_movie.\n", 200 | "* find_the_Cluster_id_of_a_class\n" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "def check_if_class_present_or_not(classname):\n", 210 | " '''This function checks if a class is present or not'''\n", 211 | " \n", 212 | " name=\"will be replaced by query result name\"\n", 213 | " query = \"SELECT FROM ( SELECT expand( classes ) FROM metadata:schema ) WHERE name = \" +'\"'+ classname + '\"'\n", 214 | " a = client.command(query)\n", 215 | " \n", 216 | " for k in a:\n", 217 | " name = k.name\n", 218 | " \n", 219 | " if(name == classname):\n", 220 | " return True\n", 221 | " else:\n", 222 | " return False\n", 223 | " \n", 224 | " \n", 225 | "def check_if_person_already_present():\n", 226 | " '''This function checks if the person already exists.'''\n", 227 | " \n", 228 | " check_if_already_present = \"select * from person\"\n", 229 | " c = client.command(check_if_already_present)\n", 230 | " d=[]\n", 231 | "\n", 232 | " for name in c:\n", 233 | " d.append([name.name, name.role, name.fblikes])\n", 234 | "\n", 235 | "\n", 236 | " check_df = pd.DataFrame(list(d), columns=['name','role','fblikes'])\n", 237 | " return check_df\n", 238 | "\n", 239 | "\n", 240 | "def check_if_already_present_movie():\n", 241 | " '''This function checks if the movie already exists.'''\n", 242 | " \n", 243 | " check_if_already_present = \"select title , year from movie\"\n", 244 | " c = client.command(check_if_already_present)\n", 245 | " \n", 246 | " d=[]\n", 247 | "\n", 248 | " for name in c:\n", 249 | " d.append([name.title, name.year])\n", 250 | "\n", 251 | "\n", 252 | " check_df_movie = pd.DataFrame(list(d), columns=['title','year'])\n", 253 | " return check_df_movie\n", 254 | "\n", 255 | "\n", 256 | "def find_the_Cluster_id_of_a_class(classname):\n", 257 | " '''This function finds the Cluster ID of the class.'''\n", 258 | " \n", 259 | " find_the_Cluster_id_of_a_class = \"SELECT defaultClusterId from (SELECT expand( classes ) FROM metadata:schema) where name = '\" + classname + \"'\"\n", 260 | " c = client.command(find_the_Cluster_id_of_a_class)\n", 261 | " for ids in c:\n", 262 | " return ids.defaultClusterId\n", 263 | "\n", 264 | "\n" 265 | ] 266 | }, 267 | { 268 | "cell_type": "markdown", 269 | "metadata": {}, 270 | "source": [ 271 | "## 7. Core Functions\n", 272 | "These are the core functions of the notebook performing operations on OrientDB:\n", 273 | "* Create Database.\n", 274 | "* Create node class with its properties as per defined in config.json.\n", 275 | "* Create node class when no schema defined.\n", 276 | "* Create edge class.\n", 277 | "* Create vertices/nodes with movie data.\n", 278 | "* Create relations between these nodes.\n", 279 | "* Create vertices for usecases where schema is indefinte.\n", 280 | "* Other insights like :\n", 281 | " * Most mentioned movie.\n", 282 | " * Movies with rating above 7.\n" 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": null, 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "def createDatabase(node_data):\n", 292 | " '''This function the database if it does not already exist.'''\n", 293 | " \n", 294 | " if client.db_exists( node_data['Database_name'], pyorient.STORAGE_TYPE_MEMORY ):\n", 295 | " client.db_open(node_data['Database_name'],node_data['username'], node_data['password'])\n", 296 | " print \"The Database \" + node_data['Database_name'] + \" \"+ \"has already been created and opened for use.\"\n", 297 | " else: \n", 298 | " client.db_create( node_data['Database_name'], pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY )\n", 299 | " print \"The Database \" + node_data['Database_name'] + \" created and opened successfully\"\n", 300 | " \n", 301 | "\n", 302 | "def createNodeClass_withSchema(node_data):\n", 303 | " '''This function creates a Node Class with a schema.'''\n", 304 | " \n", 305 | " for class_name,value in node_data['vertex_class'].items():\n", 306 | " bool_result = check_if_class_present_or_not(class_name)\n", 307 | " if(not bool_result):\n", 308 | " command_to_create_node = \"create class\"+\" \"+ class_name +\" \"+ \"extends V\"\n", 309 | " cluster_id = client.command(command_to_create_node) \n", 310 | " for property_name,value in node_data['vertex_class'][class_name].items():\n", 311 | " command_to_create_property= \"create property\"+ \" \"+ class_name +\".\" + property_name +\" \" +\"IF NOT EXISTS \" + value\n", 312 | " client.command(command_to_create_property) \n", 313 | " print \"The class \" + class_name + \" and its properties have been created successfully.\"\n", 314 | " else:\n", 315 | " print \"The class \" + class_name + \" has been created already.\"\n", 316 | "\n", 317 | "def createNodeClass_NoSchema(node_data):\n", 318 | " '''This function creates a Node Class with no schema.'''\n", 319 | " \n", 320 | " for class_name,value in node_data['vertex_class'].items():\n", 321 | " if(check_if_class_present_or_not(class_name)):\n", 322 | " command_to_create_node = \"create class\"+\" \"+ class_name +\" \"+ \"extends V\"\n", 323 | " cluster_id = client.command(command_to_create_node) \n", 324 | " print \"The class \" + class_name + \" has been created with cluster id \" +cluster_id\n", 325 | " else:\n", 326 | " print \"The class \" + class_name + \" has been created already.\"\n", 327 | " \n", 328 | "\n", 329 | "def createEdgeClass(node_data):\n", 330 | " '''This function checks if the edge class is already present.'''\n", 331 | " \n", 332 | " for class_name,v in node_data['edge_class'].items(): \n", 333 | " if(not check_if_class_present_or_not(class_name)):\n", 334 | " command_to_create_edge_class = \"create class\"+\" \"+ class_name +\" \"+ \"extends E\"\n", 335 | " cluster_id = client.command(command_to_create_edge_class)\n", 336 | " print(\"The Edge class\" +\" \" + class_name + \" has been created successfully.\")\n", 337 | "\n", 338 | " for key,val in node_data['edge_class'][class_name].items():\n", 339 | " command_to_create_property= \"create property\"+ \" \"+ class_name +\".\" + key +\" \" +\"IF NOT EXISTS \" + node_data['edge_class'][class_name][key]['Type']+\" \" + node_data['edge_class'][class_name][key]['Linked_Class']\n", 340 | " client.command(command_to_create_property) \n", 341 | " else:\n", 342 | " print(\"The Edge class\" +\" \" + class_name + \" already exists.\")\n", 343 | " \n", 344 | "\n", 345 | "def creating_records(imdb_df):\n", 346 | " '''Create records in the database if it does not exist.'''\n", 347 | " \n", 348 | " for index, row in imdb_df.iterrows():\n", 349 | " check_df = check_if_person_already_present()\n", 350 | " if(any(check_df.name == row[\"actor_1_name\"])):\n", 351 | " print \"Node \"+row[\"actor_1_name\"] +\" is already present.\"\n", 352 | " else:\n", 353 | " command_to_create_actor_1_node_class_person = \"INSERT INTO person (name, fblikes, role) VALUES (\" +'\"' +row[\"actor_1_name\"]+'\"' + ','+ str(row[\"actor_1_facebook_likes\"])+',' +'\"' +'actor'+'\"' + \")\"\n", 354 | " client.command(command_to_create_actor_1_node_class_person)\n", 355 | " \n", 356 | " if(any(check_df.name == row[\"actor_2_name\"])):\n", 357 | " print \"Node \"+row[\"actor_2_name\"] +\" is already present.\"\n", 358 | " else:\n", 359 | " command_to_create_actor_2_node_class_person = \"INSERT INTO person (name, fblikes, role) VALUES (\" +'\"' +row[\"actor_2_name\"]+'\"' + ','+ str(row[\"actor_2_facebook_likes\"])+',' +'\"' +'actor'+'\"' + \")\"\n", 360 | " client.command(command_to_create_actor_2_node_class_person)\n", 361 | " \n", 362 | " if(any(check_df.name == row[\"actor_3_name\"])):\n", 363 | " print \"Node \"+row[\"actor_3_name\"] +\" is already present.\"\n", 364 | " else:\n", 365 | " command_to_create_actor_3_node_class_person = \"INSERT INTO person (name, fblikes, role) VALUES (\" +'\"' +row[\"actor_3_name\"]+'\"' + ','+ str(row[\"actor_3_facebook_likes\"])+',' +'\"' +'actor'+'\"' + \")\"\n", 366 | " client.command(command_to_create_actor_3_node_class_person)\n", 367 | " \n", 368 | " if(any(check_df.name == row[\"director_name\"])):\n", 369 | " print \"Node \"+row[\"director_name\"] +\" is already present.\"\n", 370 | " else:\n", 371 | " command_to_create_director_node_class_person = \"INSERT INTO person (name, fblikes, role) VALUES (\" +'\"' +row[\"director_name\"]+'\"' + ','+ str(row[\"director_facebook_likes\"])+',' +'\"' +'director'+'\"' + \")\"\n", 372 | " client.command(command_to_create_director_node_class_person)\n", 373 | " \n", 374 | " command_to_create_movie = \"INSERT INTO movie (title, year, durationInMins, imdbRating, genre, plotKeywords, numCriticForReviews, movieFacebookLikes) VALUES (\" +'\"' +row[\"movie_title\"]+'\"' + ','+ str(row[\"title_year\"])+','+str(row[\"duration\"])+','+str(row[\"imdb_score\"])+',' +'\"'+row[\"genres\"]+'\"' +','+'\"' +row[\"plot_keywords\"]+'\"'+','+str(row[\"num_critic_for_reviews\"])+','+str(row[\"movie_facebook_likes\"])+\")\"\n", 375 | " client.command(command_to_create_movie)\n", 376 | " \n", 377 | " \n", 378 | "\n", 379 | " \n", 380 | "def createRelationships():\n", 381 | " '''This function creates relationships.''' \n", 382 | " \n", 383 | " check_df = check_if_person_already_present()\n", 384 | " check_df_movie = check_if_already_present_movie()\n", 385 | " \n", 386 | " for index, row in imdb_df.iterrows():\n", 387 | " # Create an edge between actors_1 and actor_2.\n", 388 | " if((row[\"actor_1_name\"] in check_df.name.values) and (row[\"actor_2_name\"] in check_df.name.values)):\n", 389 | " command_to_create_edge_between_two_actors_1_and_2 = \"create edge worked_with from (select from person where name = \"+'\"'+row[\"actor_1_name\"]+'\"'+ \")\"+\" \" +\"to (select from person where name = \"+'\"'+row[\"actor_2_name\"]+'\"'+\")\"\n", 390 | " client.command(command_to_create_edge_between_two_actors_1_and_2) \n", 391 | " else:\n", 392 | " print \"Edge cant be created because vertex is not present.\", row[\"actor_1_name\"], \",\",row[\"actor_2_name\"] \n", 393 | "\n", 394 | "\n", 395 | " # Create an edge between actors_2 and actor_3.\n", 396 | " if((row[\"actor_2_name\"] in check_df.name.values) and (row[\"actor_3_name\"] in check_df.name.values) ):\n", 397 | " command_to_create_edge_between_two_actors_2_and_3 = \"create edge worked_with from (select from person where name = \"+'\"'+row[\"actor_2_name\"]+'\"'+ \")\"+\" \" +\"to (select from person where name = \"+'\"'+row[\"actor_3_name\"]+'\"'+\")\"\n", 398 | " client.command(command_to_create_edge_between_two_actors_2_and_3) \n", 399 | " else:\n", 400 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_2_name\"], \",\",row[\"actor_3_name\"]\n", 401 | "\n", 402 | "\n", 403 | " # Create an edge between actors_3 and actor_1.\n", 404 | " if((row[\"actor_3_name\"] in check_df.name.values) and ( row[\"actor_1_name\"] in check_df.name.values )):\n", 405 | " command_to_create_edge_between_two_actors_3_and_1 = \"create edge worked_with from (select from person where name = \"+'\"'+row[\"actor_3_name\"]+'\"'+ \")\"+\" \" +\"to (select from person where name = \"+'\"'+row[\"actor_1_name\"]+'\"'+\")\"\n", 406 | " client.command(command_to_create_edge_between_two_actors_3_and_1) \n", 407 | " else:\n", 408 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_2_name\"], \",\",row[\"actor_3_name\"]\n", 409 | "\n", 410 | " # Create an edge between actors_1 and director.\n", 411 | " if((row[\"actor_1_name\"] in check_df.name.values) and (row[\"director_name\"] in check_df.name.values) ):\n", 412 | " command_to_create_edge_between_actor_1_and_director = \"create edge worked_with from (select from person where name = \"+'\"'+row[\"director_name\"]+'\"'+ \")\"+\" \" +\"to (select from person where name = \"+'\"'+row[\"actor_1_name\"]+'\"'+\")\"\n", 413 | " client.command(command_to_create_edge_between_actor_1_and_director)\n", 414 | " else:\n", 415 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_1_name\"], \",\",row[\"director_name\"]\n", 416 | "\n", 417 | " # Create an edge between actors_2 and director.\n", 418 | " if((row[\"actor_2_name\"] in check_df.name.values) and ( row[\"director_name\"] in check_df.name.values) ):\n", 419 | " command_to_create_edge_between_actor_2_and_director = \"create edge worked_with from (select from person where name = \"+'\"'+row[\"director_name\"]+'\"'+ \")\"+\" \" +\"to (select from person where name = \"+'\"'+row[\"actor_2_name\"]+'\"'+\")\"\n", 420 | " client.command(command_to_create_edge_between_actor_2_and_director)\n", 421 | " else:\n", 422 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_2_name\"], \",\",row[\"director_name\"]\n", 423 | "\n", 424 | " # Create an edge between actors_3 and director.\n", 425 | " if((row[\"actor_3_name\"] in check_df.name.values) and ( row[\"director_name\"] in check_df.name.values) ):\n", 426 | " command_to_create_edge_between_actor_3_director = \"create edge worked_with from (select from person where name = \"+'\"'+row[\"director_name\"]+'\"'+ \")\"+\" \" +\"to (select from person where name = \"+'\"'+row[\"actor_3_name\"]+'\"'+\")\"\n", 427 | " client.command(command_to_create_edge_between_actor_3_director)\n", 428 | " else:\n", 429 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_3_name\"], \",\",row[\"director_name\"]\n", 430 | "\n", 431 | " # Create an edge between actors_1 and movie.\n", 432 | " if((row[\"actor_1_name\"] in check_df.name.values) and (row[\"movie_title\"] in check_df_movie.title.values)):\n", 433 | " command_to_create_edge_between_actors_1_and_movie = \"create edge acted_in from (select from person where name = \"+'\"'+row[\"actor_1_name\"]+'\"'+ \")\"+\" \" +\"to (select from movie where title = \"+'\"'+row[\"movie_title\"]+'\"'+\")\"\n", 434 | " client.command(command_to_create_edge_between_actors_1_and_movie)\n", 435 | " else:\n", 436 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_1_name\"], \",\",row[\"movie_title\"]\n", 437 | "\n", 438 | " # Create an edge between actors_2 and movie.\n", 439 | " if((row[\"actor_2_name\"] in check_df.name.values) and (row[\"movie_title\"] in check_df_movie.title.values) ):\n", 440 | " command_to_create_edge_between_actors_2_and_movie = \"create edge acted_in from (select from person where name = \"+'\"'+row[\"actor_2_name\"]+'\"'+ \")\"+\" \" +\"to (select from movie where title = \"+'\"'+row[\"movie_title\"]+'\"'+\")\"\n", 441 | " client.command(command_to_create_edge_between_actors_2_and_movie)\n", 442 | " else:\n", 443 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_2_name\"], \",\",row[\"movie_title\"]\n", 444 | "\n", 445 | " # Create an edge between actors_3 and movie.\n", 446 | " if((row[\"actor_3_name\"] in check_df.name.values) and (row[\"movie_title\"] in check_df_movie.title.values)):\n", 447 | " command_to_create_edge_between_actors_3_and_movie = \"create edge acted_in from (select from person where name = \"+'\"'+row[\"actor_3_name\"]+'\"'+ \")\"+\" \" +\"to (select from movie where title= \"+'\"'+row[\"movie_title\"]+'\"'+\")\"\n", 448 | " client.command(command_to_create_edge_between_actors_3_and_movie)\n", 449 | " else:\n", 450 | " print \"Edge cant be created because one or both the vertices is not present -\",row[\"actor_3_name\"], \",\",row[\"movie_title\"]\n", 451 | "\n", 452 | " \n", 453 | "\n", 454 | "def creating_records_noschema(data):\n", 455 | " '''This function creates records with no schema.'''\n", 456 | " \n", 457 | " id = client.record_create(cluster_id, data)\n", 458 | " print \"Record succesfully created with \" + str(id)\n", 459 | " \n", 460 | "\n", 461 | "\n", 462 | "def most_mentioned_movie():\n", 463 | " '''This function retrieves the most mentioned movies.'''\n", 464 | " \n", 465 | " a = client.command(('select max(movieFacebookLikes) from movie '))\n", 466 | "\n", 467 | " for max_num in a :\n", 468 | " max_num = max_num.max\n", 469 | " \n", 470 | " most_mentioned_movie_object = client.command('select title from movie where movieFacebookLikes = ' + str(max_num))\n", 471 | " \n", 472 | " return most_mentioned_movie_object \n", 473 | " \n", 474 | "\n", 475 | "def movie_with_imdb_rating_above_7():\n", 476 | " '''This function retrieves the movies with IMDb rating > 7.'''\n", 477 | " \n", 478 | " title = []\n", 479 | " a = client.command(('select title from movie where imdbRating > 7 '))\n", 480 | " for titles in a :\n", 481 | " title.append(titles.title)\n", 482 | " title_df = pd.DataFrame(list(title), columns=['title']) \n", 483 | " return title_df\n", 484 | " \n", 485 | "\n", 486 | " " 487 | ] 488 | }, 489 | { 490 | "cell_type": "markdown", 491 | "metadata": {}, 492 | "source": [ 493 | "## 8. Perform operations on OrientDB" 494 | ] 495 | }, 496 | { 497 | "cell_type": "markdown", 498 | "metadata": {}, 499 | "source": [ 500 | "### 8.1 Create Database, Node classes, Edge classes, and Records" 501 | ] 502 | }, 503 | { 504 | "cell_type": "code", 505 | "execution_count": null, 506 | "metadata": {}, 507 | "outputs": [], 508 | "source": [ 509 | "# Create Database\n", 510 | "print \"\"\n", 511 | "print \"Creating database...\"\n", 512 | "createDatabase(node_data)\n", 513 | "print \"Database creation successful.\"\n", 514 | "\n", 515 | "# Create Node class with schema\n", 516 | "print \"\"\n", 517 | "print \"Creating Node classes with schema...\"\n", 518 | "createNodeClass_withSchema(node_data)\n", 519 | "print \"Node classes with schema creation successful.\"\n", 520 | "\n", 521 | "# Create Edge class\n", 522 | "print \"\"\n", 523 | "print \"Creating Edge classes...\"\n", 524 | "createEdgeClass(node_data)\n", 525 | "print \"Edge classes creation successful.\"\n", 526 | "\n", 527 | "# Create records\n", 528 | "print \"\"\n", 529 | "print \"Creating records...\"\n", 530 | "creating_records(imdb_df)\n", 531 | "print \"Records creation successful.\"\n", 532 | "\n", 533 | "# Create Relationships\n", 534 | "print \"\"\n", 535 | "print \"Creating relationships...\"\n", 536 | "createRelationships()\n", 537 | "print \"Relationships creation successful.\"\n" 538 | ] 539 | }, 540 | { 541 | "cell_type": "markdown", 542 | "metadata": {}, 543 | "source": [ 544 | "### 8.2 Create the records for the scenario where there is no schema defined" 545 | ] 546 | }, 547 | { 548 | "cell_type": "code", 549 | "execution_count": null, 550 | "metadata": {}, 551 | "outputs": [], 552 | "source": [ 553 | "data = {\n", 554 | " 'person': {\n", 555 | " \"name\": \"John\", \n", 556 | " \"role\": \"director\",\n", 557 | " \"fblikes\": 400000.0,\n", 558 | " \"born_in\" : 1980\n", 559 | " },\n", 560 | " }\n", 561 | "# Get cluster id\n", 562 | "for key, value in data.iteritems():\n", 563 | " cluster_id = find_the_Cluster_id_of_a_class(key)\n", 564 | " print \"Cluster Id:\",cluster_id\n", 565 | "\n", 566 | "# Create record that has no schema\n", 567 | "creating_records_noschema(data)" 568 | ] 569 | }, 570 | { 571 | "cell_type": "markdown", 572 | "metadata": {}, 573 | "source": [ 574 | "### 8.3 Insights from OrientDB" 575 | ] 576 | }, 577 | { 578 | "cell_type": "code", 579 | "execution_count": null, 580 | "metadata": {}, 581 | "outputs": [], 582 | "source": [ 583 | "most_mentioned_movie = most_mentioned_movie()\n", 584 | "print \"Most mentioned movies\"\n", 585 | "for titles in most_mentioned_movie:\n", 586 | " print titles.title\n", 587 | "print \"\" \n", 588 | "\n", 589 | "movie_with_imdb_rating_above_7 = movie_with_imdb_rating_above_7()\n", 590 | "print \"Movies with IMDb rating > 7:\"\n", 591 | "print movie_with_imdb_rating_above_7" 592 | ] 593 | }, 594 | { 595 | "cell_type": "markdown", 596 | "metadata": {}, 597 | "source": [ 598 | "## 9. Visualisation of results\n", 599 | "You can open OrientDB studio and execute the queries in the graph editor of OrientDB to view the graph you have built.\n", 600 | "Watch this video : https://www.youtube.com/watch?v=l-OVSjf-vk0&t=4s for OrientDB tutorial." 601 | ] 602 | }, 603 | { 604 | "cell_type": "markdown", 605 | "metadata": {}, 606 | "source": [ 607 | "\n" 608 | ] 609 | } 610 | ], 611 | "metadata": { 612 | "kernelspec": { 613 | "display_name": "Python 3.5", 614 | "language": "python", 615 | "name": "python3" 616 | }, 617 | "language_info": { 618 | "codemirror_mode": { 619 | "name": "ipython", 620 | "version": 3 621 | }, 622 | "file_extension": ".py", 623 | "mimetype": "text/x-python", 624 | "name": "python", 625 | "nbconvert_exporter": "python", 626 | "pygments_lexer": "ipython3", 627 | "version": "3.5.4" 628 | } 629 | }, 630 | "nbformat": 4, 631 | "nbformat_minor": 2 632 | } 633 | --------------------------------------------------------------------------------