OrientDB Manual Orient DB Manual(3.X)
User Manual: Pdf
Open the PDF directly: View PDF
.
Page Count: 1452
| Download | |
| Open PDF In Browser | View PDF |
Table of Contents
Home
1.1
FIRST STEPS
Introduction
2.1
About This M anual
2.1.1
Overview of OrientDB
2.1.2
Editions
Release 3.0
2.1.2.1
2.1.3
What's new in OrientDB 3.0?
2.1.3.1
Available Packages
2.1.3.2
SQL Changes
2.1.3.3
API Changes
2.1.3.4
Known Issues
2.1.3.5
Upgrading to OrientDB 3.0
2.1.3.6
How to Report Bugs or Problems
2.1.4
How to Get in Touch with OrientDB
2.1.5
How to Contribute to OrientDB
2.1.6
OrientDB Roadmap
2.1.7
OrientDB in Five M inutes
2.2
Install
2.2.1
Create a DB
2.2.2
Create the Java Application
2.2.3
Connect to the DB and create the Schema
2.2.4
Create your First Graph and Run Queries
2.2.5
Getting Started
2.3
Installation
2.3.1
Run the server
2.3.2
Run the console
2.3.3
Run the Studio
2.3.4
Documents, Vertices and Edges
2.3.5
Classes, Schema and Constraints
2.3.6
Demo Database
2.3.7
Introduction
2.3.7.1
Data M odel
2.3.7.2
Queries
2.3.7.3
Profiles
2.3.7.3.1
Friendship
2.3.7.3.2
Customers
2.3.7.3.3
Countries
2.3.7.3.4
Orders
2.3.7.3.5
1
Attractions
2.3.7.3.6
Services
2.3.7.3.7
Locations
2.3.7.3.8
Reviews
2.3.7.3.9
Recommendations
2.3.7.3.10
Business Opportunities
2.3.7.3.11
Polymorphism
2.3.7.3.12
Shortest Paths
2.3.7.3.13
Traverses
2.3.7.3.14
Graph Portions
2.3.7.4
Basic SQL
2.3.8
Users, Roles and Security
2.3.9
Distributed Architecture
2.3.10
Tutorials
2.3.11
Working with Graphs
2.3.11.1
Using Schema with Graphs
2.3.11.2
Setup a Distributed Database
2.3.11.3
Working with Distributed Graphs
2.3.11.4
Time Series
2.3.11.5
Chat
2.3.11.6
Key Value
2.3.11.7
Queue system
2.3.11.8
Import Tutorials
2.3.11.9
Importing the Open Beer Database into OrientDB
2.3.11.9.1
Importing the northwind Database from Neo4j
2.3.11.9.2
Importing the movie Database from Neo4j
2.3.11.9.3
General Information
2.4
Supported Types
2.4.1
Schema
2.4.2
Inheritance
2.4.3
Concurrency
2.4.4
Indexing
2.4.5
SB-Tree
2.4.5.1
Hash
2.4.5.2
Auto-Sharding
2.4.5.3
Full Text
2.4.5.4
Lucene Full Text
2.4.5.5
Lucene Spatial Index
2.4.5.6
M anaging Dates
2.4.6
Transactions
2.4.7
Embedding the Server
2.4.8
Available OrientDB Plugins
2.4.9
Automatic Backup
2.4.9.1
SysLog
2.4.9.2
2
M ail
2.4.9.3
JM X
2.4.9.4
Rexster
2.4.9.5
Gephi Graph Render
2.4.9.6
spider-box
2.4.9.7
3rd Party Plugins
2.4.9.8
Data M odeling
2.5
M ulti Tenant
2.5.1
Basic Concepts
2.5.2
CORE TOPICS
OrientDB Programs
3.1
OrientDB Server-Startup Programs
3.1.1
server
3.1.1.1
dserver
3.1.1.2
orientdb
3.1.1.3
OrientDB Client Programs
Console
3.1.2
3.1.2.1
Console M odes
3.1.2.1.1
Console Commands
3.1.2.1.2
Backup
3.1.2.1.2.1
Browse Class
3.1.2.1.2.2
Browse Cluster
3.1.2.1.2.3
List Classes
3.1.2.1.2.4
Cluster Status
3.1.2.1.2.5
List Clusters
3.1.2.1.2.6
List Servers
3.1.2.1.2.7
List Server Users
3.1.2.1.2.8
Check Database
3.1.2.1.2.9
Config
3.1.2.1.2.10
Config Get
3.1.2.1.2.11
Config Set
3.1.2.1.2.12
Connect
3.1.2.1.2.13
Create Database
3.1.2.1.2.14
Declare Intent
3.1.2.1.2.15
Dictionary Get
3.1.2.1.2.16
Dictionary Keys
3.1.2.1.2.17
Dictionary Put
3.1.2.1.2.18
Dictionary Remove
3.1.2.1.2.19
Disconnect
3.1.2.1.2.20
Display Record
3.1.2.1.2.21
Display Raw Record
3.1.2.1.2.22
Drop Database
3.1.2.1.2.23
Drop Server User
3.1.2.1.2.24
3
Export Database
3.1.2.1.2.25
Export Record
3.1.2.1.2.26
Freeze DB
3.1.2.1.2.27
Get
3.1.2.1.2.28
Import Database
3.1.2.1.2.29
Indexes
3.1.2.1.2.30
Info
3.1.2.1.2.31
Info Class
3.1.2.1.2.32
Info Property
3.1.2.1.2.33
Js
3.1.2.1.2.34
Jss
3.1.2.1.2.35
List Databases
3.1.2.1.2.36
List Connections
3.1.2.1.2.37
Load Record
3.1.2.1.2.38
Load Script
3.1.2.1.2.39
Profiler
3.1.2.1.2.40
Properties
3.1.2.1.2.41
Release DB
3.1.2.1.2.42
Reload Record
3.1.2.1.2.43
Repair Database
3.1.2.1.2.44
Restore
3.1.2.1.2.45
Set
3.1.2.1.2.46
Set Server User
3.1.2.1.2.47
Custom Console Commands
OrientDB Administrative and Utility Programs
3.1.2.1.3
3.1.3
backup
3.1.3.1
shutdown
3.1.3.2
stresstester
3.1.3.3
OrientDB Data Import Programs
3.1.4
orientdb-neo4j-importer
3.1.4.1
oetl
3.1.4.2
OrientDB Server Administration
Installation
3.2
3.2.1
Prerequisites
3.2.1.1
Installation from Source
3.2.1.2
Install as Service on Unix
3.2.1.3
Install as Service on Windows
3.2.1.4
Install with Docker
3.2.1.5
Configuration
3.2.2
Upgrade
3.2.3
Backward Compatibility
3.2.3.1
Upgrading a Distributed Environment
3.2.3.2
Logs
3.2.4
Event Scheduler
3.2.5
4
Functions
3.2.6
Creating Functions
3.2.6.1
Using Functions
3.2.6.2
Accessing the Database
3.2.6.3
Server-side Functions
3.2.6.4
Backup and Restore
Incremental Backup and Restore
Export and Import
3.2.7
3.2.7.1
3.2.8
Export to & Import from JSON
Export format
Import From RDBM S
3.2.8.1
3.2.8.1.1
3.2.8.2
To Document M odel
3.2.8.2.1
To Graph M odel
3.2.8.2.2
Import From Neo4j
Import from Neo4j using GraphM L
M onitoring
3.2.8.3
3.2.8.3.1
3.2.9
JM X
3.2.9.1
OrientDB Tools
3.3
Studio
3.3.1
Introduction
3.3.1.1
Overview of M enus and Panels
3.3.1.2
Working with Databases
3.3.1.3
Common Database Operations
3.3.1.3.1
Database M anagement Panel
3.3.1.3.2
Working with Data
3.3.1.4
Browse Panel
3.3.1.4.1
Querying Data
3.3.1.4.1.1
M odifying Data
3.3.1.4.1.2
Edit Document
3.3.1.4.1.2.1
Edit Vertex
3.3.1.4.1.2.2
Edit Edge
3.3.1.4.1.2.3
Graph Editor
Working with Schemas
3.3.1.4.2
3.3.1.5
Schema M anager Panel
3.3.1.5.1
Classes
3.3.1.5.2
Properties
3.3.1.5.3
Indexes
3.3.1.5.4
Working with Functions
Functions M anagement Panel
Working with Users and Roles
3.3.1.6
3.3.1.6.1
3.3.1.7
Security M anager Panel
3.3.1.7.1
Users M anagement
3.3.1.7.2
Roles M anagement
3.3.1.7.3
Backups, Imports and Exports
3.3.1.8
5
Backup M anagement Panel
3.3.1.8.1
Integration with Teleporter
3.3.1.8.2
Integration with the Neo4j to OrientDB Importer
3.3.1.8.3
Server M anagement
3.3.1.9
Dashboard Panel
3.3.1.9.1
Servers M anagement Panel
3.3.1.9.2
Cluster M anagement Panel
3.3.1.9.3
Data Centers
3.3.1.9.3.1
Query Profiler Panel
3.3.1.9.4
Security Panel
3.3.1.9.5
Server Auditing
Alerts M anagement Panel
3.3.1.9.5.1
3.3.1.9.6
Studio Backup M anagement
3.3.1.10
Teleporter
3.3.1.11
Neo4j to OrientDB Importer
3.3.1.12
Teleporter
3.3.2
Installation and configuration
3.3.2.1
Execution strategies
3.3.2.2
Sequential executions and One-Way Synchronizer
3.3.2.3
Import filters
3.3.2.4
Inheritance
3.3.2.5
Single Table Inheritance
3.3.2.5.1
Table Per Class Inheritance
3.3.2.5.2
Table Per Concrete Class Inheritance
3.3.2.5.3
Import Configuration
ETL
3.3.2.6
3.3.3
Configuration
3.3.3.1
Blocks
3.3.3.2
Sources
3.3.3.3
Extractors
3.3.3.4
Transformers
3.3.3.5
Loaders
3.3.3.6
Import from CSV to a Graph
3.3.3.7
Import a tree structure
3.3.3.8
Import from JSON
3.3.3.9
Import from RDBM S
3.3.3.10
Import from DB-Pedia
3.3.3.11
Import from Parse (Facebook)
3.3.3.12
Neo4j to OrientDB Importer
3.3.4
SQL, API, DRIVERS
SQL Reference
Introduction
Querying M etadata
4.1
4.1.1
4.1.1.1
6
SQL Syntax
4.1.2
Projections
4.1.2.1
SQL Commands
4.1.3
Alter Class
4.1.3.1
Alter Cluster
4.1.3.2
Alter Database
4.1.3.3
Alter Property
4.1.3.4
Alter Sequence
4.1.3.5
Create Class
4.1.3.6
Create Cluster
4.1.3.7
Create Edge
4.1.3.8
Create Function
4.1.3.9
Create Index
4.1.3.10
Create Link
4.1.3.11
Create Property
4.1.3.12
Create Sequence
4.1.3.13
Create User
4.1.3.14
Create Vertex
4.1.3.15
Delete
4.1.3.16
Delete Edge
4.1.3.17
Delete Vertex
4.1.3.18
Drop Class
4.1.3.19
Drop Cluster
4.1.3.20
Drop Index
4.1.3.21
Drop Property
4.1.3.22
Drop Sequence
4.1.3.23
Drop User
4.1.3.24
Explain
4.1.3.25
Find References
4.1.3.26
Grant
4.1.3.27
HA Remove Server
4.1.3.28
HA Status
4.1.3.29
HA Sync Cluster
4.1.3.30
HA Sync Database
4.1.3.31
HA Set
4.1.3.32
Insert
4.1.3.33
Live Select
4.1.3.34
Live Unsubscribe
4.1.3.35
M atch
4.1.3.36
M ove Vertex
4.1.3.37
Optimize Database
4.1.3.38
Profile
4.1.3.39
Rebuild Index
4.1.3.40
Revoke
4.1.3.41
7
Select
4.1.3.42
Traverse
4.1.3.43
Truncate Class
4.1.3.44
Truncate Cluster
4.1.3.45
Truncate Record
4.1.3.46
Update
4.1.3.47
Update Edge
4.1.3.48
Filtering
4.1.4
Functions
4.1.5
M ethods
4.1.6
Batch
4.1.7
Pagination
4.1.8
Sequences and auto increment
4.1.9
Pivoting with Query
4.1.10
Command Cache
4.1.11
APIs and Drivers
4.2
Java API
4.2.1
Java M ulti-M odel API
4.2.1.1
Database creation and connection
4.2.1.1.1
M anipulating data in Java
4.2.1.1.2
Running SQL statements Java
4.2.1.1.3
Defining Database Schema
4.2.1.1.4
Classes
4.2.1.1.4.1
Property
4.2.1.1.4.2
Reference
4.2.1.2
OClass
4.2.1.2.1
addCluster()
4.2.1.2.1.1
addClusterId()
4.2.1.2.1.2
addSuperClass()
4.2.1.2.1.3
count()
4.2.1.2.1.4
createIndex()
4.2.1.2.1.5
createProperty()
4.2.1.2.1.6
dropProperty()
4.2.1.2.1.7
existsProperty()
4.2.1.2.1.8
getAllSubclasses()
4.2.1.2.1.9
getAllSuperClasses()
4.2.1.2.1.10
getAutoShardingIndex()
4.2.1.2.1.11
getClassIndex()
4.2.1.2.1.12
getClassIndexes()
4.2.1.2.1.13
getClassInvolvedIndexes()
4.2.1.2.1.14
getClusterIds()
4.2.1.2.1.15
getDefaultClusterId()
4.2.1.2.1.16
getIndexedProperties()
4.2.1.2.1.17
getProperty()
4.2.1.2.1.18
8
getSubclasses()
4.2.1.2.1.19
getSuperClassesNames()
4.2.1.2.1.20
hasClusterId()
4.2.1.2.1.21
hasPolymorphicClusterId()
4.2.1.2.1.22
hasSuperClasses()
4.2.1.2.1.23
isEdgeType()
4.2.1.2.1.24
isVertexType()
4.2.1.2.1.25
properties()
4.2.1.2.1.26
propertiesM ap()
4.2.1.2.1.27
removeClusterId()
4.2.1.2.1.28
removeSuperClass()
4.2.1.2.1.29
setDefaultClusterId()
4.2.1.2.1.30
setName()
4.2.1.2.1.31
truncate()
4.2.1.2.1.32
truncateCluster()
4.2.1.2.1.33
ODatabaseDocument
4.2.1.2.2
browseClass()
4.2.1.2.2.1
browseCluster()
4.2.1.2.2.2
countClass()
4.2.1.2.2.3
createClass()
4.2.1.2.2.4
createClassIfNotExists()
4.2.1.2.2.5
createEdgeClass()
4.2.1.2.2.6
createVertexClass()
4.2.1.2.2.7
getRecord()
4.2.1.2.2.8
getRecordType()
4.2.1.2.2.9
newBlob()
4.2.1.2.2.10
newEdge()
4.2.1.2.2.11
newElement()
4.2.1.2.2.12
newInstance()
4.2.1.2.2.13
newVertex()
4.2.1.2.2.14
OEdge
4.2.1.2.3
getFrom()
4.2.1.2.3.1
getTo()
4.2.1.2.3.2
OElement
4.2.1.2.4
asEdge()
4.2.1.2.4.1
asVertex()
4.2.1.2.4.2
getProperty()
4.2.1.2.4.3
getPropertyNames()
4.2.1.2.4.4
getSchemaType()
4.2.1.2.4.5
isEdge()
4.2.1.2.4.6
isVertex()
4.2.1.2.4.7
removeProperty()
4.2.1.2.4.8
setProperty()
4.2.1.2.4.9
OProperty
4.2.1.2.5
9
getDefaultValue()
4.2.1.2.5.1
getM ax()
4.2.1.2.5.2
getM in()
4.2.1.2.5.3
getName()
4.2.1.2.5.4
getType()
4.2.1.2.5.5
isM andatory()
4.2.1.2.5.6
isNotNull()
4.2.1.2.5.7
setDefaultValue()
4.2.1.2.5.8
setM ax()
4.2.1.2.5.9
setM in()
4.2.1.2.5.10
setName()
4.2.1.2.5.11
setType()
4.2.1.2.5.12
OrientDB
4.2.1.2.6
create()
4.2.1.2.6.1
createIfNotExists()
4.2.1.2.6.2
drop()
4.2.1.2.6.3
exists()
4.2.1.2.6.4
list()
4.2.1.2.6.5
open()
4.2.1.2.6.6
OServer
4.2.1.2.7
addTemporaryUser()
4.2.1.2.7.1
addUser()
4.2.1.2.7.2
authenticate()
4.2.1.2.7.3
dropUser()
4.2.1.2.7.4
existsStoragePath()
4.2.1.2.7.5
getAvailableStorageNames()
4.2.1.2.7.6
getConfiguration()
4.2.1.2.7.7
getDatabaseDirectory()
4.2.1.2.7.8
getInstance()
4.2.1.2.7.9
getInstanceByPath()
4.2.1.2.7.10
getStoragePath()
4.2.1.2.7.11
isActive()
4.2.1.2.7.12
isAllowed()
4.2.1.2.7.13
openDatabase()
4.2.1.2.7.14
restart()
4.2.1.2.7.15
saveConfiguration()
4.2.1.2.7.16
shutdown()
4.2.1.2.7.17
startup()
4.2.1.2.7.18
OType
4.2.1.2.8
OVertex
4.2.1.2.9
addEdge()
4.2.1.2.9.1
getEdges()
4.2.1.2.9.2
getVertices()
4.2.1.2.9.3
TinkerPop 2.6 Graph API
4.2.1.3
10
Tutorial
4.2.1.3.1
Vertices and Edges
4.2.1.3.2
Blueprints Extension
4.2.1.3.3
Factory
4.2.1.3.4
Schema
4.2.1.3.5
Class
4.2.1.3.5.1
Property
4.2.1.3.5.2
Partitioned
4.2.1.3.6
Lightweight Edges
4.2.1.3.7
Graph Batch Insert
4.2.1.3.8
Apache TinkerPop 3
4.2.1.4
Document API
4.2.1.5
Documents
Object API
4.2.1.5.1
4.2.1.6
Database
4.2.1.6.1
POJO
4.2.1.6.2
Attach
4.2.1.6.3
Schema
4.2.1.6.4
Binding
4.2.1.6.5
Traverse
4.2.1.7
M ulti-Threading
4.2.1.8
Usage
4.2.1.8.1
Concurrency Control
4.2.1.8.2
Transactions
4.2.1.9
Fetching Strategies
4.2.1.10
Graph Consistency
4.2.1.11
Binary Data
4.2.1.12
JPA
4.2.1.13
JDBC Driver
4.2.2
Scala API
4.2.3
OrientJS - Node.js Driver
4.2.4
Server API
4.2.4.1
Database API
4.2.4.2
Record API
4.2.4.3
Class API
4.2.4.4
Class
4.2.4.4.1
Property
4.2.4.4.2
Records
4.2.4.4.3
Index API
4.2.4.5
Function API
4.2.4.6
Queries
4.2.4.7
create()
4.2.4.7.1
delete()
4.2.4.7.2
fetch()
4.2.4.7.3
11
insert()
4.2.4.7.4
liveQuery()
4.2.4.7.5
select()
4.2.4.7.6
transform()
4.2.4.7.7
traverse()
4.2.4.7.8
update()
4.2.4.7.9
Transactions
4.2.4.8
Events
4.2.4.9
PyOrient - Python Driver
Client
4.2.5
4.2.5.1
command()
4.2.5.1.1
batch()
4.2.5.1.2
data_cluster_add()
4.2.5.1.3
data_cluster_count()
4.2.5.1.4
data_cluster_data_range()
4.2.5.1.5
data_cluster_drop()
4.2.5.1.6
db_count_records()
4.2.5.1.7
db_create()
4.2.5.1.8
db_drop()
4.2.5.1.9
db_exists()
4.2.5.1.10
db_list()
4.2.5.1.11
db_open()
4.2.5.1.12
db_reload()
4.2.5.1.13
db_size()
4.2.5.1.14
get_session_token()
4.2.5.1.15
query()
4.2.5.1.16
query_async()
4.2.5.1.17
record_create()
4.2.5.1.18
record_delete()
4.2.5.1.19
record_load()
4.2.5.1.20
record_update()
4.2.5.1.21
set_session_token()
4.2.5.1.22
tx_commit()
4.2.5.1.23
attach()
4.2.5.1.23.1
begin()
4.2.5.1.23.2
commit()
4.2.5.1.23.3
rollback()
4.2.5.1.23.4
OGM
4.2.5.2
Connection
4.2.5.2.1
Schemas
4.2.5.2.2
Brokers
4.2.5.2.3
Batch
4.2.5.2.4
Scripts
4.2.5.2.5
OrientDB-NET - C#/.NET Driver
4.2.6
12
Server
4.2.6.1
ConfigGet()
4.2.6.1.1
ConfigList()
4.2.6.1.2
ConfigSet()
4.2.6.1.3
CreateDatabase()
4.2.6.1.4
DatabaseExists()
4.2.6.1.5
Databases()
4.2.6.1.6
DropDatabase()
4.2.6.1.7
Database
4.2.6.2
Clusters()
4.2.6.2.1
Command()
4.2.6.2.2
GetClusterIdFor()
4.2.6.2.3
GetClusterNameFor()
4.2.6.2.4
GetClusters()
4.2.6.2.5
Gremlin()
4.2.6.2.6
Insert()
4.2.6.2.7
JavaScript()
4.2.6.2.8
Query()
4.2.6.2.9
Select()
4.2.6.2.10
SqlBatch()
4.2.6.2.11
Update()
4.2.6.2.12
Query
4.2.6.3
Conditionals
4.2.6.3.1
Limiters
4.2.6.3.2
Sort
4.2.6.3.3
Transaction
4.2.6.4
Add()
4.2.6.4.1
AddEdge()
4.2.6.4.2
AddOrUpdate()
4.2.6.4.3
Delete()
4.2.6.4.4
GetPendingObject()
4.2.6.4.5
Update()
4.2.6.4.6
PhpOrient - PHP Driver
4.2.7
Client
4.2.7.1
Server
4.2.7.2
dbCreate()
4.2.7.2.1
dbDrop()
4.2.7.2.2
dbExists()
4.2.7.2.3
dbList()
4.2.7.2.4
Database
4.2.7.3
command()
4.2.7.3.1
dataClusterAdd()
4.2.7.3.2
dataClusterCount()
4.2.7.3.3
dataClusterDrop()
4.2.7.3.4
13
dataClusterDataRange()
4.2.7.3.5
dbCountRecords()
4.2.7.3.6
dbReload()
4.2.7.3.7
dbSize()
4.2.7.3.8
query()
4.2.7.3.9
queryAsync()
4.2.7.3.10
recordCreate()
4.2.7.3.11
recordLoad()
4.2.7.3.12
recordUpdate()
4.2.7.3.13
sqlBatch()
4.2.7.3.14
ClusterM ap
4.2.7.4
dropClusterID()
4.2.7.4.1
getClusterID()
4.2.7.4.2
getIdList()
4.2.7.4.3
Record
4.2.7.5
getOClass()
4.2.7.5.1
getOData()
4.2.7.5.2
getRid()
4.2.7.5.3
jsonSerialize()
4.2.7.5.4
recordSerialize()
4.2.7.5.5
setOClass()
4.2.7.5.6
setOData()
4.2.7.5.7
setRid()
4.2.7.5.8
ID
4.2.7.6
Transaction
4.2.7.7
attach()
4.2.7.7.1
begin()
4.2.7.7.2
commit()
4.2.7.7.3
rollback()
4.2.7.7.4
M arcoPolo - Elixir Driver
Server
4.2.8
4.2.8.1
create_db()
4.2.8.1.1
db_exists?()
4.2.8.1.2
distrib-config()
4.2.8.1.3
drop_db()
4.2.8.1.4
Database
4.2.8.2
command()
4.2.8.2.1
create_record()
4.2.8.2.2
db_countrecords()
4.2.8.2.3
db_reload()
4.2.8.2.4
db_size()
4.2.8.2.5
delete_record()
4.2.8.2.6
live_query()
4.2.8.2.7
live_query_unsubscribe()
4.2.8.2.8
14
load_record()
4.2.8.2.9
script()
4.2.8.2.10
update_record()
4.2.8.2.11
Types
4.2.8.3
Structs
4.2.8.4
BinaryRecord
4.2.8.4.1
Date
4.2.8.4.2
DateTime
4.2.8.4.3
Document
4.2.8.4.4
FetchPlan
4.2.8.4.5
RID
4.2.8.4.6
Javascript (legacy)
Javascript API
4.2.9
4.2.9.1
Rest API
4.2.10
Gremlin API
4.2.11
ADVANCED TOPICS
Security
5.1
Database security
5.1.1
Server security
5.1.2
Database encryption
5.1.3
Secure SSL connections
5.1.4
Security Configuration
5.1.5
Kerberos Example
5.1.6
Security v2.2 Code Changes
5.1.7
Security v2.2 New Features
5.1.8
Symmetric Key Authentication
5.1.9
Distributed Architecture
5.2
Lifecycle
5.2.1
Configuration
5.2.2
Server M anager
5.2.2.1
Runtime Configuration
5.2.2.2
Replication
5.2.3
Sharding
5.2.4
Data Centers
5.2.5
Troubleshooting
5.3
Java
5.3.1
M emory Leak Detector
5.3.2
Direct M emory Tracing
5.3.3
Performance Tuning
5.4
Tuning the Graph API
5.4.1
Tuning the Document API
5.4.2
Tuning the Object API
5.4.3
Profiler
5.4.4
15
Distributed Configuration Tuning
5.4.5
OrientDB Stress Test Tool
5.4.6
Enterprise Edition
Auditing
5.5
5.5.1
Internals
6.1
System database
6.1.1
Storages
6.1.2
M emory storage
6.1.2.1
PLocal storage
6.1.2.2
Engine
6.1.2.2.1
Disk-Cache
6.1.2.2.2
WAL (Journal)
6.1.2.2.3
Local storage (deprecated)
6.1.2.3
Clusters
6.1.3
Limits
6.1.4
RidBag
6.1.5
Custom Index Engine
6.1.6
Caching
6.1.7
Hooks - Triggers
6.1.8
Dynamic Hooks
6.1.8.1
Java (Native) Hooks
6.1.8.2
Server
Server Status
6.1.9
6.1.9.1
Web Server
6.1.10
Binary Protocol
6.1.11
CSV Serialization
6.1.11.1
Schemaless Serialization
6.1.11.2
Commands
6.1.11.3
Release Notes
7.1
16
Home
OrientDB Manual - version 3.0.0RC1
Welcome to OrientDB - the first M ulti-M odel Open Source NoSQL DBM S that brings together the power of graphs and the flexibility
of documents into one scalable high-performance operational database.
OrientDB 3.0 M2 is out!
Check what's new and download the binary distribution now
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
Quick Navigation
Getting S tarted
Main Topics
Developers
Introduction to OrientDB
Basic Concepts
SQL
Installation
Supported Data Types
Gremlin
First Steps
Inheritance
HTTP API
Troubleshooting
Security
Java API
Enterprise Edition
Indexes
NodeJS
ACID Transactions
PHP
Functions
Python
Caching Levels
.NET
Common Use Cases
Other Drivers
Network Binary Protocol
Javadocs
17
Home
Operations
Installation
3rd party Plugins
Upgrade
Configuration
Distributed Architecture (replication, sharding and high-availability)
Performance Tuning
ETL to Import any kind of data into OrientDB
Import from Relational DB
Backup and Restore
Export and Import
Quick References
Console
Studio web tool
OrientDB Server
Network-Binary-Protocol
Gephi Graph Analysis Visual tool
Rexster Support and configuration
Continuous integration
Resources
User Group - Have question, troubles, problems?
#orientdb IRC channel on freenode
Professional Support
Training - Training and classes.
Events - Follow OrientDB at the next event!
Team - M eet the team behind OrientDB
Contribute - Contribute to the project.
Who is using OrientDB? - Clients using OrientDB in production.
Questions or Need Help?
Check out our Get in Touch page for different ways of getting in touch with us.
PDF
This documentation is also available in PDF format.
Past Releases
v2.2.x
v2.1.x
v2.0.x
v1.7.8
Every effort has been made to ensure the accuracy of this manual. However, OrientDB, LTD. makes no warranties with respect
to this documentation and disclaims any implied warranties of merchantability and fitness for a particular purpose. The
information in this document is subject to change without notice.
18
Introduction
Introduction
This Chapter provides an introduction to OrientDB.
About This M anual
Overview of OrientDB
Release 3.0
What's new in OrientDB 3.0?
Available Packages
SQL Changes
API Changes
Known Issues
Upgrading to OrientDB 3.0
How to Report Bugs or Problems
How to Get in Touch with OrientDB
How to Contribute to OrientDB
OrientDB Roadmap
19
About This M anual
About this Manual
This M anual documents version 3.0 of the OrientDB Server and the OrientDB suite of products.
OrientDB 3.0.0RC1 and this M anual are still in development.
Generated on M on Jan 08 2018 10:25:34 GM T+0000 (UTC) using GitBook v.3.2.2.
20
Overview of OrientDB
Overview
OrientDB is the first M ulti-M odel Open Source NoSQL DBM S that combines the power of graphs and the flexibility of documents
into one scalable, high-performance operational database.
Gone are the days where your database only supports a single data model. As a direct response to polyglot persistence, multi-model
databases acknowledge the need for multiple data models, combining them to reduce operational complexity and maintain data
consistency. Though graph databases have grown in popularity, most NoSQL products are still used to provide scalability to
applications sitting on a relational DBM S. Advanced 2nd generation NoSQL products like OrientDB are the future: providing more
functionality and flexibility, while being powerful enough to replace your operational DBM S.
Speed
OrientDB was engineered from the ground up with performance as a key specification. It’s fast on both read and write operations.
Stores up to 120,000 records per second
No more Joins: relationships are physical links to the records.
Better RAM use.
Traverses parts of or entire trees and graphs of records in milliseconds.
Traversing speed is not affected by the database size.
Enterprise
While most NoSQL DBM Ss are used as secondary databases, OrientDB is powerful and flexible enough to be used as an operational
DBM S. Though OrientDB Community Edition is free for commercial use, robust applications need enterprise level functionalities to
guarantee data security and flawless performance. OrientDB Enterprise Edition gives you all the features of our community edition plus:
Incremental backups
Unmatched security
24x7 Support
Query Profiler
Distributed Clustering configuration
M etrics Recording
Live M onitor with configurable alerts
Zero Configuration Multi-Master Architecture
With a master-slave architecture, the master often becomes the bottleneck. With OrientDB, throughput is not limited by a single server.
Global throughput is the sum of the throughput of all the servers.
M ulti-M aster + Sharded architecture
Elastic Linear Scalability
Restore the database content using WAL
With a zero-config multi-master architecture, OrientDB is perfect for the Cloud. Hundreds of servers can share the workload, scaling
horizontally across distributed modern data centers.
Flexibility
Replacing your DBM S, once it no longer meets requirements, can be a huge cost in time and resources. Is your database powerful,
scalable and flexible enough to grow with you? Using OrientDB also reduces the need to support multiple products to achieve your
goals.
21
Overview of OrientDB
Get Started in Minutes
OrientDB is written entirely in Java and can run on any platform without configuration and installation. It's a drop-in replacement for
the most common existing graph databases in deployment today.
2M B Full Server distribution (not including demo)
M ultiple Programming Language Bindings
Extended SQL with graph functionality
Tinkerpop API
Coming from the relational world? Import your data using OrientDB Teleporter and get started in an instant
Coming From Neo4j? Our Neo4j Importer lets you get started with your own graph data
Low TCO
There is absolutely no cost associated with using OrientDB Community Edition.
OrientDB Community is free for commercial use.
Comes with an Apache 2 Open Source License.
Eliminates the need for multiple products and multiple licenses.
OrientDB Ltd, the company behind OrientDB, offers optional services such as Developer and Production Support, consultancy and
Training with transparent pricing far below our competitors to ensure you’re maximizing OrientDB’s capabilities for your particular use
case. OrientDB Enterprise Edition is included with the purchase of any of these services.
Open Source
Which is more likely to have better quality? A DBM S created and tested by a handful of developers or one tested by over 100,000
developers globally? When code is public, everyone can scrutinize, test, report and resolve issues. All things Open Source move faster
compared to the proprietary world. In fact, the most popular databases ranked by DB-Engines are now Open Source.
OrientDB LTD leads the OrientDB Open Source project and defines the roadmap but all members of the OrientDB Development Team
were original contributors to the OrientDB Open Source project, years before being brought onto the team. Their expert product
knowledge coupled with the passion they bring to the table every day, ensures quality for our products, support and consultancy work.
22
Editions
Editions
OrientDB is available in two editions:
Community Edition is released as an open source project under the Apache 2 license. This license allows unrestricted free usage
for both open source and commercial projects.
Enterprise Edition is commercial software built on top of the Community Edition. Enterprise is developed by the same team that
developed the OrientDB engine. It serves as an extension of the Community Edition, providing Enterprise features, such as:
Non-Stop Backup and Restore
Scheduled FULL and Incremental Backups
Query Profiler
Distributed Clustering configuration
M etrics Recording
Live M onitoring with configurable Alerts
23
Release 3.0
Release 3.0
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
This Section documents what is new and what has changed in OrientDB 3.0.
What's new in OrientDB 3.0?
Available Packages
SQL Changes
API Changes
Known Issues
Upgrading to OrientDB 3.0
24
What's new in OrientDB 3.0?
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
What's new in OrientDB 3.0?
New database administration, access and pooling API
OrientDB v 3.0 has a new API that is specifically intended to manipulate database instances (ie. creating and dropping databases,
checking that a DB exists, creating single db connections and connection pools).
Using this API is as simple as doing:
OrientDB orientDB = new OrientDB("embedded:/tmp/",OrientDBConfig.defaultConfig());
orientDB.create("test",ODatabaseType.PLOCAL);
try(ODatabaseDocument db = orientDB.open("test","admin","admin");) {
// Enter your code here...
}
orientDB.close();
You can also instantiate a connection pool as follows:
ODatabasePool pool = new ODatabasePool(orientDB,"test","admin","admin");
// OPEN DATABASE
try (ODatabaseDocument db = pool.acquire() {
// YOUR CODE
...
}
M ore information HERE
Graph-document concepts unification in core API
Core Graph API
In v 3.0 TinkerPop is just an alternative graph API. The main graph API provided by OrientDB is in the Core module:
25
What's new in OrientDB 3.0?
Create documents and graphs with the same API
With the ODatabaseDocument API you can now create simple documents:
OElement doc = db.newInstance("ADocumentClass");
or graphs
OVertex vertex1 = db.newVertex("AVertexClass");
OVertex vertex2 = db.newVertex("AVertexClass");
vertex1.addEdge("AnEdgeClass", vertex2);
Unified and more powerful API for properties
Now documents, vertices and edges have a single, unified API to get and set property names:
document.setProperty("name", "foo");
vertex.setProperty("name", "foo");
edge.setProperty("name", "foo");
document.getProperty("name");
vertex.getProperty("name");
edge.getProperty("name");
No more
doc.field("name")
and
vertex.getProperty("name")
!!!
Property names can now contain any character, including blank spaces, dots, brackets and special characters.
M ore information HERE
New execution plan based query engine
26
What's new in OrientDB 3.0?
OrientDB team completely re-wrote the SQL query engine. The new query engine is more strict, more accurate and explicit in the
execution planning and of course faster!
An example of the new execution planning:
SELECT sum(Amount), OrderDate
FROM Orders
WHERE OrderDate > date("2012-12-09", "yyyy-MM-dd")
GROUP BY OrderDate
+ FETCH FROM INDEX Orders.OrderDate
OrderDate > date("2012-12-09", "yyyy-MM-dd")
+ EXTRACT VALUE FROM INDEX ENTRY
+ FILTER ITEMS BY CLASS
Orders
+ CALCULATE PROJECTIONS
Amount AS _$$$OALIAS$$_1, OrderDate
+ CALCULATE AGGREGATE PROJECTIONS
sum(_$$$OALIAS$$_1) AS _$$$OALIAS$$_0, OrderDate
GROUP BY OrderDate
+ CALCULATE PROJECTIONS
_$$$OALIAS$$_0 AS `sum(Amount)`, OrderDate
You can also obtain statistics about the cost of each step in the query execution:
+ FETCH FROM INDEX Orders.OrderDate (1.445μs)
OrderDate > date("2012-12-09", "yyyy-MM-dd")
+ EXTRACT VALUE FROM INDEX ENTRY
+ FILTER ITEMS BY CLASS
Orders
+ CALCULATE PROJECTIONS (5.065μs)
Amount AS _$$$OALIAS$$_1, OrderDate
+ CALCULATE AGGREGATE PROJECTIONS (3.182μs)
sum(_$$$OALIAS$$_1) AS _$$$OALIAS$$_0, OrderDate
GROUP BY OrderDate
+ CALCULATE PROJECTIONS (1.116μs)
_$$$OALIAS$$_0 AS `sum(Amount)`, OrderDate
M ore information about SELECT execution planning, EXPLAIN, PROFILE
Support for query on remote transactions
Until V 2.2 remote connection did not allow to mix API operations and SQL statements in the same transaction. Version 3.0 finally
solves this limitation, now you can mix SQL and API operations in a single, remote transaction and the tx isolation will be guaranteed by
OrientDB, transparently.
Support streaming of query result set
In V 3.0 we re-designed the binary protocol and the ResultSet API to support streaming on query result sets. This means:
lower latency in query execution
much smaller memory footprint for query result sets, both on the server and on the client
(if you are a Java developer) a new, modern Java 8 API based on Streams to manipulate query result sets
M ore information about HERE
Integration with Apache TinkerPop 3.x
OrientDB v3.0 is compliant with TinkerPop 3.x through an external plugin.
M ore information HERE
Integration with Apache TinkerPop 2.x
27
What's new in OrientDB 3.0?
OrientDB v3.0 is backward compatible with TinkerPop 2.6.x API through an external plugin. If you built your application with
OrientDB 2.2 or minor and you don't want to migrate to the new API (the new M ulti-M odel or the new TinkerPop 3.x APIs), then
download the version with TP2 plugin included.
Externalization of object API
The Object Database API are now part of a separate module. If your existent application is using it, please include this module. For new
application we don't suggest to use the Object Database API, but rather the new M ulti-M odel API.
Improvements of storage caching for reduce latency
New Demo DB 'Social Travel Agency'
Starting with OrientDB v.3.0 a new demo database is included. M ore information on the new demo database can be found here.
28
Available Packages
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
Available Packages
Starting from OrientDB 3.0, for each OrientDB Editions, different packages are available for download. Please use the package that best
fits your needs.
Community Edition
The following are the packages available for OrientDB Community Edition:
CE (orientdb-community-3.0.0RC1.tar.gz)
OrientDB Community Edition without Gremlin/TinkerPop support
CE-TP2 (orientdb-community-tp2-3.0.0RC1.tar.gz)
OrientDB Community Edition that includes support for Gremlin/TinkerPop 2.6
CE-TP3 (orientdb-community-tp3-3.0.0RC1.tar.gz)
OrientDB Community Edition that includes support for Gremlin/TinkerPop 3.x
CE-spatial-TP3 (orientdb-community-spatial-3.0.0RC1.tar.gz)
Similar to CE-TP3, i.e. OrientDB Community Edition that includes support for Gremlin/TinkerPop 3.x, but with spatial
support a sell. Warning: this package does include software that is released with LGPL license
Enterprise Edition
OrientDB Enterprise Edition is not available as 3.0 milestone preview. The Enterprise Edition will be available as soon as the GA
version of 3.0.0 is published.
29
SQL Changes
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
SQL Changes
DISTINCT keyword
In v 2.2 the only way to have distinct values from a SELECT statement was using the
DISTINCT
operator, that is much more flexible than
distinct()
distinct()
function. In v 3.0 we introduced
function. The following query is valid in v 3.0
SELECT DISTINCT name, surname from Person
distinct()
function is still allowed, but it's deprecated
eval() and mathematical expressions
Until v 2.2 the only way to execute mathematical operations in SQL was to use
eval(expression)
function:
SELECT eval(' 3 + 2 ') as sum
In v 3.0 mathematical expressions are allowed in both projections and WHERE conditions, eg.
SELECT 3 + 2 as sum
SELECT FROM V WHERE theNumber > 3 + 3
Please refer to SQL syntax page for all the details
MATCH and DISTINCT
In v.2.2 the M ATCH statement automatically filters duplicate result rows and there is no way to specify a different behavior.
In v 3.0 the M ATCH by default ALLOWS duplicate results, if you want only distinct results you have to explicitly declare
RETURN
DISTINCT ...
The following statement in v.2.2
MATCH
{class:Person, as:a} -FriendOf-> {as:b}
RETURN a.name, b.name
is equivalent to v. 3.0
MATCH
{class:Person, as:a} -FriendOf-> {as:b}
RETURN DISTINCT a.name, b.name
Changes in the CREATE INDEX statement
CREATE INDEX T.id UNIQUE
is not allowed anymore, please use
30
SQL Changes
CREATE INDEX T.id ON T(id) UNIQUE
instead
Changes in the way batch script commands are separated
In v. 2.2 the newline is a valid statement separator in batch scripts. Since 3.0 the only valid statement separator is the semicolon
;
.
In v 3.0 the following script is invalid
SELECT FROM V
SELECT FROM E
The following script is valid as well
SELECT FROM V
WHERE name = 'foo';
SELECT FROM E;
Please note that the first statement is split on two rows.
EXPLAIN
BREAKING CHANGE: in v. 3.0 the EXPLAIN statement does not execute the statement anymore and does not return information
about execution statistics.
The EXPLAIN statement in v 3.0 returns details about the execution planning for the query, ie. all the steps that the query executor will
execute to calculate the query result.
Changes in the CREATE EDGE statement
Starting from 3.0, it is mandatory to create the Edge class before executing the CREATE EDGE statement. If the Edge class does not
exist the CREATE EDGE statement will fail (previously it was creating the Edge class automatically).
Changes in the DELETE EDGE statement
Starting from 3.0, it is mandatory to specify in the DELETE EDGE statement the Edge class of the edge instance you want to delete. If
the Edge class is not specified the DELETE EDGE statement will fail. So if until 2.2.x Edge class is optional and you can execute
something like
DELETE EDGE WHERE out=#9:0 AND in=#10:1
in 3.0 Edge Class is mandatory:
DELETE EDGE WHERE out=#9:0 AND in=#10:1
To delete all edges from two specific vertices regardless of their Edge class you can simply specify the 'E' Edge Class:
DELETE EDGE E WHERE out=#9:0 AND in=#10:1
31
API Changes
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
API Changes
ODatabase hierarchy and factories
TODO
OProperty
OProperty.getFullName()
now returns
"`ClassName`.`propertyName`"
instead of
"ClassName.propertyName"
OrientBaseGraph
setUseVertexFieldsForEdgeLabels(boolean)
is now deprecated and has no effect. All the edge labels are represented as edge classes.
32
Known Issues
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
Known Issues
The command line tool Neo4j to OrientDB Importer tool has not been refactored using the new M ulti-M odel API. As a
consequence, if you plan to use the Neo4j to OrientDB Importer, please use it with the CE-TP2 package of OrientDB 3.0. For more
information on the available 3.0 packages, please refer to this page.
33
Upgrading to OrientDB 3.0
OrientDB 3.0.0RC1 and this M anual are still in development. Not suitable for production
environments.
Upgrading to OrientDB 3.0
General information
Developing OrientDB 3.0 we put a lot of attention on maintaining backward compatibility with v 2.2. In some cases though, we had to
do some small breaking changes to make the whole solution more consistent.
Here is a list of the things you should know when migrating to v 3.0
Schema
Case sensitive property names
In v 2.2 property names are case sensitive while working schemaless, while if you work schemaful property names are treated as case
insensitive.
Eg. consider the following queries:
Query 1:
SELECT name from V
Query 2:
SELECT Name from V
In v 2.2:
Query 1 and Query 2 are equivalent if you are working schemaless
Query 1 and Query 2 are different if you declared
In v 3.0 these two queries are always different, so
Name
name
and
property in the schema for V
name
are considered two different properties (with or without a schema)
When migrating from v 2.2 to v 3.0, review your queries and make sure that you are writing property names in the right case
Note: CLASS names are still case insensitive
Case sensitive index names
In v 2.2 index names are case insensitive
In v 3.0 index names are case sensitive
When migrating from v 2.2 to v 3.0, review your queries and make sure that you are writing index names in the right case
SQL
See full SQL reference
UPDATE ADD/PUT/INCREMENT
34
Upgrading to OrientDB 3.0
In v 2.2 there was a specific syntax for:
adding values to lists:
UPDATE AClass ADD aListProperty = "a value to add"
adding elements to maps:
incrementing values:
UPDATE AClass PUT aMapProperty = "a key to add", "a value to add"
UPDATE AClass INCREMENT aNumberProperty =
This syntax is limitating, misleading and hard to read, so we decided to switch to a more natural syntax, as follows:
UPDATE ADD:
V 3.0 has a new
||
operator that allows to concatenate lists and sets:
UPDATE AClass ADD aListProperty = "a value to add"
becomes
UPDATE AClass SET aListProperty =
aListProperty || "a value to add"
but it can also be used to concatenate the value on the left:
UPDATE AClass SET aListProperty =
"a value to add" || aListProperty
or to concatenate multiple values:
UPDATE AClass SET aListProperty =
aListProperty || ["a value to add", "another value"]
UPDATE PUT:
The UPDATE PUT syntax is actually redundant, even in v 2.2. It can be replaced with dot notation or with square bracket notation:
UPDATE AClass PUT aMapProperty = "a key to add", "a value to add"
can be written as:
UPDATE AClass SET aMapProperty["a key to add"] = "a value to add"
or
UPDATE AClass SET aMapProperty.`a key to add` = "a value to add"
UPDATE INCREMENT
The INCREM ENT syntax is limited to adding numbers to numbers. In v 3.0 we removed this option and replaced it with a much more
flexible set of operators:
+=
// add and set
-=
// subtract and set
*=
// multiply and set
/=
// divide and set
...
The following:
UPDATE AClass INCREMENT aNumberProperty = 15
can be written as
35
Upgrading to OrientDB 3.0
UPDATE AClass SET aNumberProperty += 15
that is equivalent to
UPDATE AClass SET aNumberProperty = aNumberProperty + 15
But also the following are valid
UPDATE AClass SET aNumberProperty -= 15
equivalent to
UPDATE AClass SET aNumberProperty = aNumberProperty - 15
and so on so forth
eval() function
V 2.2 did not support expressions in SQL projections and filters, so you had to use
eval()
function to explicitly calculate them.
V 3.0 has full support for expressions in SQL, so you can re-write your queries removing the
eval()
function, eg.
SELECT eval(' age + 10 ') as ageInTenYears FROM Person
can be written as follows in v 3.0
SELECT age + 10 as ageInTenYears FROM Person
The same applies to WHERE conditions, eg. the following query is valid in v 3.0
SELECT FROM Person WHERE age + 10 < 50
FETCH PLAN
In v 3.0 FETCH PLAN is deprecated, and no longer works in most of the scenarios. It was replaced by a much more flexible syntax:
nested projections
See full syntax here
Other changes in SQL
See SQL changes
Release notes
General information on how to upgrade OrientDB can be found in the Upgrade Chapter.
You may also be interested in checking the Release Notes.
36
How to Report Bugs or Problems
Report an Issue
Very often when a new issue is open it lacks some fundamental information. This slows down the entire process because the first
question from the OrientDB team is always "What release of OrientDB are you using?" and every time a Ferret dies in the world.
So please add more information about your issue:
1. OrientDB release? (If you're using a SNAPSHOT please attach also the build number found in "build.number" file)
2. What steps will reproduce the problem? 1. 2. 3.
3. S ettings. If you're using custom settings please provide them below (to dump all the settings run the application using the JVM
argument -Denvironment.dumpCfgAtStartup=true)
4. What is the expected behavior or output? What do you get or see instead?
5. If you're describing a performance or memory problem the profiler dump can be very useful (to dump it run the application using
the JVM arguments -Dprofiler.autoDump.reset=true -Dprofiler.autoDump.interval=10 -Dprofiler.enabled=true)
Now you're ready to create a new one: https://github.com/orientechnologies/orientdb/issues/new
37
How to Get in Touch with OrientDB
How to Get in Touch with OrientDB
We want to make it super-easy for OrientDB users and contributors to talk to us and connect with each other, to share ideas, solve
problems and help make OrientDB awesome. Here are the main channels we're running currently, we'd love to hear from you on one of
them:
Google Group
OrientDB Google Group
The OrientDB Google Group (aka Community Group) is a good first stop for a general inquiry about OrientDB or a specific support
issue (e.g. trouble setting OrientDB up). It's also a good forum for discussions about the roadmap or potential new functionality.
StackOverflow
StackOverflow OrientDB tag
Feel free to ask your questions on StackOverflow under "orientdb" and "orient-db" tags.
Gitter.io
The best Web Chat, where we have an open channel. Use this is you have a question about OrientDB.
IRC
#orientdb
We're big fans of IRC here at OrientDB. We have a #orientdb channel on Freenode - stop by and say hi, you can even use Freenode's
webchat service so don't need to install anything to access it.
Twitter
@orientdb
Follow and chat to us on Twitter.
GitHub
OrientDB issues
If you spot a bug, then please raise an issue in our main GitHub project orientechnologies/orientdb. Likewise if you have developed a
cool new feature or improvement in your OrientDB fork, then send us a pull request against the "develop" branch!
If you want to brainstorm a potential new feature, then the OrientDB Google Group (see above) is probably a better place to start.
Email
info@orientdb.com
If you want more information about Commercial Support, Consultancy or Training, email us.
38
How to Contribute to OrientDB
How to Contribute to OrientDB
In order to contribute issues and pull requests, please sign OrientDB's Contributor License Agreement. The purpose of this agreement is
to protect users of this codebase by ensuring that all code is free to use under the stipulations of the Apache2 license.
Pushing into main repository
OrientDB uses different branches to support the development and release process. The
develop
branch contains code under
development for which there's not a stable release yet. When a stable version is released, a branch for the hotfix is created. Each stable
release is merged on master branch and tagged there. At the time of writing these notes, the state of branches is:
develop: work in progress for next 2.2.x release (2.2.0-SNAPSHOT)
2.1.x: hot fix for next 2.1.x stable release (2.1.10-SNAPSHOT)
2.0.x: hot fix for next 2.0.x stable release (2.0.17-SNAPSHOT)
last tag on master is 2.1.9
If you'd like to contribute to OrientDB with a patch follow the following steps:
fork the repository interested in your change. The main one is https://github.com/orientechnologies/orientdb, while some other
components reside in other projects under Orient Technologies umbrella.
clone the forked repository
select the branch, e.g the develop branch:
git checkout develop
apply your changes with your favourite editor or IDE
test that Test Suite hasn't been broken by running:
mvn clean test
if all the tests pass, then do a Pull Request (PR) against the branch (e.g.: "develop") on GitHub repository and write a comment
about the change. Please don't send PR to "master" because we use that branch only for releasing
Documentation
If you want to contribute to the OrientDB documentation, the right repository is: https://github.com/orientechnologies/orientdb-docs.
Every 24-48 hours all the contributions are reviewed and published on the public documentation.
Code formatting
You can find eclipse java formatter config file here: _base/ide/eclipse-formatter.xml.
If you use IntelliJ IDEA you can install this plugin and use formatter profile mentioned above.
Debugging
Run OrientDB as standalone server
The settings to run OrientDB Server as stand-alone (where the OrientDB's home is
community-2.2-SNAPSHOT
M ain Class:
/repositories/orientdb/releases/orientdb-
) are:
com.orientechnologies.orient.server.OServerMain
VM parameters:
-server
-DORIENTDB_HOME=/repositories/orientdb/releases/orientdb-community-2.2-SNAPSHOT
-Dorientdb.www.path=src/site
-Djava.util.logging.config.file=${ORIENTDB_HOME}/config/orientdb-server-log.properties
-Dorientdb.config.file=${ORIENTDB_HOME}/config/orientdb-server-config.xml
-Drhino.opt.level=9
39
How to Contribute to OrientDB
Use classpath of module:
orientdb-graphdb
Run OrientDB distributed
The settings to run OrientDB Server as distributed (where the OrientDB's home is
community-2.2-SNAPSHOT
M ain Class:
/repositories/orientdb/releases/orientdb-
) are:
com.orientechnologies.orient.server.OServerMain
VM parameters:
-server
-DORIENTDB_HOME=/repositories/orientdb/releases/orientdb-community-2.2-SNAPSHOT
-Dorientdb.www.path=src/site
-Djava.util.logging.config.file=${ORIENTDB_HOME}/config/orientdb-server-log.properties
-Dorientdb.config.file=${ORIENTDB_HOME}/config/orientdb-server-config.xml
-Drhino.opt.level=9
-Ddistributed=true
Use classpath of module:
orientdb-distributed
In order to debug OrientDB in distributed mode, changed the scope to "runtime" in file distributed/pom.xml:
com.orientechnologies
orientdb-graphdb
${project.version}
runtime
In this way IDE like IntelliJ can start the server correctly that requires graphdb dependency.
40
OrientDB Roadmap
OrientDB Roadmap
This page contains the roadmap with the main enhancements for the OrientDB product.
Terms
RC: Release Candidate, is a beta version with potential to be a final product, which is ready to release unless significant bugs
emerge. In this stage of product stabilization, all product features have been designed, coded and tested through one or more beta
cycles with no known showstopper-class bug. A release is called code complete when the development team agrees that no entirely
new source code will be added to this release. There could still be source code changes to fix defects, changes to documentation and
data files, and peripheral code for test cases or utilities. Beta testers, if privately selected, will often be credited for using the release
candidate as though it were a finished product. Beta testing is conducted in a client's or customer's location and to test the software
from a user's perspective.
GA: General Availability, is the stage where the software has "gone live" for usage in production. Users in production are suggested
to plan a migration for the current GA evaluating pros and cons of the upgrade.
Release 3.0
- Development started on.: June 2016
- Expected first M1......: January 2017
- Expected first M2......: February 2017
- Expected first RC......: March 2017
- Expected final GA......: March/April 2017
Status
Last update: December 14, 2016
For a more detailed an updated view, look at the Roadmap 3.0 issue.
41
OrientDB Roadmap
Module
Feature
S tatus
Core
M ulti-Threads WAL
30%
Core
WAL Compaction
30%
Core
Index rebuild avoid using WAL
0%
Core
Compression of used space on serialization
3%
Core
Improved DISKCACHE algorithm
60%
Core
Index per cluster
0%
Core
New data structure to manage edges
0%
SQL
Distributed SQL Executor
70%
SQL
M ulti-line queries in batch scripts
100%
Java API
New factories
100%
Java API
Improve SQL UPDATE syntax
100%
Java API
Support for TinkerPop 3
70%
Remote protocol
Support for server-side transactions
10%
Remote protocol
Support for server-side cursors
90%
Remote protocol
Push messages on schema change
0%
Remote protocol
Push messages on record change
0%
Distributed
Auto-Sharding
10%
Distributed
Optimized network protocol to send only the delta between updates
50%
Release 3.1
- Development started on.: - Expected first RC......: TBD
- Expected final GA......: TBD
Status
Last update: April 12, 2015
Module
Feature
S tatus
Core
Parallel Transactions
0%
Core
Indexing of embedded properties
0%
Core
Override of properties
0%
Core
Enhance isolation level also for remote commands
0%
Distributed
Optimized replication for cross Data Center
0%
Distributed
Replication of in-memory databases
0%
Lucene
Faceted search
20%
Java API
ODocument.update()
0%
SQL
shortestPaths() function
0%
SQL
New functions (strings, maths)
40%
42
OrientDB in Five M inutes
OrientDB in Five Minutes
Learn OrientDB basics in just five minutes, in your favorite programming language:
Java
43
Install
OrientDB for Java Developers in Five Minutes
If you are a Java Developer and it's the first time you approach OrientDB, then you are in the right place!
Ready? Let's start!
Step 1/5 - Download and Install
Download OrientDB from the following URL:
http://orientdb.com/download.php?file=orientdb-community-3.0.0m2.tar.gz
(you can find all the other download options here, if needed http://orientdb.com/orientdb-labs/)
Unzip it on your FileSystem and open a shell in the directory.
Now type
cd orientdb-community-3.0.0m2
cd bin
and then, if you are on Linux/OSX, you can start the server with
./server.sh
if you are on Windows, start the server with
server.bat
You will see OrientDB starting
44
Install
.`
,
`,`
.,.
.,,
`
`:.
,:`
:,,
,,,
.
.,.:::::
:::::::::
:::::::::
,`
.::,,,,::.,,,,,,`;;
`
`
.:
::::::::::
:::
`,.
::,,,,,,,:.,,.`
.:
:::
:::
:::
,,:,:,,,,,,,,::.
`
`
,,:.,,,,,,,,,: `::, ,,
`
``
.:
:::
:::
:::
::,::`
: :,::`
::::
:::
:::
:::
:::
:::
:::
,:,,,,,,,,,,::,:
,,
:.
::
:
.:
:::
:::
:::::::
:,,,,,,,,,,:,::
,,
:
:
:
:
.:
:::
:::
:::::::::
:,,,,,,,,,,:,::,
,, .::::::::
:
:
.:
:::
:::
:::
:::
:
:
.:
:::
:::
:::
:::
:::
:::
:::
:::
`
:
:::
`,...,,:,,,,,,,,,: .:,. ,, ,,
.,,,,::,,,,,,,:
`: , ,,
...,::,,,,::.. `:
.,,
,::::,,,. `:
,,
:
`
:
:
.:
:::
:,
:
:
:
.:
:::::::::::
:::
:
:
.:
:::::::::
::::::::::
:::::
,,:` `,,.
,,,
,,.
``
.,`
`,
GRAPH DATABASE
`.
``
orientdb.com
`
2017-08-14 14:11:12:824 INFO
Loading configuration from: /Users/luigidellaquila/temp/orient/orientdb-community-3.0.0m2/config
/orientdb-server-config.xml... [OServerConfigurationLoaderXml]
2017-08-14 14:11:12:932 INFO
OrientDB Server v3.0.0m2 (build 4abea780acc12595bad8cbdcc61ff96980725c3b) is starting up... [OSe
rver]
2017-08-14 14:11:12:951 INFO
OrientDB auto-config DISKCACHE=12.373MB (heap=1.963MB direct=524.288MB os=16.384MB) [orientechno
logies]
2017-08-14 14:11:12:994 INFO
Databases directory: /Users/luigidellaquila/temp/orient/orientdb-community-3.0.0m2/databases [OS
erver]
2017-08-14 14:11:13:017 INFO
Creating the system database 'OSystem' for current server [OSystemDatabase]
2017-08-14 14:11:14:457 INFO
Listening binary connections on 0.0.0.0:2424 (protocol v.37, socket=default) [OServerNetworkList
ener]
2017-08-14 14:11:14:459 INFO
Listening http connections on 0.0.0.0:2480 (protocol v.10, socket=default) [OServerNetworkListen
er]
+---------------------------------------------------------------+
|
WARNING: FIRST RUN CONFIGURATION
|
+---------------------------------------------------------------+
| This is the first time the server is running. Please type a
|
| password of your choice for the 'root' user or leave it blank |
| to auto-generate it.
|
|
|
| To avoid this message set the environment variable or JVM
|
| setting ORIENTDB_ROOT_PASSWORD to the root password to use.
|
+---------------------------------------------------------------+
Root password [BLANK=auto generate it]: *
The first time you start the server, you will be asked to enter a root password (twice). You can choose the password you prefer, just
make sure to remember it, you will need it alter.
Now you are ready for the Next Step - Create a Database >>>
45
Create a DB
OrientDB for Java Developers in Five Minutes
In the Previous Step you installed and started OrientDB on your machine, now it's time to create a database
Step 2/5 - Create a DB
Open your favourite browser (modern browser, no IE please!) and enter the following URL:
http://localhost:2480/studio/index.html
You will see this page:
Click on "NEW DB"
enter "test" as database name
enter the root password
Then click on "CREATE DATABASE"
Good job! You just created your first database!
Now, to make sure that everything is OK, try to enter the following query
SELECT * FROM OUser
and click the green "RUN" button. You should see the three default users that OrienDB creates for you: admin, reader and writer
46
Create a DB
Now you are ready for the Next Step - Create your Java Application >>>
47
Create the Java Application
OrientDB for Java Developers in Five Minutes
In the previous step you created your first database, now it's time to create a Java application that can connect to the DB, query and
manipulate it.
From now on, for this tutorial we will use IntelliJ Idea, but you can use any IDE that supports Java 8 and M aven.
Step 3/5 - Create a Maven project
Open IntelliJ Idea and:
choose the menu File -> new -> Project...
from the left menu, choose Maven
make sure that Project S DK is greater or equal to 1.8
click Next
choose your GroupId and ArtifactId (we will use "test" "test", as this is what we are doing ;-) )
click Next twice
48
Create the Java Application
Now open pom.xml file and add the following dependency:
com.orientechnologies
orientdb-client
3.0.0m2
Click on "automatically import dependencies" if needed
Now you are ready for the Next Step - Open a DB Connection and Create the DB Schema >>>
49
Connect to the DB and create the Schema
OrientDB for Java Developers in Five Minutes
In the previous step you created your Java application scaffolding in IntelliJ Idea, now it's time to create a Java class that connects to
the database and does basic operations
We will write a very simple application with two classes:
Person: a vertex type containing information about people
FriendOf: an edge class that connects people together
Step 4/5 - Connect to the DB and create a basic schema
Let's create a simple Java class
Open the folder src -> main -> java
Right-click on the java folder and choose New -> Java Class
Give the class the name you prefer and click OK
create a main method
Connecting to the DB
Now it's time to connect to OrientDB
Create an OrientDB object to manage the remote server
Also invoke a
close()
at the end of the method (so that you don't forget it later)
OrientDB orient = new OrientDB("remote:localhost", OrientDBConfig.defaultConfig());
//let's do something with this server!
orient.close();
The first argument of
remote
OrientDB()
constructor is the URL of the remote database. It's made of two parts:
: specifies that we are connecting to a remote (stand-alone) server
localhost
: the address of the host where OrientDB is running (it can be a URL or an IP, in this case orientdb is running on the
local machine)
50
Connect to the DB and create the Schema
Until now, we just established a connection with the server, but not with the database itself (we created a db named test, do you
remember?).
Now it's time to open a database session (and remember to close it at the end!):
OrientDB orient = new OrientDB("remote:localhost", OrientDBConfig.defaultConfig());
ODatabaseSession db = orient.open("test", "admin", "admin");
//let's do something with this session!
db.close();
orient.close();
Here we are actually connecting to the database. The three parameters are:
test
: the database name (we created it a couple of steps before)
admin
(the first one): the username used to connect
admin
(the second one): the password for the connection
By default, when you create a new database, OrientDB creates three users for you:
users are the same as the user names, eg. the password for
admin
is
admin
admin
,
reader
,
writer
; the passwords for these
. You can change it later of course, and you can define more
users if needed.
Creating the schema
Now it's time to create a schema for our db. Do you remember? We are creating a graph of people who are friends, so we need a
vertex class and a
FriendOf
Person
edge class.
Let's also add a little check to make sure that the classes do not already exist
if (db.getClass("Person") != null) {
db.createVertexClass("Person");
}
if (db.getClass("FriendOf") != null) {
db.createEdgeClass("FriendOf");
}
And this is the final version of our class
This is the full source code:
51
Connect to the DB and create the Schema
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
public class Main {
public static void main(String[] args) {
OrientDB orient = new OrientDB("remote:localhost", OrientDBConfig.defaultConfig());
ODatabaseSession db = orient.open("test", "admin", "admin");
if (db.getClass("Person") == null) {
db.createVertexClass("Person");
}
if (db.getClass("FriendOf") == null) {
db.createEdgeClass("FriendOf");
}
db.close();
orient.close();
}
}
Now just run it and then open OrientDB Studio again:
go back to the browser (OrientDB Studio)
click on the S CHEMA tab
you will see the two newly created classes:
Person
and
FriendOf
Just to make it a bit more realistic, let's also create some basic schema for our
We will just add a
name
Person
class.
to the Person and we will create an index on it.
52
Connect to the DB and create the Schema
OClass person = db.getClass("Person");
if (person == null) {
person = db.createVertexClass("Person");
}
if (person.getProperty("name") == null) {
person.createProperty("name", OType.STRING);
//
index name
index type
property name
person.createIndex("Person_name_index", OClass.INDEX_TYPE.NOTUNIQUE, "name");
}
And this is the final result:
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
public class Main {
public static void main(String[] args) {
OrientDB orient = new OrientDB("remote:localhost", OrientDBConfig.defaultConfig());
ODatabaseSession db = orient.open("test", "admin", "admin");
OClass person = db.getClass("Person");
if (person == null) {
person = db.createVertexClass("Person");
}
if (person.getProperty("name") == null) {
person.createProperty("name", OType.STRING);
person.createIndex("Person_name_index", OClass.INDEX_TYPE.NOTUNIQUE, "name");
}
if (db.getClass("FriendOf") == null) {
db.createEdgeClass("FriendOf");
}
db.close();
orient.close();
}
}
Now you are ready for the Next Step - Create your First Graph and Run Queries >>>
53
Create your First Graph and Run Queries
OrientDB for Java Developers in Five Minutes
In the previous step you established a DB connection from Java, then you created the DB schema (two classes and an index)
Now it's time to insert and query some data
Step 5/5 - Create and Query a Graph
First of all, let's create three vertices: Alice, Bob and Jim
Creating vertices
We are good Java developers, aren't we? Let's encaplusate a single vertex creation in a method:
private static OVertex createPerson(ODatabaseSession db, String name, String surname) {
OVertex result = db.newVertex("Person");
result.setProperty("name", name);
result.setProperty("surname", surname);
result.save();
return result;
}
Wow, we never mentioned that people have a
surname
!!! In the previous section we just defined the schema for
name
property...
OrientDB can work schemaful (with all the property names and types defined), schemaless (schema-free, no schema defined) or
schema-mixed like in this case, where we define a part of the schema (ie. the
name
) but we leave the developer the ability to add new
properties at run time, without having to deal with further schema definitions.
Now let's create the three vertices:
private static void createPeople(ODatabaseSession db){
OVertex alice = createPerson(db, "Alice", "Foo");
OVertex bob = createPerson(db, "Bob", "Bar");
OVertex jim = createPerson(db, "Jim", "Baz");
}
Creating edges
Suppose that Alice is a friend of Bob and that Bob is a friend of Jim:
Alice --FriendOf--> Bob --FriendOf--> Jim
Let's create the edges in the database:
OEdge edge1 = alice.addEdge(bob, "FriendOf");
OEdge edge2 = bob.addEdge(jim, "FriendOf");
Please cosider that edges are plain documents, so you can get/set properties on them exactly like for vertices.
Executing queries
Last step of this journey: let's write and execute a simple query that finds friends of friends (FoaF) of a person. We will use a SELECT
for this.
54
Create your First Graph and Run Queries
private static void executeAQuery(ODatabaseSession db) {
String query = "SELECT expand(out('FriendOf').out('FriendOf')) from Person where name = ?";
OResultSet rs = db.query(query, "Alice");
while (rs.hasNext()) {
OResult item = rs.next();
System.out.println("friend: " + item.getProperty("name"));
}
rs.close(); //REMEMBER TO ALWAYS CLOSE THE RESULT SET!!!
}
or, if you prefer Java Streams API:
private static void executeAQuery(ODatabaseSession db) {
String query = "SELECT expand(out('FriendOf').out('FriendOf')) from Person where name = ?";
OResultSet rs = db.query(query, "Alice");
rs.stream().forEach(x -> System.out.println("friend: " + x.getProperty("name")));
rs.close();
}
Let's try a more complex query, let's find all the people that are friends of both Alice and Jim. We will use a M ATCH for this.
private static void executeAnotherQuery(ODatabaseSession db) {
String query =
" MATCH
" +
"
{class:Person, as:a, where: (name = :name1)}, " +
"
{class:Person, as:b, where: (name = :name2)}, " +
"
{as:a} -FriendOf-> {as:x} -FriendOf-> {as:b}
" RETURN x.name as friend
" +
";
Map params = new HashMap();
params.put("name1", "Alice");
params.put("name2", "Jim");
OResultSet rs = db.query(query, params);
while (rs.hasNext()) {
OResult item = rs.next();
System.out.println("friend: " + item.getProperty("name"));
}
rs.close();
}
Good job!!! This is your first OrientDB Java program!
Here is the full source code of the main class:
import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.OEdge;
import com.orientechnologies.orient.core.record.OVertex;
import com.orientechnologies.orient.core.sql.executor.OResult;
import com.orientechnologies.orient.core.sql.executor.OResultSet;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
OrientDB orient = new OrientDB("remote:localhost", OrientDBConfig.defaultConfig());
ODatabaseSession db = orient.open("test", "admin", "admin");
createSchema(db);
55
Create your First Graph and Run Queries
createPeople(db);
executeAQuery(db);
executeAnotherQuery(db);
db.close();
orient.close();
}
private static void createSchema(ODatabaseSession db) {
OClass person = db.getClass("Person");
if (person == null) {
person = db.createVertexClass("Person");
}
if (person.getProperty("name") == null) {
person.createProperty("name", OType.STRING);
person.createIndex("Person_name_index", OClass.INDEX_TYPE.NOTUNIQUE, "name");
}
if (db.getClass("FriendOf") == null) {
db.createEdgeClass("FriendOf");
}
}
private static void createPeople(ODatabaseSession db) {
OVertex alice = createPerson(db, "Alice", "Foo");
OVertex bob = createPerson(db, "Bob", "Bar");
OVertex jim = createPerson(db, "Jim", "Baz");
OEdge edge1 = alice.addEdge(bob, "FriendOf");
OEdge edge2 = bob.addEdge(jim, "FriendOf");
}
private static OVertex createPerson(ODatabaseSession db, String name, String surname) {
OVertex result = db.newVertex("Person");
result.setProperty("name", name);
result.setProperty("surname", surname);
result.save();
return result;
}
private static void executeAQuery(ODatabaseSession db) {
String query = "SELECT expand(out('FriendOf').out('FriendOf')) from Person where name = ?";
OResultSet rs = db.query(query, "Alice");
while (rs.hasNext()) {
OResult item = rs.next();
System.out.println("friend: " + item.getProperty("name"));
}
rs.close(); //REMEMBER TO ALWAYS CLOSE THE RESULT SET!!!
}
private static void executeAnotherQuery(ODatabaseSession db) {
String query =
" MATCH
" +
"
{class:Person, as:a, where: (name = :name1)}, " +
"
{class:Person, as:b, where: (name = :name2)}, " +
"
{as:a} -FriendOf-> {as:x} -FriendOf-> {as:b}
" RETURN x.name as friend
" +
";
Map params = new HashMap();
params.put("name1", "Alice");
params.put("name2", "Jim");
OResultSet rs = db.query(query, params);
while (rs.hasNext()) {
OResult item = rs.next();
System.out.println("friend: " + item.getProperty("name"));
56
Create your First Graph and Run Queries
}
rs.close();
}
}
Next steps:
You may be interested in:
M ore details about the Java M ulti-M odel API
Full SQL Syntax
57
Getting Started
Getting Started
58
Installation
Installation
OrientDB Community Edition is available as a binary package for download or as source code on GitHub. The Enterprise Edition is
available as a binary package to all our Customers that purchased one of the available Subscriptions. A 45-days Enterprise Edition trial
for development purposes is available as well.
OrientDB prerequisites can be found here.
Use Docker
If you have Docker installed in your computer, this is the easiest way to run OrientDB. From the command line type:
$ docker run -d --name orientdb -p 2424:2424 -p 2480:2480
-e ORIENTDB_ROOT_PASSWORD=root orientdb:latest
Where instead of "root", type the root's password you want to use.
Use Ansible
If you manage your servers through Ansible, you can use the following role : https://galaxy.ansible.com/migibert/orientdb which is highly
customizable and allows you to deploy OrientDB as a standalone instance or multiple clusterized instances.
For using it, you can follow these steps :
Install the role
ansible-galaxy install migibert.orientdb
Create an Ansible inventory
Assuming you have one two servers with respective IPs fixed at 192.168.10.5 and 192.168.10.6, using ubuntu user.
[orientdb-servers]
192.168.20.5 ansible_ssh_user=ubuntu
192.168.20.6 ansible_ssh_user=ubuntu
Create an Ansible playbook
In this example, we provision a two node cluster using multicast discovery mode. Please note that this playbook assumes java is already
installed on the machine so you should have one step before that install Java 8 on the servers
59
Installation
- hosts: orientdb-servers
become: yes
vars:
orientdb_version: 2.0.5
orientdb_enable_distributed: true
orientdb_distributed:
hazelcast_network_port: 2434
hazelcast_group: orientdb
hazelcast_password: orientdb
multicast_enabled: True
multicast_group: 235.1.1.1
multicast_port: 2434
tcp_enabled: False
tcp_members: []
orientdb_users:
- name: root
password: root
tasks:
- apt:
name: openjdk-8-jdk
state: present
roles:
- role: orientdb-role
Run the playbook
ansible-playbook -i inventory playbook.yml
Binary Installation
OrientDB provides a pre-compiled binary package to install the database on your system. Depending on your operating system, this is
a tarred or zipped package that contains all the relevant files you need to run OrientDB. For desktop installations, go to OrientDB
Downloads and select the package that best suits your system.
On server installations, you can use the
utility:
wget
$ wget http://orientdb.com/download.php?file=orientdb-community-importers-3.0.0RC1.tar.gz&utm_source=Labs&utm_medium=link&utm_
campaign=300 -O orientdb-community-3.0.0RC1.tar.gz
Whether you use your web browser or
example,
/opt/orientdb/
wget
, unzip or extract the downloaded file into a directory convenient for your use, (for
on Linux). This creates a directory called orientdb-community-3.0.0RC1 with relevant files and scripts,
which you will need to run OrientDB on your system.
Source Code Installation
For information on how to install OrientDB from source, please refer to this Section.
Post-installation Tasks
For desktop users installing the binary, OrientDB is now installed and can be run through shell scripts found in the package
bin
directory of the installation. For servers, there are some additional steps that you need to take in order to manage the database server for
OrientDB as a service. The procedure for this varies, depending on your operating system.
Install as Service on Unix, Linux and M ac OS X
Install as Service on M icrosoft Windows
Upgrading
When the time comes to upgrade to a newer version of OrientDB, the methods vary depending on how you chose to install it in the first
place. If you installed from binary downloads, repeat the download process above and update any symbolic links or shortcuts to point
to the new directory.
60
Installation
For systems where OrientDB was built from source, pull down the latest source code and compile from source.
$ git pull origin master
$ mvn clean install
Bear in mind that when you build from source, you can switch branches to build different versions of OrientDB using Git. For example,
$ git checkout 2.2.x
$ mvn clean install
builds the
2.2.x
branch, instead of
master
.
Building a single executable jar with OrientDB
OrientDB for internal components like engines, operators, factories uses Java SPI Service Provider Interface. That means that the jars of
OrientDB are shipped with files in
META-INF/services
that contains the implementation of components. Bear in mind that when
building a single executable jar, you have to concatenate the content of files with the same name in different orientdb-*.jar . If you are
using M aven Shade Plugin you can use Service Resource Transformer to do that.
Other Resources
To learn more about how to install OrientDB on specific environments, please refer to the guides below:
Install with Docker
Install with Ansible
Install on Linux Ubuntu
Install on JBoss AS
Install on GlassFish
Install on Ubuntu 12.04 VPS (DigitalOcean)
Install on Vagrant
61
Run the server
Running the OrientDB Server
When you finish installing OrientDB, whether you build it from source or download the binary package, you are ready to launch the
database server. You can either start it through the system daemon or through the provided server script. This article only covers the
latter.
Note: If you would like to run OrientDB as a service on your system, there are some additional steps that you need to take. This
provides alternate methods for starting the server and allows you to launch it as a daemon when your system boots. For more
information on this process see:
Install OrientDB as a Service on Unix, Linux and M ac OS X
Install OrientDB as a Service on M icrosoft Windows
Starting the Database Server
While you can run the database server as system daemon, you also have the option of starting it directly. In the OrientDB installation
directory, (that is
$ORIENTDB_HOME
), under
bin
, there is a file named
server.sh
on Unix-based systems and
server.bat
on
Windows. Executing this file starts the server.
To launch the OrientDB database server, run the following commands:
62
Run the server
$
cd $ORIENTDB_HOME/bin
$
./server.sh
.
.`
,
`
`:.
`,`
.,.
.,,
,:`
:,,
,,,
.
.,.:::::
,`
.::,,,,::.,,,,,,`;;
````
`,.
::,,,,,,,:.,,.`
,,:,:,,,,,,,,::.
`
.:
`
`
,,:.,,,,,,,,,: `::, ,,
`
.:
``
::,::`
,:,,,,,,,,,,::,:
,,
:.
:,,,,,,,,,,:,::
,,
:
:,,,,,,,,,,:,::,
:
: :,::`
::::
::
:
.:
:
:
:
.:
,, .::::::::
:
:
.:
:
:
.:
`,...,,:,,,,,,,,,: .:,. ,, ,,
.,,,,::,,,,,,,:
.:
`: , ,,
...,::,,,,::.. `:
.,,
,::::,,,. `:
,,
:
`
:
:
.:
:,
:
:
:
.:
:
:
.:
:::::
,,:` `,,.
,,,
,,.
``
.,`
`,
S E R V E R
`.
``
`
2012-12-28 01:25:46:319 INFO Loading configuration from: config/orientdb-serverconfig.xml... [OServerConfigurationLoaderXml]
2012-12-28 01:25:46:625 INFO OrientDB Server v1.6 is starting up... [OServer]
2012-12-28 01:25:47:142 INFO -> Loaded memory database 'temp' [OServer]
2012-12-28 01:25:47:289 INFO Listening binary connections on 0.0.0.0:2424
[OServerNetworkListener]
2012-12-28 01:25:47:290 INFO Listening http connections on 0.0.0.0:2480
[OServerNetworkListener]
2012-12-28 01:25:47:317 INFO OrientDB Server v1.6 is active. [OServer]
The database server is now running. It is accessible on your system through ports
2424
and
2480
. At the first startup the server will
ask for the root user password. The password is stored in the config file.
Stop the Server
On the console where the server is running a simple CTRL+c will shutdown the server.
The shutdown.sh (shutdown.bat) script could be used to stop the server:
$
cd $ORIENTDB_HOME/bin
$
./shutdown.sh -p ROOT_PASSWORD
On *nix systems a simple call to shutdown.sh will stop the server running on localhost:
$
cd $ORIENTDB_HOME/bin
$
./shutdown.sh
63
Run the server
It is possible to stop servers running on remote hosts or even on different ports on localhost:
$
cd $ORIENTDB_HOME/bin
$
./shutdown.sh -h odb1.mydomain.com -P 2424-2430 -u root -p ROOT_PASSWORD
List of params
-h | --host HOS TNAME or IP ADDRES S : the host or ip where OrientDB is running, default to localhost
-P | --ports PORT or PORT RANGE : single port value or range of ports; default to 2424-2430
-u | --user ROOT US ERNAME : root's username; deafult to root
-p | --password ROOT PAS S WORD : root's user password; mandatory
NOTE: On Windows systems password is always mandatory because the script isn't able to discover the pid of the OrientDB's
process.
Server Log Messages
Following the masthead, the database server begins to print log messages to standard output. This provides you with a guide to what
OrientDB does as it starts up on your system.
1. The database server loads its configuration file from the file
$ORIENTDB_HOME/config/orientdb-server-config.xml
.
For more information on this step, see OrientDB Server.
2. The database server loads the
temp
database into memory. You can use this database for storing temporary data.
3. The database server begins listening for binary connections on port
2424
for all configured networks, (
0.0.0.0
).
4. The database server begins listening for HTTP connections on port
2480
for all configured networks, (
0.0.0.0
).
Accessing the Database Server
By default, OrientDB listens on two different ports for external connections.
Binary: OrientDB listens on port
2424
for binary connections from the console and for clients and drivers that support the
Network Binary Protocol.
HTTP: OrientDB listens on port
2480
for HTTP connections from OrientDB Studio Web Tool and clients and drivers that
support the HTTP/REST protocol, or similar tools, such as cURL.
If you would like the database server to listen at different ports or IP address, you can define these values in the configuration file
config/orientdb-server-config.xml
.
64
Run the console
Running the OrientDB Console
Once the server is running there are various methods you can use to connect to your database server to an individual databases. Two
such methods are the Network Binary and HTTP/REST protocols. In addition to these OrientDB provides a command-line interface for
connecting to and working with the database server.
Starting the OrientDB Console
In the OrientDB installation directory (that is,
console.sh
for Unix-based systems or
$ORIENTDB_HOME
console.bat
, where you installed the database) under
bin
, there is a file called
for Windows users.
To launch the OrientDB console, run the following command after you start the database server:
$
cd $ORIENTDB_HOME/bin
$
./console.sh
OrientDB console v.X.X.X (build 0) www.orientdb.com
Type 'HELP' to display all the commands supported.
Installing extensions for GREMLIN language v.X.X.X
orientdb>
The OrientDB console is now running. From this prompt you can connect to and manage any remote or local databases available to you.
Using the
HELP
Command
In the event that you are unfamiliar with OrientDB and the available commands, or if you need help at any time, you can use the
command, or type
orientdb>
?
HELP
into the console prompt.
HELP
AVAILABLE COMMANDS:
* alter class
Alter a class in the database schema
* alter cluster Alter class in the database schema
...
...
* help
Print this help
* exit
Close the console
For each console command available to you,
HELP
documents its basic use and what it does. If you know the particular command and
need details on its use, you can provide arguments to
orientdb>
HELP
for further clarification.
HELP SELECT
COMMAND: SELECT
- Execute a query against the database and display the results.
SYNTAX: select
WHERE:
- : The query to execute
65
Run the console
Connecting to Server Instances
There are some console commands, such as
LIST DATABASES
or
CREATE DATABASE
, which you can only run while connected to a server
instance. For other commands, however, you must also connect to a database, before they run without error.
Before you can connect to a fresh server instance and fully control it, you need to know the root password for the database. The
root password is located in the configuration file at
config/orientdb-server-config.xml
. You can find it by searching for the
element. If you want to change it, edit the configuration file and restart the server.
...
...
With the required credentials, you can connect to the database server instance on your system, or establish a remote connection to one
running on a different machine.
orientdb>
CONNECT remote:localhost root my_root_password
Connecting to remote Server instance [remote:localhost] with user 'root'...OK
Once you have established a connection to the database server, you can begin to execute commands on that server, such as
DATABASES
and
orientdb>
CREATE DATABASE
LIST
.
LIST DATABASES
Found 1 databases:
* GratefulDeadConcerts (plocal)
To connect to this database or to a different one, use the
and password. By default, each database has an
admin
CONNECT
command from the console and specify the server URL, username,
user with a password of
admin
.
Warning: Always change the default password on production databases.
The above
LIST DATABASES
command shows a
GratefulDeadConcerts
installed on the local server. To connect to this database, run the
following command:
orientdb>
CONNECT remote:localhost/GratefulDeadConcerts admin admin
Connecting to database [remote:localhost/GratefulDeadConcerts] with user 'admin'...OK
The
CONNECT
command takes a specific syntax for its URL. That is,
remote:localhost/GratefulDeadConcerts
in the example. It has
three parts:
Protocol: The first part of the database address is the protocol the console should use in the connection. In the example, this is
remote
, indicating that it should use the TCP/IP protocol.
Address: The second part of the database address is hostname or IP address of the database server that you want the console to
connect to. In the example, this is
localhost
, since the connection is made to a server instance running on the local file system.
Database: The third part of the address is the name of the database that you want to use. In the case of the example, this is
GratefulDeadConcerts
.
66
Run the console
For more detailed information about the commands, see Console Commands.
Note: The OrientDB distribution comes with the bundled database
GratefulDeadConcerts
which represents the Graph of the
Grateful Dead's concerts. This database can be used by anyone to start exploring the features and characteristics of OrientDB.
67
Run the Studio
Run the Studio
If you're more comfortable interacting with database systems through a graphical interface then you can accomplish the most common
database tasks with OrientDB Studio, the web interface.
Connecting to Studio
By default, there are no additional steps that you need to take to start OrientDB Studio. When you launch the Server, whether through
the start-up script
$
server.sh
or as a system daemon, the Studio web interface opens automatically with it.
firefox http://localhost:2480
68
Run the Studio
From here you can create a new database, connect to or drop an existing database, import a public database and navigate to the Server
management interface.
For more information on the OrientDB Studio, see Studio.
69
Documents, Vertices and Edges
Documents, Vertices and Edges
TODO
70
Classes, Schema and Constraints
Classes
Here we will learn about how classes structure data in OrientDB. A class in OrientDB is similar to a table in a relational database with
some key differences. In this section you will learn how to see all of the classes in your database and how to create classes of your own.
You'll also learn how to provide schema on top of classes by defining constraints for a class's properties. Finally you'll learn how to
access the records stored within your classes.
The Class is a concept drawn from the Object-oriented programming paradigm. In OrientDB a class is a data model that allows you to
define certain rules for records that belong together. For example, a class 'Person' can store information about people. You can structure
your class such that a record in the class must have certain properties (i.e. Name, Birthdate, Favorite Number, etc...).
In the traditional document database model classes are comparable to collections, while in the Relational database model (R-DBM S)
they are comparable to tables. Classes are not tables though. Classes provide efficient means for storage of schema-less data. We'll see
more about schema-less, schema-full, and schema-mixed data models later (See 'Adding Properties to a Class' below).
Like many database management systems, OrientDB uses the Record as an element of storage. There are many types of records, but
with the Document Database API records always use the Document type. A document is formed by a set of key/value pairs. A
document can belong to a class.
In the example above, there are two documents. One document contains information for Sarah and another for Abdul. The keys 15:0 and
15:1 refer to each document respectively.
To list all the configured classes on your system, use the
LIST CLASSES
command in the console:
71
Classes, Schema and Constraints
orientdb>
LIST CLASSES
orientdb {db=playingwithClasses}> LIST CLASSES
CLASSES
+----+-----------+-------------+-----------------+-----+
|#
|NAME
|SUPER-CLASSES|CLUSTERS
|COUNT|
+----+-----------+-------------+-----------------+-----+
|0
|_studio
|
|_studio(13)
|
1|
|1
|Blue
|[Color]
|blue(19)
|
0|
|2
|Color
|[V]
|-
|
0|
|3
|E
|
|e(11),e_1(12)
|
0|
|4
|OFunction
|
|ofunction(6)
|
0|
|5
|OIdentity
|
|-
|
0|
|6
|ORestricted|
|-
|
0|
|7
|ORole
|[OIdentity]
|orole(4)
|
3|
|8
|OSchedule
|
|oschedule(8)
|
0|
|9
|OSequence
|
|osequence(7)
|
0|
|10
|OTriggered |
|-
|
0|
|11
|OUser
|[OIdentity]
|ouser(5)
|
3|
|12
|Person
|[V]
|person(15)
|
0|
|13
|Red
|[Color]
|red(17),red_1(18)|
0|
|14
|V
|
|v(9),v_1(10)
0|
|
+----+-----------+-------------+-----------------+-----+
|
|TOTAL
|
|
|
7|
+----+-----------+-------------+-----------------+-----+
If you are using studio, then you can see the same information by clicking on the 'schema' tab.
Here we can see that there are 14 classes in the database. Class 12 refers to person. There is also a class Color which is the super-class
of Red and Blue. Color and Person both have super-classes called V. The class V is important for using OrientDB’s graph model. We'll
see more about Superclasses and V later in the tutorial. Let's move on now to working with classes.
Working with Classes
In order to start using classes with your own applications, you need to understand how to create and configure a class for use. The class
in OrientDB is similar to the table in relational databases, but unlike tables, classes can be schema-less, schema-full or mixed. A class can
inherit properties from other classes thereby creating trees of classes (though the super-class relationship).
Each class has its own cluster or clusters, (created by default, if none are defined). For now we should know that a cluster is a place
where a group of records are stored. We'll soon see how
clustering
improves performance of querying the database.
For more information on classes in OrientDB, see Class.
To create a new class, use the
orientdb>
CREATE CLASS
command:
CREATE CLASS Student
Class created successfully. Total classes in database now: 15
This creates a class called
cluster called
student
now displayed in the
Student
. Given that no cluster was defined in the
CREATE CLASS
command, OrientDB creates a default
, to contain records assigned to this class. For the moment, the class has no records or properties tied to it. It is
CLASSES
listing and in the schema manager of Studio.
Adding Properties to a Class
72
Classes, Schema and Constraints
As mentioned above, OrientDB allows you to work in a schema-less mode. That is, it allows you to create classes without defining their
properties. However, properties are mandatory if you would like to define indexes or constraints for a class. Let's follow OrientDB's
comparison to relational databases again... If classes in OrientDB are similar to tables, then properties are the columns on those tables.
To create new properties on
orientdb>
Student
, use the
CREATE PROPERTY
command in the console or in the browse window of studio:
CREATE PROPERTY Student.name STRING
Property created successfully with id=1
orientdb>
CREATE PROPERTY Student.surname STRING
Property created successfully with id=2
orientdb>
CREATE PROPERTY Student.birthDate DATE
Property created successfully with id=3
These commands create three new properties on the
Student
class. The properties provide you with areas to define an individual
student's name, surname, and date of birth.
Displaying Class Information
Occasionally you may need to reference a particular class to see what clusters it belongs to, or any properties configured for the class's
use. Use the
INFO CLASS
command to display information about the current configuration and properties of a class.
To display information on the class
orientdb>
Student
, use the
INFO CLASS
command:
INFO CLASS Student
Class................: Student
Default cluster......: student (id=96)
Supported cluster ids: [96]
Properties:
-----------+--------+--------------+-----------+----------+----------+-----+-----+
NAME
| TYPE
| LINKED TYPE/ | MANDATORY | READONLY | NOT NULL | MIN | MAX |
|
| CLASS
|
|
|
|
|
|
-----------+--------+--------------+-----------+----------+----------+-----+-----+
birthDate | DATE
| null
| false
| false
| false
|
|
|
name
| STRING | null
| false
| false
| false
|
|
|
surname
| STRING | null
| false
| false
| false
|
|
|
-----------+--------+--------------+-----------+----------+----------+-----+-----+
Adding Constraints to Properties
Constraints create limits on the data values assigned to properties. For instance, the type, the minimum or maximum size of, whether or
not a value is mandatory or if null values are permitted to the property.
Constraints create limits on the data values assigned to properties. For instance, if 'M ANDATORY' is set to true for name in student,
then every record in the student class must have a name. If we set 'M IN' to three, then every name must also be at least three characters
long.
The only two properties required when using the 'create a property' command for a class are 'NAM E' and 'TYPE'.
To add a constraint to an existing property, use the
ALTER PROPERTY
command:
73
Classes, Schema and Constraints
orientdb>
ALTER PROPERTY Student.name MIN 3
Property updated successfully
This command adds a constraint to
Student
on the
name
property. After running this command, Student will allow any record to be
stored unless the record has a property called 'Name'. If the records has such a property then 'Student' will reject the record if the value
in 'Name' is less then three characters.
By setting property, 'M ANDATORY', to true for Student's Name we can also guarantee that every record added to student has a name.
orientdb>
ALTER PROPERTY Student.name MANDATORY true
There are many ways to use constraints on properties. They can allow you to build a data-model that tells a story about your own use
case. Constraints can also help ensure that you're database communicates with other components of a larger application by only
allowing storage of values that another application is able to recognize.
Viewing Records in a Class
Classes contain and define records in OrientDB. You can view all records that belong to a class using the
can also see data belonging to a particular record with the
DISPLAY RECORD
BROWSE CLASS
command. You
command.
Note: you cannot display a record unless you have recently received a query result with records to browse (select statement,
'browse class x', etc...).
Earlier we created a
Student
class and defined some schema for records belonging to that class, but we didn't create any records or add
any data. Thus, running 'BROWSE CLASS' on the
Student
class returns no results. Luckily OrientDB has a few preconfigured classes
and records that we can query.
Let's take the class OUser for example.
74
Classes, Schema and Constraints
orientdb>
INFO CLASS OUser
CLASS 'OUser'
Super classes........: [OIdentity]
Default cluster......: ouser (id=5)
Supported cluster ids: [5]
Cluster selection....: round-robin
Oversize.............: 0.0
PROPERTIES
----------+---------+--------------+-----------+----------+----------+-----+-----+
NAME
| TYPE
| LINKED TYPE/ | MANDATORY | READONLY | NOT NULL | MIN | MAX |
|
| CLASS
|
|
|
|
|
|
----------+---------+--------------+-----------+----------+----------+-----+-----+
password | STRING
| true
| false
| true
|
|
|
roles
| LINKSET | ORole
| null
| false
| false
| false
|
|
|
name
| STRING
| null
| true
| false
| true
|
|
|
status
| STRING
| null
| true
| false
| true
|
|
|
----------+---------+--------------+-----------+----------+----------+-----+-----+
INDEXES (1 altogether)
-------------------------------+----------------+
NAME
| PROPERTIES
|
-------------------------------+----------------+
OUser.name
| name
|
-------------------------------+----------------+
The
OUser
class defines the users on your database.
To see records assigned to the
orientdb>
OUser
class, run the
BROWSE CLASS
command:
BROWSE CLASS OUser
---+------+-------+--------+-----------------------------------+--------+-------+
# | @RID | @Class| name
| password
| status | roles |
---+------+-------+--------+-----------------------------------+--------+-------+
0 | #5:0 | OUser | admin
| {SHA-256}8C6976E5B5410415BDE90... | ACTIVE | [1]
|
1 | #5:1 | OUser | reader | {SHA-256}3D0941964AA3EBDCB00EF... | ACTIVE | [1]
|
2 | #5:2 | OUser | writer | {SHA-256}B93006774CBDD4B299389... | ACTIVE | [1]
|
---+------+-------+--------+-----------------------------------+--------+-------+
In the example, you are listing all of the users of the database. While this is fine for your initial setup and as an
example, it is not particularly secure. To further improve security in production environments, see Security.
When you run
BROWSE CLASS
, the first column in the output provides the identifier number, which you can use to display detailed
information on that particular record.
To show the first record browsed from the
OUser
class, run the
DISPLAY RECORD
command:
75
Classes, Schema and Constraints
orientdb>
DISPLAY RECORD 0
DOCUMENT @class:OUser @rid:#5:0 @version:1
----------+--------------------------------------------+
Name | Value
|
----------+--------------------------------------------+
name | admin
|
password | {SHA-256}8C6976E5B5410415BDE908BD4DEE15... |
status | ACTIVE
|
roles | [#4:0=#4:0]
|
----------+--------------------------------------------+
Bear in mind that this command references the last call of
BROWSE CLASS
. You can continue to display other records, but you cannot
display records from another class until you browse that particular class.
Class Review
Here are some key things to remember about classes:
1) A class in OrientDB is similar to a table in a relational database with some key differences. Among those differences we see tables are
schema-full, and classes can be schema-full, schema-less, or mixed.
2) You can see all of the classes in your database by running 'LIST CLASSES' in console or by visiting the 'Schema M anager' in Studio.
3) You can create a class by running the 'create class ' command in console, or by running the same command in the 'Browse' window of
studio.
4) You can use the commands, 'Create property [constraints]' and 'Create property [constraints]' to give schema to a class.
5) To see properties and constraints associated with a class you can run 'info class '.
6) To see information about a the records within a class run 'Browse class '.
7) To see information about a specific record of a class use the command 'Display record '. Note: You must have recently queried a class
for it's records before using this command. '' references the number in the left-most column of the previous query's result.
Congratulations! You are now familiar with classes in OrientDB. If you're ready to explore clusters then let's move on to the
clustering
section of this tutorial.
76
Demo Database
Demo Database
Starting with OrientDB v.3.0 a new demo database (
This Section introduces the
demodb
demodb
) is included.
database and its Data M odel, and includes some queries that is possible to execute on it.
Some screenshots on "portions" of the
demodb
graph are included as well.
77
Introduction
Introduction
The demo database can help you understand better OrientDB features and capabilities and replaces the old demo database
included in version 2.2 and previous ones.
GratefulDeadConcerts
Note: Random-generated data is used in the
demodb
, including data used for Emails, Names, Surnames, Phone Numbers and Reviews.
Version
demodb
has a version that, in general, is not linked to the Server version you are running. You can check the version of the
demodb
included in your distribution by executing the following SQL query:
SELECT `Version` FROM `DBInfo`;
Current version is 0.76.
Location
The demo database is located in the
3.0.0\databases\demodb
databases
directory under your
$ORIENTDB_HOME
(e.g.
D:\orientdb\orientdb-community-
.
Connecting to the Demo Database
It is possible to connect to
read
/
demodb
using the three standard OrientDB Users:
read
write
/
write
admin
/
admin
Using the Demo Database with OrientDB 2.2.x
The demo database can be easily loaded into OrientDB 2.2.x using the Studio's "Import a public database" feature.
Alternatively, it is possible to import it via an SQL script that includes the set of instructions needed to recreate the data model as well
as all the records (vertices, edges, and documents).
78
Data M odel
Data Model
demodb
is the database of an hypothetical Travel Agency that runs a public social platform as well.
Users (that are stored in the database in the class Profiles) can freely register to the social platform and start making friends (friendship
is expressed via the HasFriend edge).
Some of the users can become customers. When this happens the application in use at the Social Travel Agency creates a vertex in the
Customers class and links it to the associated profile via an HasProfile edge.
When customers are created, they are automatically linked to a country as well, via an IsFromCountry edge. Countries are stored in the
Countries vertex class.
Orders made by customers are stored in the vertex class Orders. Each customer can make one or more orders, and the HasCustomer
edge is used to connect orders to customers.
When customers start visiting Attractions (like Castles, Monuments, Theatres or Archaeological Sites) or using Services (like Hotels or
Restaurants) edges are created to link that specific customer with that specific attraction or service (HasVisited, HasStayed, and
HasEaten edges are used).
The Social Travel Agency also stores some reviews in the vertex class Reviews. Reviews are linked to customers via the MadeReview
edge, and to an attraction or service via the HasReview edge.
Data model of
demodb
v.0.76 is reported in the image below:
Inheritance
79
Data M odel
Inheritance in the Vertex and Edge classes of
demodb
v.0.76 is reported in the image below:
80
Queries
Queries
This Section includes several query examples that you can execute from the Studio's Browse Tab, or from its Graph Editor. You may
also execute these queries directly from the Console, or your application through an API or Driver.
Note: the screen-shots included in this Section have been taken with version 0.76 of the demo database. While the queries remain valid,
future versions of the demo database may include different records.
The following table can help you navigate through all examples:
Category
Profiles
Friendship
Customers
Countries
Orders
Question
Link
Find the 'year of birth' of the Profiles, and how many Profiles were born in the same
year
Link
Find the top 3 Profiles that have the highest number of Friends
Link
Find Santo's Friends
Link
Find Santo's Friends who are also Customers
Link
Find Santo's Friends who are also Customers, and the Countries they are from
Link
Find Santo's Friends who are also Customers, and the Orders they have placed
Link
Among Santo's Friends, find the top 3 Customers that placed the highest number of
Orders
Link
Among Santo's Friends, find the top 3 Customers that visited the highest number of
Places
Link
Find all the Friends of Customer identified with OrderedId 1 that are not Customers (so
that a product can be proposed)
Link
Find everything that is connected (1st degree) to Customer with OrderedId 1
Link
Find all Locations connected to Customer with OrderedId 1
Link
Find all Locations connected to Customer with OrderedId 1, and their Reviews (if any)
Link
Find the other Customers that visited the Locations visited by Customer with OrderedId
1
Link
Find all the places where Customer with OrderedId 2 has stayed
Link
Find all places where Customer with Id 1 has eaten
Link
Find the 3 Customers who made more reviews
Link
Find all Orders placed by Customer with OrderedId 2
Link
Calculate the total revenues from Orders associated with Customer with OrderedId 2
Link
Find the 3 Customers who placed most Orders
Link
Find the top 3 Countries from where Customers are from
Link
Find the top 3 Countries from where Customers are from
Link
Find Santo's Friends who are also Customers, and the Countries they are from
Link
Calculate the total revenues from Orders, and the min, max and average Order amount
Link
Find the year of the Orders, and how many Orders have been placed in the same year
Link
Find the 3 Customers who placed most Orders
Link
Find the top 3 Customers in terms of spending
Link
Find all Orders placed by Customer with Id 2
Link
Calculate the total revenues from Orders associated with Customer with Id 2
Link
81
Queries
Attractions
Find all Attractions connected with Customer with OrderedId 1
Link
S ervices
Find all Services connected with Customer with OrderedId 1
Link
Find the 3 Hotels that have been booked most times
Link
Find the 3 Hotels that have most reviews
Link
Find the top 3 nationality of the tourists that have eaten at Restaurant with Id 26
Link
Find all Locations visited by Santo
Link
Find all Locations connected to Customer with OrderedId 1
Link
Find all Locations connected to Customer with OrderedId 1, and their Reviews (if any)
Link
Find all Locations visited by Customer with OrderedId 2
Link
Find all Locations visited by Santo's friends
Link
Find number of Reviews per star
Link
Find all reviewed Services
Link
Find all reviewed Services and the Customer who made the review
Link
Find the numbers of reviews per Service
Link
Find the 3 Hotels that have most reviews
Link
Find the 3 Customers who made more reviews
Link
Recommend some friends to Profile 'Isabella Gomez' (friends of friends)
Link
Recommend some Hotels to Customer with OrderedId 1
Link
Find all the Friends of Customer identified with OrderedId 1 that are not Customers (so
that a product can be proposed)
Link
Find all the Customer Friends that are not Customers (so that a product can be
proposed)
Link
Find all Locations (Services + Attractions) connected with Customer with OrderedId 1
Link
Find the 3 Services (Hotels + Restaurants) that have most reviews
Link
Find the shortest path between the Profile 'Santo' and the Country 'United States'
Link
Find the shortest path between the Profile 'Santo' and the Restaurant 'M alga Granezza'
Link
Traverse everything from Profile 'Santo' up to depth three
Link
Traverse everything from Country 'Italy' up to depth three
Link
Locations
Reviews
Recommendations
Business
Opportunities
Polymorphism
S hortest Paths
Traverses
82
Queries
Profiles
Example 1
Find the 'year of birth' of the Profiles, and how many Profiles were born in the same year:
SELECT
count(*) as NumberOfProfiles,
Birthday.format('yyyy') AS YearOfBirth
FROM Profiles
GROUP BY YearOfBirth
ORDER BY NumberOfProfiles DESC
In the Browse Tab of Studio, using the query above, this is the obtained list of records (only few records are shown in the image below):
Note: in v. 2.x the corresponding query is:
SELECT
count(*) as NumberOfProfiles,
YearOfBirth
FROM (
SELECT
Birthday.format('yyyy') AS YearOfBirth
FROM Profiles)
GROUP BY YearOfBirth
ORDER BY NumberOfProfiles DESC
Example 2
Find the top 3 Profiles that have the highest number of Friends:
SELECT
@rid as Profile_RID,
Name,
Surname,
both('HasFriend').size() AS FriendsNumber
FROM `Profiles`
ORDER BY FriendsNumber DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
83
Queries
84
Queries
Friendship
Example 1
Find Santo's Friends:
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN friend.@Rid as Friend_RID, friend.Name as Friend_Name, friend.Surname as
Friend_Surname' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
If you would like only to count them, you can execute a query like the following:
SELECT COUNT(*)
FROM (
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}
RETURN friend
)
or
85
Queries
SELECT
both('HasFriend').size() AS FriendsNumber
FROM `Profiles`
WHERE Name='Santo' AND Surname='OrientDB'
Example 2
Find Santo's Friends who are also Customers:
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}<-Ha
sProfile-{class: Customers, as: customer}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN friend.@Rid as Friend_RID, friend.Name as Friend_Name, friend.Surname as
Friend_Surname, customer.@Rid as Customer_RID, customer.OrderedId as Customer_OrederedId' as
RETURN
clause, this is the
obtained list of records (only few records are shown in the image below):
Example 3
Find Santo's Friends who are also Customers, and the Countries they are from:
86
Queries
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}<-Ha
sProfile-{class: Customers, as: customer}-IsFromCountry->{Class: Countries, as: country}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN friend.@Rid as Friend_RID, friend.Name as Friend_Name, friend.Surname as
Friend_Surname, customer.@Rid as Customer_RID, customer.OrderedId as Customer_OrederedId, country.Name as FriendIsFrom' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
Example 4
Find Santo's Friends who are also Customers, and the Orders they have placed:
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}<-Ha
sProfile-{class: Customers, as: customer}<-HasCustomer-{Class: Orders, as: order}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
87
Queries
In the Browse Tab of Studio, using 'RETURN friend.@Rid as Friend_RID, friend.Name as Friend_Name, friend.Surname as
Friend_Surname, customer.@Rid as Customer_RID, customer.OrderedId as Customer_OrederedId, order.Id as OrderId' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
Example 5
Among Santo's Friends, find the top 3 Customers that placed the highest number of Orders:
88
Queries
SELECT
OrderedId as Customer_OrderedId,
in('HasCustomer').size() as NumberOfOrders,
out('HasProfile').Name as Friend_Name,
out('HasProfile').Surname as Friend_Surname
FROM (
SELECT expand(customer)
FROM (
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}
<-HasProfile-{class: Customers, as: customer}
RETURN customer
)
)
ORDER BY NumberOfOrders DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 6
Among Santo's Friends, find the top 3 Customers that visited the highest number of Places:
SELECT
OrderedId as Customer_OrderedId,
out('HasVisited').size() as NumberOfVisits,
out('HasProfile').Name as Friend_Name,
out('HasProfile').Surname as Friend_Surname
FROM (
SELECT expand(customer)
FROM (
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}
<-HasProfile-{class: Customers, as: customer}
RETURN customer
)
)
ORDER BY NumberOfVisits DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
89
Queries
You may find in a similar way the top 3 Customers, among Santo's Friends, that have stayed at the highest number of Hotels, or have
eaten at the highest number of Restaurants. Just use
out("HasVisited").size()
NumberOfRestaurants
out("HasStayed").size()
(you may also consider to modify the alias, from
or
out("HasEaten").size()
NumberOfVisits
to
instead of
NumberOfHotels
and
, so that it is more coherent to these cases).
Example 7
Find all the Friends of Customer identified with OrderedId 1 that are not Customers (so that a product can be proposed):
SELECT
@Rid as Friend_RID,
Name as Friend_Name,
Surname as Friend_Surname
FROM (
SELECT expand(customerFriend)
FROM (
MATCH {Class:Customers, as: customer, where:(OrderedId=1)}-HasProfile-{Class:Profiles, as: profile}-HasFriend-{Class:Profi
les, as: customerFriend} RETURN customerFriend
)
)
WHERE in('HasProfile').size()=0
ORDER BY Friend_Name ASC
In the Browse Tab of Studio, using the query above, this is the obtained list of records (only few records are shown in the image below):
or, without restricting to a specific customer:
Find all the Customer Friends that are not Customers (so that a product can be proposed):
In the Graph Editor included in Studio, using the query below, this is the obtained graph:
SELECT *
FROM (
SELECT expand(customerFriend)
FROM (
MATCH {Class:Customers, as: customer}-HasProfile-{Class:Profiles, as: profile}-HasFriend-{Class:Profiles, as: customerFrie
nd}
RETURN customerFriend
)
)
WHERE in('HasProfile').size()=0
90
Queries
In the Browse Tab of Studio, using the query below, this is the obtained list of records (only few records are shown in the image below):
SELECT
@Rid as Friend_RID,
Name as Friend_Name,
Surname as Friend_Surname
FROM (
SELECT expand(customerFriend)
FROM (
MATCH {Class:Customers, as: customer}-HasProfile-{Class:Profiles, as: profile}-HasFriend-{Class:Profiles, as: customerFrie
nd}
RETURN customerFriend
)
)
WHERE in('HasProfile').size()=0
91
Queries
Customers
Example 1
Find everything that is connected (1st degree) to Customer with OrderedId 1:
MATCH {class: Customers, as: c, where: (OrderedId=1)}--{as: n}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 2
Find all Locations connected to Customer with OrderedId 1:
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{Class: Locations}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
92
Queries
Example 3
Find all Locations connected to Customer with OrderedId 1, and their Reviews (if any):
MATCH {class: Customers, as: c, where: (OrderedId=1)}--{class: Locations, as: loc}-HasReview->{class: Reviews, as: r, optional
: true}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 4
Find the other Customers that visited the Locations visited by Customer with OrderedId 1:
93
Queries
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{class: Locations, as: loc}--{class: Customers, as: otherCustome
rs, where: (OrderedId<>1)}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
If we want to return also also their Profile names, surnames and emails:
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{class: Locations, as: loc}--{class: Customers, as: otherCustome
rs, where: (OrderedId<>1)}-HasProfile->{class: Profiles, as: profile}
RETURN otherCustomers.OrderedId, profile.Name, profile.Surname, profile.Email
ORDER BY `otherCustomers.OrderedId` ASC
In the Browse Tab of Studio, using 'RETURN otherCustomers.OrderedId, profile.Name, profile.Surname, profile.Email' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
Example 5
Find all the places where Customer with OrderedId 2 has stayed:
94
Queries
MATCH {as: n}<-HasStayed-{class: Customers, as: c, where: (OrderedId=2)}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 6
Find all places where Customer with OrderedId 1 has eaten:
MATCH {as: n}<-HasEaten-{class: Customers, as: c, where: (OrderedId=1)}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 7
95
Queries
Find the 3 Customers who made more reviews:
SELECT
OrderedId as CustomerId,
out("MadeReview").size() AS ReviewNumbers
FROM `Customers`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 8
Find all Orders placed by Customer with Id 2:
MATCH {class: Customers, as: c, where: (OrderedId=1)}<-HasCustomer-{class: Orders, as: o}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 9
Calculate the total revenues from Orders associated with Customer with Id 2:
96
Queries
SELECT sum(Amount) as TotalAmount
FROM (
SELECT expand(in('HasCustomer'))
FROM Customers
WHERE OrderedId=2
)
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 10
Find the 3 Customers who placed most Orders:
SELECT
OrderedId as CustomerId,
in("HasCustomer").size() AS NumberOfOrders
FROM Customers
ORDER BY NumberOfOrders
DESC LIMIT 3
In the Browse Tab of Studio, using the query above, this is the visualized result:
Example 11
Find the top 3 Countries from where Customers are from:
SELECT
Name as CountryName,
in('IsFromCountry').size() as NumberOfCustomers
FROM Countries
ORDER BY NumberOfCustomers DESC
LIMIT 3
97
Queries
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
98
Queries
Countries
Example 1
Find the top 3 Countries from where Customers are from:
SELECT
Name as CountryName,
in('IsFromCountry').size() as NumberOfCustomers
FROM Countries
ORDER BY NumberOfCustomers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 2
Find Santo's Friends who are also Customers, and the Countries they are from:
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}-HasFriend-{Class: Profiles, as: friend}<-Ha
sProfile-{class: Customers, as: customer}-IsFromCountry->{Class: Countries, as: country}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
99
Queries
In the Browse Tab of Studio, using 'RETURN friend.@Rid as Friend_RID, friend.Name as Friend_Name, friend.Surname as
Friend_Surname, customer.@Rid as Customer_RID, customer.OrderedId as Customer_OrederedId, country.Name as FriendIsFrom' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
100
Queries
Orders
Example 1
Calculate the total revenues from Orders, and the min, max and average Order amount:
SELECT
count(*) as OrdersNumber,
sum(Amount) AS TotalRevenuesFromOrders,
min(Amount) as MinAmount,
(sum(Amount)/count(*)) as AverageAmount,
max(Amount) as MaxAmount
FROM Orders
In the Browse Tab of Studio, using the query above, this is the visualized result:
Example 2
Find the year of the Orders, and how many Orders have been placed in the same year:
SELECT
count(*) as OrdersCount,
OrderDate.format('yyyy') AS OrderYear
FROM Orders
GROUP BY OrderYear
ORDER BY OrdersCount DESC
In the Browse Tab of Studio, using the query above, this is the visualized result:
101
Queries
Example 3
Find the 3 Customers who placed most Orders:
SELECT
OrderedId as CustomerId,
in("HasCustomer").size() AS NumberOfOrders
FROM Customers
ORDER BY NumberOfOrders
DESC LIMIT 3
In the Browse Tab of Studio, using the query above, this is the visualized result:
Example 4
Find the top 3 Customers in terms of spending:
SELECT
customer.OrderedId as customerOrderedId,
SUM(order.Amount) as totalAmount
FROM (
MATCH {Class: Customers, as: customer}<-HasCustomer-{class: Orders, as: order}
RETURN customer, order
)
GROUP BY customerOrderedId
ORDER BY totalAmount DESC
LIMIT 3
102
Queries
In the Browse Tab of Studio, using the query above, this is the visualized result:
Example 5
Find all Orders placed by Customer with Id 2:
MATCH {class: Customers, as: c, where: (OrderedId=1)}<-HasCustomer-{class: Orders, as: o}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 6
Calculate the total revenues from Orders associated with Customer with Id 2:
SELECT sum(Amount) as TotalAmount
FROM (
SELECT expand(in('HasCustomer'))
FROM Customers
WHERE OrderedId=2
)
103
Queries
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
104
Queries
Attractions
Example 1
Find all Attractions connected with Customer with OrderedId 1:
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{Class: Attractions, as: attraction}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN attraction.@Rid as Attraction_RID, attraction.Name as Attraction_Name, attraction.Type
as Attraction_Type' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
105
Queries
Services
Example 1
Find all Services connected with Customer with OrderedId 1:
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{Class: Services, as: service}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN service.@Rid as Service_RID, service.Name as Service_Name, service.Type as
Service_Type' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
Example 2
Find the 3 Hotels that have been booked most times:
106
Queries
SELECT
Name, Type, in("HasStayed").size() AS NumberOfBookings
FROM Hotels
ORDER BY NumberOfBookings DESC
LIMIT 3
In the Browse Tab of Studio, using the query below, this is the obtained list of records:
In a similar way:
Find the 3 Restaurants that have been used most times:
SELECT
Name, Type, in("HasEaten").size() AS VisitsNumber
FROM Restaurants
ORDER BY VisitsNumber DESC
LIMIT 3
In the Browse Tab of Studio, using the query below, this is the obtained list of records:
Example 3
Find the 3 Hotels that have most reviews:
SELECT
Name, Type, out("HasReview").size() AS ReviewNumbers
FROM `Hotels`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query below, this is the obtained list of records:
107
Queries
In a similar way:
Find the 3 Restaurants that have most reviews :
SELECT
Name, Type, out("HasReview").size() AS ReviewNumbers
FROM `Restaurants`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query below, this is the obtained list of records:
Example 4
Find the top 3 nationality of the tourists that have eaten at Restaurant with Id 26:
SELECT
Name,
count(*) as CountryCount
FROM (
SELECT
expand(out('IsFromCountry')) AS countries
FROM (
SELECT
expand(in("HasEaten")) AS customers
FROM Restaurants
WHERE Id='26'
UNWIND customers)
UNWIND countries)
GROUP BY Name
ORDER BY CountryCount DESC
LIMIT 3
In the Browse Tab of Studio, using the query below, this is the obtained list of records:
108
Queries
In a similar way:
Find the top 3 nationality of the tourists that stayed at Hotel with Id 627:
SELECT
Name, count(*) as CountryCount
FROM (
SELECT
expand(out('IsFromCountry')) AS countries
FROM (
SELECT
expand(in("HasStayed")) AS customers
FROM Hotels
WHERE Id='627'
UNWIND customers)
UNWIND countries)
GROUP BY Name
ORDER BY CountryCount DESC
LIMIT 3
In the Browse Tab of Studio, using the query below, this is the obtained list of records:
109
Queries
Locations
Example 1
Find all Locations visited by Santo:
MATCH {Class: Profiles, as: profile, where: (Name='Santo' AND Surname='OrientDB')}<-HasProfile-{Class: Customers, as: customer
}-HasVisited->{class: Locations, as: location}
RETURN $pathelements
In the Graph Editor included in Studio, using the query above, this is the obtained graph:
Example 2
Find all Locations connected to Customer with OrderedId 1:
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{Class: Locations}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
110
Queries
Example 3
Find all Locations connected to Customer with OrderedId 1, and their Reviews (if any):
MATCH {class: Customers, as: c, where: (OrderedId=1)}--{class: Locations, as: loc}-HasReview->{class: Reviews, as: r, optional
: true}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
Example 4
Find all Locations visited by Customer with OrderedId 2:
MATCH {Class: Locations, as: location}<-HasVisited-{class: Customers, as: customer, where: (OrderedId=2)}
RETURN $pathelements
111
Queries
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN location.@Rid as Location_RID, location.Name as Location_Name, location.Type as
Location_Type' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
Example 5
Find all Locations visited by Santo's friends:
MATCH {Class: Profiles, as: profile, where: (Name='Santo' and Surname='OrientDB')}-HasFriend->{Class: Profiles, as: friend}<-H
asProfile-{Class: Customers, as: customer}-HasVisited->{Class: Locations, as: location}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
112
Queries
In the Browse Tab of Studio, using 'location.@Rid as Location_RID, location.Name as Location_Name, location.Type as Location_Type,
friend.Name as Friend_Name, friend.Surname as Friend_Surname' as
RETURN
clause, this is the obtained list of records (only few
records are shown in the image below):
113
Queries
Reviews
Example 1
Find number of Reviews per star:
SELECT
Stars, count(*) as Count
FROM HasReview
GROUP BY Stars
ORDER BY Count DESC
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 2
Find all reviewed Services:
MATCH {class: Services, as: s}-HasReview->{class: Reviews, as: r}
RETURN $pathelements
In the Graph Editor included in Studio, using the query above, this is the obtained graph:
114
Queries
Example 3
Find all reviewed Services and the Customer who made the review:
MATCH {class: Services, as: s}-HasReview->{class: Reviews, as: r}<-MadeReview-{class: Customers, as: c}
RETURN $pathelements
In the Graph Editor included in Studio, using the query above, this is the obtained graph:
Example 4
Find the numbers of reviews per Service:
115
Queries
SELECT
@rid as Service_RID,
Name as Service_Name,
Type as Service_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Services`
ORDER BY ReviewNumbers DESC
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 5
Find the 3 Hotels that have most reviews:
SELECT
@rid as Hotel_RID,
Name as Hotel_Name,
Type as Hotel_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Hotels`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
In a similar way:
Find the 3 Restaurants that have most reviews:
116
Queries
SELECT
@rid as Restaurant_RID,
Name as Restaurants_Name,
Type as Restaurants_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Restaurants`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
In a polymorphic way:
Find the 3 Services (Hotels + Restaurants) that have most reviews:
SELECT
@rid as Service_RID,
Name as Service_Name,
Type as Service_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Services`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
Example 6
Find the 3 Customers who made more reviews:
117
Queries
SELECT
OrderedId as CustomerId,
out("MadeReview").size() AS ReviewNumbers
FROM `Customers`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
118
Queries
Recommendations
Example 1
Recommend some friends to Profile 'Isabella Gomez' (friends of friends):
MATCH
{class: Profiles, as: profile, where: (Name = 'Isabella' AND Surname='Gomez')}-HasFriend-{as: friend},
{as: friend}-HasFriend-{as: friendOfFriend, where: ($matched.profile not in $currentMatch.both('HasFriend') and $matched.pro
file != $currentMatch)}
RETURN DISTINCT friendOfFriend.Name
In the Browse Tab of Studio, using the query above, this is the obtained list of records (only few records are shown in the image below):
Example 2
Recommend some Hotels to Customer with OrderedId 1:
MATCH
{Class: Customers, as: customer, where: (OrderedId=1)}-HasProfile->{class: Profiles, as: profile},
{as: profile}-HasFriend->{class: Profiles, as: friend},
{as: friend}<-HasProfile-{Class: Customers, as: customerFriend},
{as: customerFriend}-HasStayed->{Class: Hotels, as: hotel},
{as: customerFriend}-MadeReview->{Class: Reviews, as: review},
{as: hotel}-HasReview->{as: review}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
119
Queries
To filter additionally, and suggest only the 4 and 5-rated hotels, it is possible to add a filter condition on the 'HasReview' edge (property
'Stars'):
MATCH
{Class: Customers, as: customer, where: (OrderedId=1)}-HasProfile->{class: Profiles, as: profile},
{as: profile}-HasFriend->{class: Profiles, as: friend},
{as: friend}<-HasProfile-{Class: Customers, as: customerFriend},
{as: customerFriend}-HasStayed->{Class: Hotels, as: hotel},
{as: customerFriend}-MadeReview->{Class: Reviews, as: review},
{as: hotel}.outE('HasReview'){as: ReviewStars, where: (Stars>3)}.inV(){as: review}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
120
Queries
Business Opportunities
Example 1
Find all the Friends of Customer identified with OrderedId 1 that are not Customers (so that a product can be proposed):
SELECT
@Rid as Friend_RID,
Name as Friend_Name,
Surname as Friend_Surname
FROM (
SELECT expand(customerFriend)
FROM (
MATCH {Class:Customers, as: customer, where:(OrderedId=1)}-HasProfile-{Class:Profiles, as: profile}-HasFriend-{Class:Profi
les, as: customerFriend} RETURN customerFriend
)
)
WHERE in('HasProfile').size()=0
ORDER BY Friend_Name ASC
In the Browse Tab of Studio, using the query above, this is the obtained list of records (only few records are shown in the image below):
Example 2
Find all the Customer Friends that are not Customers (so that a product can be proposed).
In the Graph Editor included in Studio, using the query below, this is the obtained graph:
SELECT DISTINCT * FROM (
SELECT expand(customerFriend)
FROM (
MATCH
{Class:Customers, as: customer}-HasProfile-{Class:Profiles, as: profile}-HasFriend-{Class:Profiles, as: customerFriend}
RETURN customerFriend
)
)
WHERE in('HasProfile').size()=0
121
Queries
In the Browse Tab of Studio, using the query below, this is the obtained list of records (only few records are shown in the image below):
SELECT DISTINCT @Rid as Friend_RID, Name as Friend_Name, Surname as Friend_Surname
FROM (
SELECT expand(customerFriend)
FROM (
MATCH
{Class:Customers, as: customer}-HasProfile-{Class:Profiles, as: profile}-HasFriend-{Class:Profiles, as: customerFriend}
RETURN customerFriend
)
)
WHERE in('HasProfile').size()=0
ORDER BY Friend_RID
122
Queries
Polymorphism
Example 1
Find all Locations (Services + Attractions) connected with Customer with OrderedId 1:
MATCH {class: Customers, as: customer, where: (OrderedId=1)}--{Class: Locations, as: location}
RETURN $pathelements
In the Graph Editor included in Studio, using 'RETURN $pathelements' as
RETURN
clause, this is the obtained graph:
In the Browse Tab of Studio, using 'RETURN location.@Rid as Location_RID, location.Name as Location_Name, location.Type as
Location_Type' as
RETURN
clause, this is the obtained list of records (only few records are shown in the image below):
Example 2
Find the 3 Hotels that have most reviews:
123
Queries
SELECT
@rid as Hotel_RID,
Name as Hotel_Name,
Type as Hotel_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Hotels`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
In a similar way:
Find the 3 Restaurants that have most reviews:
SELECT
@rid as Restaurant_RID,
Name as Restaurants_Name,
Type as Restaurants_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Restaurants`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
In a polymorphic way:
Find the 3 Services (Hotels + Restaurants) that have most reviews:
124
Queries
SELECT
@rid as Service_RID,
Name as Service_Name,
Type as Service_Type,
out("HasReview").size() AS ReviewNumbers
FROM `Services`
ORDER BY ReviewNumbers DESC
LIMIT 3
In the Browse Tab of Studio, using the query above, this is the obtained list of records:
125
Queries
Shortest Paths
Example 1
Find the shortest path between the Profile 'Santo' and the Country 'United States':
SELECT expand(path) FROM (
SELECT shortestPath($from, $to) AS path
LET
$from = (SELECT FROM Profiles WHERE Name='Santo' and Surname='OrientDB'),
$to = (SELECT FROM Countries WHERE Name='United States')
UNWIND path
)
In the Graph Editor included in Studio, this is the obtained graph:
In the Browse Tab of Studio, this is the obtained list of records:
Example 2
126
Queries
Find the shortest path between the Profile 'Santo' and the Restaurant 'M alga Granezza':
SELECT expand(path) FROM (
SELECT shortestPath($from, $to) AS path
LET
$from = (SELECT FROM Profiles WHERE Name='Santo' and Surname='OrientDB'),
$to = (SELECT FROM Restaurants WHERE Name='Malga Granezza')
UNWIND path
)
In the Graph Editor included in Studio, this is the obtained graph:
In the Browse Tab of Studio, this is the obtained list of records:
127
Queries
Traverses
Example 1
Traverse everything from Profile 'Santo' up to depth three:
TRAVERSE * FROM (
SELECT FROM Profiles WHERE Name='Santo' and Surname='OrientDB'
) MAXDEPTH 3
In the Graph Editor included in Studio, this is the obtained graph:
In the Browse Tab of Studio, this is the obtained list of records (only few records are shown in the image below):
Example 2
Traverse everything from Country 'Italy' up to depth three:
128
Queries
TRAVERSE * FROM (
SELECT FROM Countries WHERE Name='Italy'
) MAXDEPTH 3
In the Graph Editor included in Studio, this is the obtained graph:
In the Browse Tab of Studio, this is the obtained list of records (only few records are shown in the image below):
129
Graph Portions
Graph Portions
This Section includes some screen-shots on "portions" of the
demodb
graph.
Note: the screen-shots included in this Section have been taken with version 0.76 of the demo database. While the queries remain valid,
future versions of the demo database may include different records.
Profiles
The graph below includes vertices in the Profiles class.
Some profiles have no friends, and ten profile "communities" are easily identifiable (a "community" is a group of highly connected
profiles):
Customers' Friends
The graph below shows the relationships between all customers and their friends.
All customer vertices are connected to their corresponding profiles in the social platform. The profiles may have friends, or not.
130
Graph Portions
Customer-Country Relationship
The graph below shows the relationships between all customers and their countries of origin:
Customer-Restaurant Relationship
Relationships between customers and restaurants are reported in the graph below:
131
Graph Portions
132
Basic SQL
SQL
M ost NoSQL products employ a custom query language. In this, OrientDB differs by focusing on standards in query languages. That is,
instead of inventing "Yet Another Query Language," it begins with the widely used and well-understood language of SQL. It then
extends SQL to support more complex graphing concepts, such as Trees and Graphs.
Why SQL? Because SQL is ubiquitous in the database development world. It is familiar and more readable and concise than its
competitors, such as M ap Reduce scripts or JSON based querying.
SELECT
The
statement queries the database and returns results that match the given parameters. For instance, earlier in Getting Started,
SELECT
two queries were presented that gave the same results:
available through a
orientdb>
SELECT
BROWSE CLUSTER ouser
and
BROWSE CLASS OUser
. Here is a third option,
statement.
SELECT FROM OUser
Notice that the query has no projections. This means that you do not need to enter a character to indicate that the query should return
the entire record, such as the asterisk in the Relational model, (that is,
SELECT * FROM OUser
).
Additionally, OUser is a class. By default, OrientDB executes queries against classes. Targets can also be:
Clusters To execute against a cluster, rather than a class, prefix
orientdb>
CLUSTER
to the target name.
SELECT FROM CLUSTER:Ouser
Record ID To execute against one or more Record ID's, use the identifier(s) as your target. For example.
orientdb>
SELECT FROM #10:3
orientdb>
SELECT FROM [#10:1, #10:30, #10:5]
Indexes To execute a query against an index, prefix
orientdb>
INDEX
to the target name.
SELECT VALUE FROM INDEX:dictionary WHERE key='Jay'
WHERE
M uch like the standard implementation of SQL, OrientDB supports
orientdb>
This returns all
WHERE
WHERE
conditions to filter the returning records too. For example,
SELECT FROM OUser WHERE name LIKE 'l%'
OUser
records where the name begins with
l
. For more information on supported operators and functions, see
.
ORDER BY
In addition to
WHERE
, OrientDB also supports
ORDER BY
clauses. This allows you to order the results returned by the query according
to one or more fields, in either ascending or descending order.
orientdb>
SELECT FROM Employee WHERE city='Rome' ORDER BY surname ASC, name ASC
The example queries the
Employee
class, it returns a listing of all employees in that class who live in Rome and it orders the results by
surname and name, in ascending order.
133
Basic SQL
GROUP BY
In the event that you need results of the query grouped together according to the values of certain fields, you can manage this using the
GROUP BY
clause.
orientdb>
SELECT SUM(salary) FROM Employee WHERE age < 40 GROUP BY job
In the example, you query the
Employee
class for the sum of the salaries of all employees under the age of forty, grouped by their job
types.
LIMIT
In the event that your query returns too many results, making it difficult to read or manage, you can use the
LIMIT
clause to reduce it
to the top most of the return values.
orientdb>
SELECT FROM Employee WHERE gender='male' LIMIT 20
In the example, you query the
Employee
class for a list of male employees. Given that there are likely to be a number of these, you
limit the return to the first twenty entries.
SKIP
When using the
LIMIT
clause with queries, you can only view the topmost of the return results. In the event that you would like to
view certain results further down the list, for instance the values from twenty to forty, you can paginate your results using the
keyword in the
LIMIT
SKIP
clause.
orientdb>
SELECT FROM Employee WHERE gender='male' LIMIT 20
orientdb>
SELECT FROM Employee WHERE gender='male' SKIP 20 LIMIT 20
orientdb>
SELECT FROM Employee WHERE gender='male' SKIP 40 LIMIT 20
The first query returns the first twenty results, the second returns the next twenty results, the third up to sixty. You can use these
queries to manage pages at the application layer.
INSERT
The
INSERT
statement adds new data to a class and cluster. OrientDB supports three forms of syntax used to insert new data into your
database.
The standard ANSI-92 syntax:
orientdb>
INSERT INTO
Employee(name, surname, gender)
VALUES('Jay', 'Miner', 'M')
The simplified ANSI-92 syntax:
orientdb>
INSERT INTO Employee SET name='Jay', surname='Miner', gender='M'
The JSON syntax:
orientdb>
INSERT INTO Employee CONTENT {name : 'Jay', surname : 'Miner',
gender : 'M'}
Each of these queries adds Jay M iner to the
Employee
class. You can choose whichever syntax that works best with your application.
134
Basic SQL
UPDATE
The
UPDATE
statement changes the values of existing data in a class and cluster. In OrientDB there are two forms of syntax used to
update data on your database.
The standard ANSI-92 syntax:
orientdb>
UPDATE Employee SET local=TRUE WHERE city='London'
The JSON syntax, used with the
orientdb>
MERGE
keyword, which merges the changes with the current record:
UPDATE Employee MERGE { local : TRUE } WHERE city='London'
Each of these statements updates the
Employee
class, changing the
local
property to
TRUE
when the employee is based in London.
DELETE
The
DELETE
statement removes existing values from your class and cluster. OrientDB supports the standard ANSI-92 compliant
syntax for these statements:
orientdb>
DELETE FROM Employee WHERE city <> 'London'
Here, entries are removed from the
Employee
class where the employee in question is not based in London.
S ee also:
The SQL Reference
The Console Command Reference
135
Users, Roles and Security
Users, Roles and Security
136
Distributed Architecture
Distributed Architecture
137
Tutorials
Tutorials
This Section includes all the Tutorials available in this M anual.
138
Working with Graphs
Working with Graphs
In graph databases, the database system graphs data into network-like structures consisting of vertices and edges. In the OrientDB
Graph model, the database represents data through the concept of a property graph, which defines a vertex as an entity linked with
other vertices and an edge, as an entity that links two vertices.
OrientDB ships with a generic vertex persistent class, called
new vertex using the
orientdb>
INSERT
command with
V
V
, as well as a class for edges, called
E
. As an example, you can create a
.
INSERT INTO V SET name='Jay'
Created record with RID #9:0
In effect, the Graph model database works on top of the underlying document model. But, in order to simplify this process, OrientDB
introduces a new set of commands for managing graphs from the console. Instead of
orientdb>
INSERT
, use
CREATE VERTEX
CREATE VERTEX V SET name='Jay'
Created vertex with RID #9:1
By using the graph commands over the standard SQL syntax, OrientDB ensures that your graphs remain consistent. For more
information on the particular commands, see the following pages:
CREATE VERTEX
DELETE VERTEX
CREATE EDGE
UPDATE EDGE
DELETE EDGE
Use Case: Social Network for Restaurant Patrons
While you have the option of working with vertexes and edges in your database as they are, you can also extend the standard
E
V
and
classes to suit the particular needs of your application. The advantages of this approach are,
It grants better understanding about the meaning of these entities.
It allows for optional constraints at the class level.
It improves performance through better partitioning of entities.
It allows for object-oriented inheritance among the graph elements.
For example, consider a social network based on restaurants. You need to start with a class for individual customers and another for the
restaurants they patronize. Create these classes to extend the
orientdb>
CREATE CLASS Person EXTENDS V
orientdb>
CREATE CLASS Restaurant EXTENDS V
V
class.
Doing this creates the schema for your social network. Now that the schema is ready, populate the graph with data.
139
Working with Graphs
orientdb>
CREATE VERTEX Person SET name='Luca'
Created record with RID #11:0
orientdb>
CREATE VERTEX Person SET name='Bill'
Created record with RID #11:1
orientdb>
CREATE VERTEX Person SET name='Jay'
Created record with RID #11:2
orientdb>
CREATE VERTEX Restaurant SET name='Dante', type='Pizza'
Created record with RID #12:0
orientdb>
CREATE VERTEX Restaurant SET name='Charlie', type='French'
Created record with RID #12:1
This adds three vertices to the
Restaurant
Person
class, representing individual users in the social network. It also adds two vertices to the
class, representing the restaurants that they patronize.
Creating Edges
For the moment, these vertices are independent of one another, tied together only by the classes to which they belong. That is, they are
not yet connected by edges. Before you can make these connections, you first need to create a class that extends
orientdb>
.
CREATE CLASS Eat EXTENDS E
This creates the class
Restaurant
E
Eat
, which extends the class
E
.
Eat
represents the relationship between the vertex
Person
and the vertex
.
When you create the edge from this class, note that the orientation of the vertices is important, because it gives the relationship its
meaning. For instance, creating an edge in the opposite direction, (from
as
Attendee
Restaurant
to
Person
), would call for a separate class, such
.
The user Luca eats at the pizza joint Dante. Create an edge that represents this connection:
orientdb>
CREATE EDGE Eat FROM ( SELECT FROM Person WHERE name='Luca' )
TO ( SELECT FROM Restaurant WHERE name='Dante' )
Creating Edges from Record ID
In the event that you know the Record ID of the vertices, you can connect them directly with a shorter and faster command. For
example, the person Bill also eats at the restaurant Dante and the person Jay eats at the restaurant Charlie. Create edges in the class
Eat
to represent these connections.
orientdb>
CREATE EDGE Eat FROM #11:1 TO #12:0
orientdb>
CREATE EDGE Eat FROM #11:2 TO #12:1
140
Working with Graphs
Querying Graphs
In the above example you created and populated a small graph of a social network of individual users and the restaurants at which they
eat. You can now begin to experiment with queries on a graph database.
To cross edges, you can use special graph functions, such as:
To retrieve the adjacent outgoing vertices
OUT()
IN()
To retrieve the adjacent incoming vertices
To retrieve the adjacent incoming and outgoing vertices
BOTH()
For example, to know all of the people who eat in the restaurant Dante, which has a Record ID of
that restaurant and traverse the incoming edges to discover which entries in the
orientdb>
Person
#12:0
, you can access the record for
class connect to it.
SELECT IN() FROM Restaurant WHERE name='Dante'
-------+----------------+
@RID
| in
|
-------+----------------+
#-2:1 | [#11:0, #11:1] |
-------+----------------+
This query displays the record ID's from the
EXPAND()
Person
class that connect to the restaurant Dante. In cases such as this, you can use the
special function to transform the vertex collection in the result-set by expanding it.
orientdb>
SELECT EXPAND( IN() ) FROM Restaurant WHERE name='Dante'
-------+-------------+-------------+---------+
@RID
| @CLASS
| Name
| out_Eat |
-------+-------------+-------------+---------+
#11:0 | Person
| Luca
| #12:0
|
#11:1 | Person
| Bill
| #12:0
|
-------+-------------+-------------+---------+
Creating Edge to Connect Users
Your application at this point shows connections between individual users and the restaurants they patronize. While this is interesting,
it does not yet function as a social network. To do so, you need to establish edges that connect the users to one another.
To begin, as before, create a new class that extends
orientdb>
E
:
CREATE CLASS Friend EXTENDS E
The users Luca and Jay are friends. They have Record ID's of
orientdb>
In the
Friend
#11:0
and
#11:2
. Create an edge that connects them.
CREATE EDGE Friend FROM #11:0 TO #11:2
relationship, orientation is not important. That is, if Luca is a friend of Jay's then Jay is a friend of Luca's. Therefore,
you should use the
BOTH()
function.
141
Working with Graphs
orientdb>
SELECT EXPAND( BOTH( 'Friend' ) ) FROM Person WHERE name = 'Luca'
-------+-------------+-------------+---------+-----------+
@RID
| @CLASS
| Name
| out_Eat | in_Friend |
-------+-------------+-------------+---------+-----------+
#11:2 | Person
| Jay
| #12:1
| #11:0
|
-------+-------------+-------------+---------+-----------+
Here, the
the
Eat
BOTH()
function takes the edge class
Friend
as an argument, crossing only relationships of the Friend kind, (that is, it skips
class, at this time). Note in the result-set that the relationship with Luca, with a Record ID of
#11:0
in the
in_
field.
You can also now view all the restaurants patronized by friends of Luca.
orientdb>
SELECT EXPAND( BOTH('Friend').out('Eat') ) FROM Person
WHERE name='Luca'
-------+-------------+-------------+-------------+--------+
@RID
| @CLASS
| Name
| Type
| in_Eat |
-------+-------------+-------------+-------------+--------+
#12:1 | Restaurant
| Charlie
| French
| #11:2
|
-------+-------------+-------------+-------------+--------+
Lightweight Edges
In version 1.4.x, OrientDB begins to manage some edges as Lightweight Edges. Lightweight Edges do not have Record ID's, but are
physically stored as links within vertices. Note that OrientDB only uses a Lightweight Edge only when the edge has no properties,
otherwise it uses the standard Edge.
From the logic point of view, Lightweight Edges are Edges in all effects, so that all graph functions work with them. This is to improve
performance and reduce disk space.
Because Lightweight Edges don't exist as separate records in the database, some queries won't work as expected. For instance,
orientdb>
SELECT FROM E
For most cases, an edge is used connecting vertices, so this query would not cause any problems in particular. But, it would not return
Lightweight Edges in the result-set. In the event that you need to query edges directly, including those with no properties, disable the
Lightweight Edge feature.
To disable the Lightweight Edge feature, execute the following command.
orientdb>
ALTER DATABASE CUSTOM useLightweightEdges=FALSE
You only need to execute this command once. OrientDB now generates new edges as the standard Edge, rather than the Lightweight
Edge. Note that this does not affect existing edges.
For troubleshooting information on Lightweight Edges, see Why I can't see all the edges. For more information in the Graph model in
OrientDB, see Graph API.
142
Using Schema with Graphs
Using Schema with Graphs
OrientDB, through the Graph API, offers a number of features above and beyond the traditional Graph Databases given that it supports
concepts drawn from both the Document Database and the Object Oriented worlds. For instance, consider the power of graphs, when
used in conjunction with schemas and constraints.
Use Case: Car Database
For this example, consider a graph database that maps the relationship between individual users and their cars. First, create the graph
schema for the
Person
and
Car
vertex classes, as well as the
orientdb>
CREATE CLASS Person EXTENDS V
orientdb>
CREATE CLASS Car EXTENDS V
orientdb>
CREATE CLASS Owns EXTENDS E
Owns
edge class to connect the two:
These commands lay out the schema for your graph database. That is, they define two vertex classes and an edge class to indicate the
relationship between the two. With that, you can begin to populate the database with vertices and edges.
orientdb>
CREATE VERTEX Person SET name = 'Luca'
Created vertex 'Person#11:0{name:Luca} v1' in 0,012000 sec(s).
orientdb>
CREATE VERTEX Car SET name = 'Ferrari Modena'
Created vertex 'Car#12:0{name:Ferrari Modena} v1' in 0,001000 sec(s).
orientdb>
CREATE EDGE Owns FROM ( SELECT FROM Person ) TO ( SELECT FROM Car )
Created edge '[e[#11:0->#12:0][#11:0-Owns->#12:0]]' in 0,005000 sec(s).
Querying the Car Database
In the above section, you create a car database and populated it with vertices and edges to map out the relationship between drivers and
their cars. Now you can begin to query this database, showing what those connections are. For example, what is Luca's car? You can find
out by traversing from the vertex Luca to the outgoing vertices following the
orientdb>
Owns
relationship.
SELECT name FROM ( SELECT EXPAND( OUT('Owns') ) FROM Person
WHERE name='Luca' )
----+-------+-----------------+
#
| @RID
| name
|
----+-------+-----------------+
0
| #-2:1 | Ferrari Modena
|
----+-------+-----------------+
As you can see, the query returns that Luca owns a Ferrari M odena. Now consider expanding your database to track where each person
lives.
143
Using Schema with Graphs
Adding a Location Vertex
Consider a situation, in which you might want to keep track of the countries in which each person lives. In practice, there are a number
of reasons why you might want to do this, for instance, for the purposes of promotional material or in a larger database to analyze the
connections to see how residence affects car ownership.
To begin, create a vertex class for the country, in which the person lives and an edge class that connects the individual to the place.
orientdb>
CREATE CLASS Country EXTENDS V
orientdb>
CREATE CLASS Lives EXTENDS E
This creates the schema for the feature you're adding to the cars database. The vertex class
people live and the edge class
Lives
to connect individuals in the vertex class
Person
Country
recording countries in which
to entries in
Country
.
With the schema laid out, create a vertex for the United Kingdom and connect it to the person Luca.
orientdb>
CREATE VERTEX Country SET name='UK'
Created vertex 'Country#14:0{name:UK} v1' in 0,004000 sec(s).
orientdb>
CREATE EDGE Lives FROM ( SELECT FROM Person ) TO ( SELECT FROM Country
Created edge '[e[#11:0->#14:0][#11:0-Lives->#14:0]]' in 0,006000 sec(s).
The second command creates an edge connecting the person Luca to the country United Kingdom. Now that your cars database is
defined and populated, you can query it, such as a search that shows the countries where there are users that own a Ferrari.
orientdb>
SELECT name FROM ( SELECT EXPAND( IN('Owns').OUT('Lives') )
FROM Car WHERE name LIKE '%Ferrari%' )
---+-------+--------+
# | @RID
| name
|
---+-------+--------+
0 | #-2:1 | UK
|
---+-------+--------+
Using in and out Constraints on Edges
In the above sections, you modeled the graph using a schema without any constraints, but you might find it useful to use some. For
instance, it would be good to require that an
Owns
relationship only exist between the vertex
orientdb>
CREATE PROPERTY Owns.out LINK Person
orientdb>
CREATE PROPERTY Owns.in LINK Car
These commands link outgoing vertices of the
Person
class to incoming vertices of the
Car
Person
and the vertex
Car
.
class. That is, it configures your database
so that a user can own a car, but a car cannot own a user.
Using MANDATORY Constraints on Edges
By default, when OrientDB creates an edge that lacks properties, it creates it as a Lightweight Edge. That is, it creates an edge that has
no physical record in the database. Using the
MANDATORY
setting, you can stop this behavior, forcing it to create the standard Edge,
without outright disabling Lightweight Edges.
144
Using Schema with Graphs
orientdb>
ALTER PROPERTY Owns.out MANDATORY TRUE
orientdb>
ALTER PROPERTY Owns.in MANDATORY TRUE
Using UNIQUE with Edges
For the sake of simplicity, consider a case where you want to limit the way people are connected to cars to where the user can only
match to the car once. That is, if Luca owns a Ferrari M odena, you might prefer not to have a double entry for that car in the event that
he buys a new one a few years later. This is particularly important given that our database covers make and model, but not year.
To manage this, you need to define a
orientdb>
UNIQUE
index against both the out and in properties.
CREATE INDEX UniqueOwns ON Owns(out,in) UNIQUE
Created index successfully with 0 entries in 0,023000 sec(s).
The index returns tells us that no entries are indexed. You have already created the
Onws
relationship between Luca and the Ferrari
M odena. In that case, however, OrientDB had created a Lightweight Edge before you set the rule to force the creation of documents for
Owns
instances. To fix this, you need to drop and recreate the edge.
orientdb>
DELETE EDGE FROM #11:0 TO #12:0
orientdb>
CREATE EDGE Owns FROM ( SELECT FROM Person ) TO ( SELECT FROM Car )
To confirm that this was successful, run a query to check that a record was created:
orientdb>
SELECT FROM Owns
---+-------+-------+--------+
# | @RID
| out
| in
|
---+-------+-------+--------+
0 | #13:0 | #11:0 | #12:0
|
---+-------+-------+--------+
This shows that a record was indeed created. To confirm that the constraints work, attempt to create an edge in
Owns
that connects
Luca to the United Kingdom.
orientdb>
CREATE EDGE Owns FROM ( SELECT FROM Person ) TO ( SELECT FROM Country )
Error: com.orientechnologies.orient.core.exception.OCommandExecutionException:
Error on execution of command: sql.create edge Owns from (select from Person)...
Error: com.orientechnologies.orient.core.exception.OValidationException: The
field 'Owns.in' has been declared as LINK of type 'Car' but the value is the
document #14:0 of class 'Country'
This shows that the constraints effectively blocked the creation, generating a set of errors to explain why it was blocked.
You now have a typed graph with constraints. For more information, see Graph Schema.
145
Setup a Distributed Database
Setting up a Distributed Graph Database
In addition to the standard deployment architecture, where it runs as a single, standalone database instance, you can also deploy
OrientDB using Distributed Architecutre. In this environment, it shares the database across multiple server instances.
Launching Distributed Server Cluster
There are two ways to share a database across multiple server nodes:
Prior to startup, copy the specific database directory, under
to all servers.
$ORIENTDB_HOME/database
Keep the database on the first running server node, then start every other server node. Under the default configurations, OrientDB
automatically shares the database with the new servers that join.
This tutorial assumes that you want to start a distributed database using the second method.
NOTE: When you run in distributed mode, OrientDB needs more RAM. The minimum is 2GB of heap, but we suggest to use at least 4GB
of heap memory. To change the heap modify the Java memory settings in the file
bin/dserver.sh
(or dserver.bat on Windows).
Starting the First Server Node
Unlike the standard standalone deployment of OrientDB, there is a different script that you need to use when launching a distributed
server instance. Instead of
find it in the
$
bin
server.sh
, you use
dserver.sh
. In the case of Windows, use
dserver.bat
. Whichever you need, you can
of your installation directory.
./bin/dserver.sh
Bear in mind that OrientDB uses the same
orientdb-server-config.xml
configuration file, regardless of whether it's running as a server
or distributed server. For more information, see Distributed Configuration.
The first time you start OrientDB as a distributed server, it generates the following output:
+---------------------------------------------------------------+
|
WARNING: FIRST DISTRIBUTED RUN CONFIGURATION
|
+---------------------------------------------------------------+
| This is the first time that the server is running as
|
| distributed. Please type the name you want to assign to the
|
| current server node.
|
|
|
| To avoid this message set the environment variable or JVM
|
| setting ORIENTDB_NODE_NAME to the server node name to use.
|
+---------------------------------------------------------------+
Node name [BLANK=auto generate it]:
You need to give the node a name here. OrientDB stores it in the
your
orientdb-server-config.xml
nodeName
parameter of
OHazelcastPlugin
. It adds the variable to
configuration file.
Distributed Startup Process
When OrientDB starts as a distributed server instance, it loads all databases in the
database
directory and configures them to run in
distributed mode. For this reason, the first load, OrientDB copies the default distributed configuration, (that is, the
distributed-db-config.json
configuration file), into each database's directory, renaming it
distributed-config.json
default-
. On subsequent
starts, each database uses this file instead of the default configuration file. Since the shape of the cluster changes every time nodes join or
leave, the configuration is kept up to date by each distributed server instance.
For more information on working with the
default-distributed-db-config.json
configuration file, see Distributed Configuration.
Starting Additional Server Nodes
146
Setup a Distributed Database
When you have the first server node running, you can begin to start the other server nodes. Each server requires the same Hazelcast
credentials in order to join the same cluster. You can define these in the
hazelcast.xml
configuration file.
The fastest way to initialize multiple server nodes is to copy the OrientDB installation directory from the first node to each of the
subsequent nodes. For instance,
$
scp user@ip_address $ORIENTDB_HOME
This copies both the databases and their configuration files onto the new distributed server node.
Bear in mind, if you run multiple server instances on the same host, such as when testing, you need to change the port entry in
the
hazelcast.xml
configuration file.
For the other server nodes in the cluster, use the same
dserver.sh
command as you used in starting the first node. When the other
server nodes come online, they begin to establish network connectivity with each other. M onitoring the logs, you can see where they
establish connections from messages such as this:
WARN [node1384014656983] added new node id=Member [192.168.1.179]:2435 name=null
[OHazelcastPlugin]
INFO [192.168.1.179]:2434 [orientdb] Re-partitioning cluster data... Migration
queue size: 135 [PartitionService]
INFO [192.168.1.179]:2434 [orientdb] All migration tasks has been completed,
queues are empty. [PartitionService]
INFO [node1384014656983] added node configuration id=Member [192.168.1.179]:2435
name=node1384015873680, now 2 nodes are configured [OHazelcastPlugin]
INFO [node1384014656983] update configuration db=GratefulDeadConcerts
from=node1384015873680 [OHazelcastPlugin]
INFO updated distributed configuration for database: GratefulDeadConcerts:
---------{
"replication": true,
"autoDeploy": true,
"hotAlignment": true,
"resyncEvery": 15,
"clusters": {
"internal": {
"replication": false
},
"index": {
"replication": false
},
"*": {
"replication": true,
"readQuorum": 1,
"writeQuorum": 2,
"failureAvailableNodesLessQuorum": false,
"readYourWrites": true,
"partitioning":{
"strategy": "round-robin",
"default":0,
"partitions": ["","node1383734730415","node1384015873680"]("","node1383734730415","node1384015873680".md)
}
}
},
"version": 1
}
---------- [OHazelcastPlugin]
WARN [node1383734730415]->[node1384015873680] deploying database
GratefulDeadConcerts...[ODeployDatabaseTask]
WARN [node1383734730415]->[node1384015873680] sending the compressed database
GratefulDeadConcerts over the network, total 339,66Kb [ODeployDatabaseTask]
147
Setup a Distributed Database
In the example, two server nodes were started on the same machine. It has an IP address of 10.37.129.2, but is using OrientDB on two
different ports: 2434 and 2435, where the current is called
this
. The remainder of the log is relative to the distribution of the database
to the second server.
On the second server node output, OrientDB dumps messages like this:
WARN [node1384015873680]<-[node1383734730415] installing database
GratefulDeadConcerts in databases/GratefulDeadConcerts... [OHazelcastPlugin]
WARN [node1384015873680] installed database GratefulDeadConcerts in
databases/GratefulDeadConcerts, setting it online... [OHazelcastPlugin]
WARN [node1384015873680] database GratefulDeadConcerts is online [OHazelcastPlugin]
WARN [node1384015873680] updated node status to 'ONLINE' [OHazelcastPlugin]
INFO OrientDB Server v1.6.1-SNAPSHOT is active. [OServer]
What these messages mean is that the database
node1383734730415
GratefulDeadConcerts
was correctly installed from the first node, that is
through the network.
Migrating from standalone server to a cluster
If you have a standalone instance of OrientDB and you want to move to a cluster you should follow these steps:
Install OrientDB on all the servers of the cluster and configure it (according to the sections above)
Stop the standalone server
Copy the specific database directories under
$ORIENTDB_HOME/database
Start all the servers in the cluster using the script
dserver.sh
(or
to all the servers of the cluster
dserver.bat
if on Windows)
If the standalone server will be part of the cluster, you can use the existing installation of OrientDB; you don't need to copy the
database directories since they're already in place and you just have to start it before all the other servers with
dserver.sh
.
148
Working with Distributed Graphs
Working with Distributed Graphs
When OrientDB joins a distributed cluster, all clients connecting to the server node are constantly notified about this state. This ensures
that, in the event that server node fails, the clients can switch transparently to the next available server.
You can check this through the console. When OrientDB runs in a distributed configuration, the current cluster shape is visible through
the
$
INFO
command.
$ORIENTDB_HOME/bin/console.sh
OrientDB console v.1.6 www.orientechnologies.com
Type 'help' to display all the commands supported.
Installing extensions for GREMLIN language v.2.5.0-SNAPSHOT
orientdb>
CONNECT remote:localhost/GratefulDeadConcerts admin admin
Connecting to database [remote:localhost/GratefulDeadConcerts] with user 'admin'...OK
orientdb>
INFO
Current database: GratefulDeadConcerts (url=remote:localhost/GratefulDeadConcerts)
For reference purposes, the server nodes in the example have the following configurations. As you can see, it is a two node cluster
running a single server host. The first node listens on port
2481
while the second on port
2480
.
+---------+------+-----------------------------------------+-----+---------+--------------+--------------+----------------------+
|Name
|Status|Databases
|Conns|StartedOn|Binary
|HTTP
|UsedMemory
|
+---------+------+-----------------------------------------+-----+---------+--------------+--------------+----------------------+
|europe-0 |ONLINE|distributed-node-deadlock=ONLINE (MASTER)|5
|16:53:59 |127.0.0.1:2424|127.0.0.1:2480|269.32MB/3.56GB (7.40
%)|
|europe-1 |ONLINE|distributed-node-deadlock=ONLINE (MASTER)|4
|16:54:03 |127.0.0.1:2425|127.0.0.1:2481|268.89MB/3.56GB (7.38
%)|
+---------+------+-----------------------------------------+-----+---------+--------------+--------------+----------------------+
Testing Distributed Architecture
Once you have a distributed database up and running, you can begin to test its operations on a running environment. For example, begin
by creating a vertex, setting the
orientdb>
node
property to
1
.
CREATE VERTEX V SET node = 1
Created vertex 'V#9:815{node:1} v1' in 0,013000 sec(s).
From another console, connect to the second node and execute the following command:
149
Working with Distributed Graphs
orinetdb>
SELECT FROM V WHERE node = 1
----+--------+-------+
#
| @RID
| node
|
----+--------+-------+
0
| #9:815 | 1
|
----+--------+-------+
1 item(s) found. Query executed in 0.19 sec(s).
This shows that the vertex created on the first node has successfully replicated to the second node.
Logs in Distributed Architecture
From time to time server nodes go down. This does not necessarily relate to problems in OrientDB, (for instance, it could originate from
limitations in system resources).
To test this out, kill the first node. For example, assuming the first node has a process identifier, (that is, a PID), of
1254
on your
system, run the following command:
$
kill -9 1254
This command kills the process on PID
$
1254
. Now, check the log messages for the second node:
less orientdb.log
INFO [127.0.0.1]:2435 [orientdb] Removing Member [127.0.0.1]:2434
[ClusterService]
INFO [127.0.0.1]:2435 [orientdb]
Members [1] {
Member [127.0.0.1]:2435 this
}
[ClusterService]
WARN [europe-0] node removed id=Member [127.0.0.1]:2434
name=europe-1 [OHazelcastPlugin]
INFO [127.0.0.1]:2435 [orientdb] Partition balance is ok, no need to
re-partition cluster data...
[PartitionService]
What the logs show you is that the second node is now aware that it cannot reach the first node. You can further test this by running the
console connected to the first node..
orientdb>
SELECT FROM V LIMIT 2
WARN Caught I/O errors from /127.0.0.1:2425 (local
socket=0.0.0.0/0.0.0.0:51512), trying to reconnect (error:
java.io.IOException: Stream closed) [OStorageRemote]
WARN Connection re-acquired transparently after 30ms and 1 retries: no errors
will be thrown at application level [OStorageRemote]
---+------+----------------+--------+--------------+------+-----------------+----# | @RID | name
| song_type | performances | type | out_followed_by | ...
---+------+----------------+--------+--------------+------+-----------------+----1 | #9:1 | HEY BO DIDDLEY | cover
| 5
| song | [5]
| ...
2 | #9:2 | IM A MAN
| 1
| song | [2]
| ...
| cover
---+------+----------------+--------+--------------+------+-----------------+-----
150
Working with Distributed Graphs
This shows that the console auto-switched to the next available node. That is, it switched to the second node upon noticing that the first
was no longer functional. The warnings reports show what happened in a transparent way, so that the application doesn't need to
manage the issue.
From the console connected to the second node, create a new vertex.
orientdb>
CREATE VERTEX V SET node=2
Created vertex 'V#9:816{node:2} v1' in 0,014000 sec(s).
Given that the first node remains nonfunctional, OrientDB journals the operation. Once the first node comes back online, the second
node synchronizes the changes into it.
Restart the first node and check that it successfully auto-realigns. Reconnect the console to the first node and run the following
command:
orientdb>
SELECT FROM V WHERE node=2
---+--------+-------+
# | @RID
| node
|
---+--------+-------+
0 | #9:816 | 2
|
---+--------+-------+
1 item(s) found. Query executed in 0.209 sec(s).
This shows that the first node has realigned itself with the second node.
This process is repeatable with N server nodes, where every server is a master. There is no limit to the number of running servers. With
many servers spread across a slow network, you can tune the network timeouts to be more permissive and let a large, distributed cluster
of servers work properly.
For more information, Distributed Architecture.
151
Time Series
Time Series Use Case
M anaging records related to historical information is pretty common. When you have millions of records, indexes start show their
limitations, because the cost to find the records is O(logN). This is also the main reason why Relational DBM S are so slow with huge
databases.
So when you have millions of record the best way to scale up linearly is avoid using indexes at all or as much as you can. But how can
you retrieve records in a short time without indexes? Should OrientDB scan the entire database at every query? No. You should use the
Graph properties of OrientDB. Let's look at a simple example, where the domain are logs.
A typical log record has some information about the event and a date. Below is the Log record to use in our example. We're going to use
the JSON format to simplify reading:
{
"date" : 12293289328932,
"priority" : "critical",
"note" : "System reboot"
}
Now let's create a tree (that is a directed, non cyclic graph) to group the Log records based on the granularity we need. Example:
Year -> month (map) -> Month -> day (map) -> Day -> hour
(map) -> Hour
Where Year, M onth, Day and Hour are vertex classes. Each Vertex links the other Vertices of smaller type. The links should be handled
using a M ap to make easier the writing of queries.
Create the classes:
CREATE CLASS Year
CREATE CLASS Month
CREATE CLASS Day
CREATE CLASS Hour
CREATE PROPERTY Year.month LINKMAP Month
CREATE PROPERTY Month.day LINKMAP Day
CREATE PROPERTY Day.hour LINKMAP Hour
Example to retrieve the vertex relative to the date M arch 2012, 20th at 10am (2012/03/20 10:00:00):
SELECT month[3].day[20].hour[10].logs FROM Year WHERE year = "2012"
If you need more granularity than the Hour you can go ahead until the Time unit you need:
Hour -> minute (map) -> Minute -> second (map) -> Second
Now connect the record to the right Calendar vertex. If the usual way to retrieve Log records is by hour you could link the Log records
in the Hour. Example:
Year -> month (map) -> Month -> day (map) -> Day -> hour
(map) -> Hour -> log (set) -> Log
The "log" property connects the Time Unit to the Log records. So to retrieve all the log of M arch 2012, 20th at 10am:
SELECT expand( month[3].day[20].hour[10].logs ) FROM Year WHERE year = "2012"
That could be used as starting point to retrieve only a sub-set of logs that satisfy certain rules. Example:
152
Time Series
SELECT FROM (
SELECT expand( month[3].day[20].hour[10].logs ) FROM Year WHERE year = "2012"
) WHERE priority = 'critical'
That retrieves all the CRITICAL logs of M arch 2012, 20th at 10am.
Join multiple hours
If you need multiple hours/days/months as result set you can use the UNION function to create a unique result set:
SELECT expand( records ) from (
SELECT union( month[3].day[20].hour[10].logs, month[3].day[20].hour[11].logs ) AS records
FROM Year WHERE year = "2012"
)
In this example we create a union between the 10th and 11th hours. But what about extracting all the hours of a day without writing a
huge query? The shortest way is using the Traverse. Below the Traverse to get all the hours of one day:
TRAVERSE hour FROM (
SELECT expand( month[3].day[20] ) FROM Year WHERE year = "2012"
)
So putting all together this query will extract all the logs of all the hours in a day:
SELECT expand( logs ) FROM (
SELECT union( logs ) AS logs FROM (
TRAVERSE hour FROM (
SELECT expand( month[3].day[20] ) FROM Year WHERE year = "2012"
)
)
)
Aggregate
Once you built up a Calendar in form of a Graph you can use it to store aggregated values and link them to the right Time Unit.
Example: store all the winning ticket of Online Games. The record structure in our example is:
{
"date" : 12293289328932,
"win" : 10.34,
"machine" : "AKDJKD7673JJSH",
}
You can link this record to the closest Time Unit like in the example above, but you could sum all the records in the same Day and link it
to the Day vertex. Example:
Create a new class to store the aggregated daily records:
CREATE CLASS DailyLog
Create the new record from an aggregation of the hour:
INSERT INTO DailyLog
SET win = (
SELECT SUM(win) AS win FROM Hour WHERE date BETWEEN '2012-03-20 10:00:00' AND '2012-03-20 11:00:00'
)
Link it in the Calendar graph assuming the previous command returned #23:45 as the RecordId of the brand new DailyLog record:
153
Time Series
UPDATE (
SELECT expand( month[3].day[20] ) FROM Year WHERE year = "2012"
) ADD logs = #23:45
154
Chat
Chat Use Case
OrientDB allows modeling of rich and complex domains. If you want to develop a chat based application, you can use whatever you
want to create the relationships between User and Room.
We suggest avoiding using Edges or Vertices connected with edges for messages. The best way is using the document API by creating
one class per chat room, with no index, to have super fast access to last X messages. In facts, OrientDB stores new records in append
only, and the @rid is auto generated as incrementing.
The 2 most common use cases in a chat are:
writing a message in a chat room
load last page of messages in a chat room
Create the initial schema
In order to work with the chat rooms, the rule of the thumb is creating a base abstract class ("ChatRoom") and then let to the concrete
classes to represent individual ChatRooms.
Create the base ChatRoom class
create class ChatRoom
alter class ChatRoom abstract true
create property ChatRoom.date datetime
create property ChatRoom.text string
create property ChatRoom.user LINK OUser
Create a new ChatRoom
create class ItalianRestaurant extends ChatRoom
Class "ItalianRestaurant" will extend all the properties from ChatRoom.
Why creating a base class? Because you could always execute polymorphic queries that are cross-chatrooms, like get all the message
from user "Luca":
select from ChatRoom where user.name = 'Luca'
Create a new message in the Chat Room
To create a new message in the chat room you can use this code:
public ODocument addMessage(String chatRoom, String message, OUser user) {
ODocument msg = new ODocument(chatRoom);
msg.field( "date", new Date() );
msg.field( "text", message );
msg.field( "user", user );
msg.save();
return msg;
}
Example:
addMessage("ItalianRestaurant", "Have you ever been at Ponza island?", database.getUser());
155
Chat
Retrieve last messages
You can easily fetch pages of messages ordered by date in descending order, by using the OrientDB's
@rid
. Example:
select from ItalianRestaurant order by @rid desc skip 0 limit 50
You could write a generic method to access to a page of messages, like this:
public Iterable loadMessages(String chatRoom, fromLast, pageSize) {
return graph.getRawGraph().command("select from " + chatRoom + " order by @rid desc skip " + fromLast + " limit " + pageSize
).execute();
}
Loading the 2nd (last) page from chat "ItalianRestaurant", would become this query (with pageSize = 50):
select from ItalianRestaurant order by @rid desc skip 50 limit 50
This is super fast and O(1) even with million of messages.
Limitations
Since OrientDB can handle only 32k clusters, you could have maximum 32k chat rooms. Unless you want to rewrite the entire
FreeNode, 32k chat rooms will be more than enough for most of the cases.
However, if you need more than 32k chat rooms, the suggested solution is still using this approach, but with multiple databases (even
on the same server, because one OrientDB Server instance can handle thousands of databases concurrently).
In this case you could use one database to handle all the metadata, like the following classes:
ChatRoom, containing all the chatrooms, and the database where are stored. Example:
{ "@class": "ChatRoom", "description":
"OrientDB public channel", "databaseName", "db1", "clusterName": "orientdb" }
User, containing all the information about accounts with the edges to the ChatRoom vertices where they are subscribed
OrientDB cannot handle cross-database links, so when you want to know the message's author, you have to look up into the
"M etadata" database by @RID (that is O(1)).
156
Key Value
Key Value Use Case
OrientDB can also be used as a Key Value DBM S by using the super fast Indexes. You can have as many Indexes as you need.
HTTP
OrientDB RESTful HTTP protocol allows to talk with a OrientDB Server instance using the HTTP protocol and JSON. OrientDB
supports also a highly optimized Binary protocol for superior performances.
Operations
To interact against OrientDB indexes use the four methods of the HTTP protocol in REST fashion:
PUT, to create or modify an entry in the database
GET, to retrieve an entry from the database. It's idempotent that means no changes to the database happen. Remember that in IE6
the URL can be maximum of 2,083 characters. Other browsers supports longer URLs, but if you want to stay compatible with all
limit to 2,083 characters
DELETE, to delete an entry from the database
Create an entry
To create a new entry in the database use the Index-PUT API.
Syntax:
http://:[]/index//
Example:
HTTP PUT:
http://localhost:2480/index/customers/jay
{
"name" : "Jay",
"surname" : "Miner"
}
HTTP Response 204 is returned.
Retrieve an entry
To retrieve an entry from the database use the Index-GET API.
Syntax:
http://:[]/index//
Example:
HTTP GET:
http://localhost:2480/index/customers/jay
HTTP Response 200 is returned with this JSON as payload:
{
"name" : "Jay",
"surname" : "Miner"
}
Remove an entry
157
Key Value
To remove an entry from the database use the Index-DELETE API.
Syntax:
http://:[]/index//
Example:
HTTP DELETE:
http://localhost:2480/index/customers/jay
HTTP Response 200 is returned
Step-by-Step tutorial
Before to start assure you've a OrientDB server up and running. In this example we'll use curl considering the connection to localhost to
the default HTTP post 2480. The default "admin" user is used.
Create a new index
To use OrientDB as a Key/Value store we need a brand new manual index, let's call it "mainbucket". We're going to create it as UNIQUE
because keys cannot be duplicated. If you can have multiple keys consider:
creating the index as NOTUNIQUE
leave it as UNIQUE but as value handle array of documents
Create the new manual unique index "mainbucket":
> curl --basic -u admin:admin localhost:2480/command/demo/sql -d "create index mainbucket UNIQUE"
Response:
{ "result" : [
{ "@type" : "d" , "@version" : 0, "value" : 0, "@fieldTypes" : "value=l" }
]
}
Store the first entry
Below we're going to insert the first entry by using the HTTP PUT method passing "jay" as key in the URL and as value the entire
document in form of JSON:
> curl --basic -u admin:admin -X PUT localhost:2480/index/demo/mainbucket/jay -d "{'name':'Jay','surname':'Miner'}"
Response:
Key 'jay' correctly inserted into the index mainbucket.
Retrieve the entry just inserted
Below we're going to retrieve the entry we just entered by using the HTTP GET method passing "jay" as key in the URL:
> curl --basic -u admin:admin localhost:2480/index/demo/mainbucket/jay
Response:
158
Key Value
[{
"@type" : "d" , "@rid" : "#3:477" , "@version" : 0,
"name" : "Jay",
"surname" : "Miner"
}]
Note that an array is always returned in case multiple records are associated to the same key (if NOTUNIQUE index is used). Look also
at the document has been created with RID #3:477. You can load it directly if you know the RID. Remember to remove the # character.
Example:
> curl --basic -u admin:admin localhost:2480/document/demo/3:477
Response:
{
"@type" : "d" , "@rid" : "#3:477" , "@version" : 0,
"name" : "Jay",
"surname" : "Miner"
}
Drop an index
Once finished drop the index "mainbucket" created for the example:
> curl --basic -u admin:admin localhost:2480/command/demo/sql -d "drop index mainbucket"
Response:
{ "result" : [
{ "@type" : "d" , "@version" : 0, "value" : 0, "@fieldTypes" : "value=l" }
]
}
159
Queue system
Distributed queues use case
Implementing a persistent, distributed and transactional queue system using OrientDB is possible and easy. Besides the fact you don't
need a specific API accomplish a queue, there are multiple approaches you can follow depending by your needs. The easiest way is
using OrientDB SQL, so this works with any driver.
Create the queue class first:
create class queue
You could have one class per queue. Example of push operation:
insert into queue set text = "this is the first message", date = date()
Since OrientDB by default keeps the order of creation of records, a simple delete from the queue class with limit = 1 gives to you the
perfect pop:
delete from queue return before limit 1
The "return before" allows you to have the deleted record content. If you need to peek the queue, you can just use the select:
select from queue limit 1
That's it. Your queue will be persistent, if you want transactional and running in cluster distributed.
160
Import Tutorials
Import Tutorials
This section includes some import-to-OrientDB tutorials.
161
Import Tutorials
Tutorial: Importing the Open Beer Database into OrientDB
In this tutorial we will use the OrientDB's ETL module to import, as a graph, the Open Beer Database.
Note: You can access directly the converted database, result of this ETL tutorial, in the following ways:
S tudio: in the login page press the "Cloud" button, put server's credential and press the download button from the "OpenBeer"
row;
Direct Download: download the database from http://orientdb.com/public-databases/OpenBeer.zip and unzip it in a OpenBeer
folder inside OrientDB's server "databases" directory.
The Open Beer Database
The Open Beer Database can be downloaded in CSV format from https://openbeerdb.com/. The following image shows its relational
model:
Preliminary Steps
First, please create a new folder somewhere in your hard drive, and move into it. For this test we will assume
/temp/openbeer
:
$ mkdir /temp/openbeer
$ cd /temp/openbeer
162
Import Tutorials
Download the Open Beer Database in CSV format
Download the Open Beer Database in CSV format and extract the archive:
$ curl http://openbeerdb.com/files/openbeerdb_csv.zip > openbeerdb_csv.zip
$ unzip openbeerdb_csv.zip
The archive consists of the following files:
beers.csv:
contains the beer records
breweries.csv:
contains the breweries records
breweries_geocode.csv
categories.csv
styles.csv
: contains the geocodes of the breweries. This file is not used in this Tutorial
: contains the beer categories
: contains the beer styles
Install OrientDB
Download and install OrientDB:
$ wget http://orientdb.com/download.php?file=orientdb-community-importers-3.0.0RC1.tar.gz&utm_source=Labs&utm_medium=link&utm_
campaign=300 -O orientdb-community-3.0.0RC1.tar.gz
$ tar xvf orientdb-community-3.0.0RC1.tar.gz
For more information on how to install OrientDB, please refer to the Installation section.
Graph Data Model
Before starting the ETL process it's important to understand how the Open Beer Database can be modeled as a graph.
The relational model of the Open Beer Database can be easily converted to a graph model, as shown below:
The model above consists of the following nodes (or vertices) and relationships (or edges):
Nodes: Beer, Category, Style, Brewery;
Relationships: HasCategory, HasStyle, HasBrewery.
For more informations on the Graph M odel in OrientDB, please refer to the Graph M odel section.
163
Import Tutorials
ETL Process
The ETL module for OrientDB provides support for moving data to and from OrientDB databases using Extract, Transform and Load
processes.
The ETL module consists of a script,
oetl.sh
, that takes in input a single JSON configuration file.
For more information on the ETL module, please refer to the ETL section.
Import Beer Categories
The following are the first two lines of the
categories.csv
file:
"id","cat_name","last_mod"
"1","British Ale","2010-10-24 13:50:10"
In order to import this file in OrientDB, we have to create the following file as
categories.json
:
{
"source": { "file": { "path": "/temp/openbeer/openbeerdb_csv/categories.csv" } },
"extractor": { "csv": {} },
"transformers": [
{ "vertex": { "class": "Category" } }
],
"loader": {
"orientdb": {
"dbURL": "plocal:../databases/openbeerdb",
"dbType": "graph",
"classes": [
{"name": "Category", "extends": "V"}
], "indexes": [
{"class":"Category", "fields":["id:integer"], "type":"UNIQUE" }
]
}
}
}
To import it into OrientDB, please move into the "bin" directory of the OrientDB distribution:
$ cd orientdb-community-2.2.8/bin
and run OrientDB ETL:
$ ./oetl.sh /temp/openbeer/categories.json
OrientDB etl v.2.0.9 (build @BUILD@) www.orientechnologies.com
BEGIN ETL PROCESSOR
END ETL PROCESSOR
+ extracted 12 rows (0 rows/sec) - 12 rows -> loaded 11 vertices (0 vertices/sec) Total time: 77ms [0 warnings, 0 errors]
Import Beer Styles
Now let's import the Beer Styles. These are the first two lines of the
styles.csv
file:
"id","cat_id","style_name","last_mod"
"1","1","Classic English-Style Pale Ale","2010-10-24 13:53:31"
In this case we will correlate the Style with the Category created earlier.
This is the
styles.json
to use with OrientDB ETL for the next step:
164
Import Tutorials
{
"source": { "file": { "path": "/temp/openbeer/openbeerdb_csv/styles.csv" } },
"extractor": { "csv": {} },
"transformers": [
{ "vertex": { "class": "Style" } },
{ "edge": { "class": "HasCategory",
"joinFieldName": "cat_id", "lookup": "Category.id" } }
],
"loader": {
"orientdb": {
"dbURL": "plocal:../databases/openbeerdb",
"dbType": "graph",
"classes": [
{"name": "Style", "extends": "V"},
{"name": "HasCategory", "extends": "E"}
], "indexes": [
{"class":"Style", "fields":["id:integer"], "type":"UNIQUE" }
]
}
}
}
Now, to import the styles, please execute the following command:
$ ./oetl.sh /temp/openbeer/styles.json
OrientDB etl v.2.0.9 (build @BUILD@) www.orientechnologies.com
BEGIN ETL PROCESSOR
END ETL PROCESSOR
+ extracted 142 rows (0 rows/sec) - 142 rows -> loaded 141 vertices (0 vertices/sec) Total time: 498ms [0 warnings, 0 errors]
Import Breweries
Now it's time for the Breweries. These are the first two lines of the
breweries.csv
file:
"id","name","address1","address2","city","state","code","country","phone","website","filepath","descript","last_mod"
"1","(512) Brewing Company","407 Radam, F200",,"Austin","Texas","78745","United States","512.707.2337","http://512brewing.com/
",,"(512) Brewing Company is a microbrewery located in the heart of Austin that brews for the community using as many local, d
omestic and organic ingredients as possible.","2010-07-22 20:00:20"
Breweries have no outgoing relations with other entities, so this is a plain import similar to the one we did for the categories.
This is the
breweries.json
to use with OrientDB ETL for the next step:
{
"source": { "file": { "path": "/temp/openbeer/openbeerdb_csv/breweries.csv" } },
"extractor": { "csv": {} },
"transformers": [
{ "vertex": { "class": "Brewery" } }
],
"loader": {
"orientdb": {
"dbURL": "plocal:../databases/openbeerdb",
"dbType": "graph",
"classes": [
{"name": "Brewery", "extends": "V"}
], "indexes": [
{"class":"Brewery", "fields":["id:integer"], "type":"UNIQUE" }
]
}
}
}
Run the import for breweries:
165
Import Tutorials
$ ./oetl.sh /temp/openbeer/breweries.json
OrientDB etl v.2.0.9 (build @BUILD@) www.orientechnologies.com
BEGIN ETL PROCESSOR
END ETL PROCESSOR
+ extracted 1.395 rows (0 rows/sec) - 1.395 rows -> loaded 1.394 vertices (0 vertices/sec) Total time: 830ms [0 warnings, 0 er
rors]
Import Beers
Now it's time for the last and most important file: the Beers! These are the first two lines of the
beers.csv
file:
"id","brewery_id","name","cat_id","style_id","abv","ibu","srm","upc","filepath","descript","last_mod",,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,
"1","812","Hocus Pocus","11","116","4.5","0","0","0",,"Our take on a classic summer ale.
aze.
A toast to weeds, rays, and summer h
A light, crisp ale for mowing lawns, hitting lazy fly balls, and communing with nature, Hocus Pocus is offered up as a s
ummer sacrifice to clodless days.
As you can see each beer is connected to other entities through the following fields:
brewery_id
cat_id
style_id
This is the
-> Brewery
-> Category
-> S tyle
beers.json
to use with OrientDB ETL for the next step:
{
"config" : { "haltOnError": false },
"source": { "file": { "path": "/temp/openbeer/openbeerdb_csv/beers.csv" } },
"extractor": { "csv": { "columns": ["id","brewery_id","name","cat_id","style_id","abv","ibu","srm","upc","filepath","descrip
t","last_mod"],
"columnsOnFirstLine": true } },
"transformers": [
{ "vertex": { "class": "Beer" } },
{ "edge": { "class": "HasCategory",
"joinFieldName": "cat_id", "lookup": "Category.id" } },
{ "edge": { "class": "HasBrewery",
"joinFieldName": "brewery_id", "lookup": "Brewery.id" } },
{ "edge": { "class": "HasStyle",
"joinFieldName": "style_id", "lookup": "Style.id" } }
],
"loader": {
"orientdb": {
"dbURL": "plocal:../databases/openbeerdb",
"dbType": "graph",
"classes": [
{"name": "Beer", "extends": "V"},
{"name": "HasCategory", "extends": "E"},
{"name": "HasStyle", "extends": "E"},
{"name": "HasBrewery", "extends": "E"}
], "indexes": [
{"class":"Beer", "fields":["id:integer"], "type":"UNIQUE" }
]
}
}
}
Run the final import for beers:
$ ./oetl.sh /temp/openbeer/beers.json
OrientDB etl v.2.0.9 (build @BUILD@) www.orientechnologies.com
BEGIN ETL PROCESSOR
...
+ extracted 5.862 rows (1.041 rows/sec) - 5.862 rows -> loaded 4.332 vertices (929 vertices/sec) Total time: 10801ms [0 warnin
gs, 27 errors]
END ETL PROCESSOR
166
Import Tutorials
Note: the 27 errors are due to the 27 wrong content lines that have no id.
Some Queries and Visualizations
Now that the database has been imported we can execute some queries and create some visualizations.
The following are some ways we can use to access the newly imported
OpenBeer
database:
Console
Gremlin Console
Studio
APIs & Drivers
some external tools, like Gephy
some external visualization libraries for graph rendering
If we want to query all Category vertices we can execute the following query:
SELECT * FROM Category
The following is the visualization we can create using the Studio's Graph Editor:
If we want to find all nodes directly connected to a specific beer (e.g. the beer Petrus Dubbel Bruin Ale) with either an incoming or
outgoing relationship, we can use a query like the following:
SELECT EXPAND( BOTH() ) FROM Beer WHERE name = 'Petrus Dubbel Bruin Ale'
Alternatively, we can use the M ATCH syntax:
MATCH {class: Beer, where: (name = 'Petrus Dubbel Bruin Ale')}--{as: n} RETURN $pathelements
If we execute the first query in the Browse tab of Studio we get the following result, from where we can see that there are three nodes
connected to this beer, having @rid 11:4, 14:262 and 12:59:
167
Import Tutorials
We can send the result of this
SELECT
query to the Graph Editor by clicking the icon "Send to Graph", or create a new visualization
directly from the Graph Editor.
The following is the visualization of the
MATCH
query above, executed directly on the Graph Editor:
The same resultset can be visualized using an external graph library. For instance, the following graph has been obtained using the library
vis.js where the input visjs dataset has been created with a java program created using the OrientDB's Java Graph API:
168
Import Tutorials
We can also query bigger portions of the graph. For example, to query all beer Category nodes and for each of them all the connected
Style nodes, we can use a M ATCH query like the following:
MATCH
{class: Category, as: category}-HasCategory-{class: Style, as: style}
RETURN $elements
The following is the visualization of the
MATCH
query above in the Graph Editor:
while the following is a visualization created for the same recordset using the library vis.js:
169
Import Tutorials
170
Import Tutorials
Tutorial: Importing the northwind Database from Neo4j
In this tutorial we will use the Neo4j to OrientDB Importer to import the Neo4j northwind example database into OrientDB.
For general information on the possible Neo4j to OrientDB migration strategies, please refer to the Import from Neo4j section.
Neo4j and Cypher are registered trademark of Neo Technology, Inc.
Preparing for the migration
Please download and install OrientDB:
$ wget http://orientdb.com/download.php?file=orientdb-community-tp2-3.0.0RC1.tar.gz&utm_source=Labs&utm_medium=link&utm_campai
gn=300 -O orientdb-community-tp2-3.0.0RC1.tar.gz
$ tar xvf orientdb-community-tp2-3.0.0RC1.tar.gz
Download and install the Neo4j to OrientDB Importer:
$ wget http://central.maven.org/maven2/com/orientechnologies/orientdb-neo4j-importer/3.0.0RC1/orientdb-neo4j-importer-3.0.0RC1
.tar.gz
$ tar xfv orientdb-neo4j-importer-3.0.0RC1.tar.gz -C orientdb-community-3.0.0RC1 --strip-components=1
For further information on the OrientDB's installation, please refer to this section.
For further information on the Neo4j to OrientDB Importer installation, please refer to this section.
Starting the migration
Assuming that:
/home/santo/neo4j/neo4j-community-3.0.7/lib
/home/santo/data/graph.db_northwind
is the full path to the directory that includes the Neo4j's libraries
is the full path to the directory that contains the Neo4j's northwind database
/home/santo/orientdb/orientdb-community-2.2.12/databases/northwind_import
is the full path to the directory where you would
like to migrate the northwind database
that no Neo4j and OrientDB servers are running on those directories
you can import the northwind database with a command similar to the following:
./orientdb-neo4j-importer.sh \
-neo4jlibdir /home/santo/neo4j/neo4j-community-3.0.7/lib \
-neo4jdbdir /home/santo/neo4j/data/graph.db_northwind \
-odbdir /home/santo/orientdb/orientdb-community-2.2.12/databases/northwind_import
For further information on how to use the Neo4j to OrientDB Importer, please refer to this section.
Migration output
The following is the output that is written by the Neo4j to OrientDB Importer during the
northwind
database migration:
171
Import Tutorials
Neo4j to OrientDB Importer v.2.2.12-SNAPSHOT - Copyrights (c) 2016 OrientDB LTD
WARNING: 'o' option not found. Defaulting to 'false'.
Please make sure that there are no running servers on:
'/home/santo/neo4j/data/graph.db_northwind' (Neo4j)
and:
'/home/santo/orientdb/orientdb-community-2.2.12/databases/northwind_import' (OrientDB)
Initializing Neo4j...Done
Initializing OrientDB...Done
Importing Neo4j database:
'/home/santo/neo4j/data/graph.db_northwind'
into OrientDB database:
'/home/santo/orientdb/orientdb-community-2.2.12/databases/northwind_import'
Getting all Nodes from Neo4j and creating corresponding Vertices in OrientDB...
1035 OrientDB Vertices have been created (100% done)
Done
Creating internal Indices on property 'Neo4jNodeID' on all OrientDB Vertices Classes...
5 OrientDB Indices have been created (100% done)
Done
Getting all Relationships from Neo4j and creating corresponding Edges in OrientDB...
3139 OrientDB Edges have been created (100% done)
Done
Getting Constraints from Neo4j and creating corresponding ones in OrientDB...
0 OrientDB Indices have been created
Done
Getting Indices from Neo4j and creating corresponding ones in OrientDB...
5 OrientDB Indices have been created (100% done)
Done
Import completed!
Shutting down OrientDB...Done
Shutting down Neo4j...Done
===============
Import Summary:
===============
- Found Neo4j Nodes
: 1035
-- With at least one Label
:
--- With multiple Labels
:
-- Without Labels
:
- Imported OrientDB Vertices
: 1035 (100%)
- Found Neo4j Relationships
: 3139
- Imported OrientDB Edges
: 3139 (100%)
- Found Neo4j Constraints
: 0
- Imported OrientDB Constraints (Indices created)
: 0
- Found Neo4j (non-constraint) Indices
: 5
- Imported OrientDB Indices
: 5 (100%)
- Additional created Indices (on vertex properties 'Neo4jNodeID')
: 5
- Total Import time:
: 29 seconds
-- Initialization time
:
7 seconds
-- Time to Import Nodes
:
6 seconds (181.67 nodes/sec)
-- Time to Import Relationships
:
7 seconds (459.79 rels/sec)
-- Time to Import Constraints and Indices
:
4 seconds (1.21 indices/sec)
-- Time to create internal Indices (on vertex properties 'Neo4jNodeID')
:
4 seconds (1.22 indices/sec)
1035
0
0
Connecting to the newly imported Database
172
Import Tutorials
General information on how to connect to a newly imported database can be found in this section.
The following is a partial visualization of the northwind database done with the Graph Editor included in the OrientDB's Studio tool:
As you can see from the Limit field, the visualization is limited to 200 vertices.
The following, instead, is the graph returned by the following
orderID
MATCH
query (the query returns all nodes connected to the Order with
10344):
MATCH {class: Order, where: (orderID = 10344)}--{as: n} RETURN $pathelements
From Studio's Schema M anager, you can check all imported Vertex Classes (node Labels in Neo4j), Edge Classes (Relationship Types in
Neo4j), and Indexes:
173
Import Tutorials
V
and
E
are special classes: they include all Vertices and all Edges.
174
Import Tutorials
This is a legacy strategy to migrate from Neo4j. The new strategy is to migrate using the Neo4j to
OrientDB Importer.
Tutorial: Importing the movie Database from Neo4j
In this tutorial we will follow the steps described in the Import from Neo4j using GraphM L section to import the Neo4j's movie
example database into OrientDB.
We will also provide some examples of queries using the OrientDB's M ATCH syntax, making a comparison with the corresponding
Neo4j's Cypher query language.
For general information on the possible Neo4j to OrientDB migration strategies, please refer to the Import from Neo4j section.
Neo4j and Cypher are registered trademark of Neo Technology, Inc.
Exporting from Neo4j
Assuming you have already downloaded and unpacked the Neo4j Shell Tools, and restarted the Neo4j Server, as described in the Section
Exporting GraphM L, you can export the movie database using
neo4j-shell
with a command like the following one:
D:\neo4j\neo4j-community-3.0.6\bin>neo4j-shell.bat
Welcome to the Neo4j Shell! Enter 'help' for a list of commands
NOTE: Remote Neo4j graph database service 'shell' at port 1337
neo4j-sh (?)$ export-graphml -t -o d:/movie.graphml
Wrote to GraphML-file d:/movies.graphml 0. 100%: nodes = 171 rels = 253 properties = 564 time 270 ms total 270 ms
In the example above the exported movie graph is stored under
D:\movie.graphml
.
Importing into OrientDB
In this tutorial we will import in OrientDB the file
movie.graphml
using the OrientDB's Console. For other GraphM L import methods,
please refer to the section Importing GraphM L.
The OrientDB's Console output generated during the import process is similar to the following (note that first we create a movie
database using the command
CREATE DATABASE
, and then we do the actual import using the command
IMPORT DATABASE
):
D:\orientdb\orientdb-enterprise-2.2.8\bin>console.bat
OrientDB console v.2.2.8-SNAPSHOT (build 2.2.x@r39259e190e16045fe1425b1c0485f8562fca055b; 2016-08-23 14:38:49+0000) www.orient
db.com
Type 'help' to display all the supported commands.
Installing extensions for GREMLIN language v.2.6.0
orientdb> CREATE DATABASE PLOCAL:D:/orientdb/orientdb-enterprise-2.2.8/databases/movie
Creating database [PLOCAL:D:/orientdb/orientdb-enterprise-2.2.8/databases/movie] using the storage type [PLOCAL]...
Database created successfully.
Current database is: PLOCAL:D:/orientdb/orientdb-enterprise-2.2.8/databases/movie
orientdb {db=movie}> IMPORT DATABASE D:/movie.graphml
Importing GRAPHML database from D:/movie.graphml with options ()...
Done: imported 171 vertices and 253 edges
orientdb {db=movie}>
175
Import Tutorials
As you can see from the output above, as a result of the import 171 vertices and 253 edges have been created in OrientDB. This is
exactly the same number of nodes and relationships exported from Neo4j.
For more tips and tricks related to the import process, please refer to this section.
Query Comparison
Once the movie database has been imported into OrientDB, you may use several ways to access its data.
The
MATCH
syntax and the tool Studio can be used, for instance, in a similar way to the Neo4j's Cypher and Browser.
The following sections include a comparison of the Neo4j's Cypher and OrientDB's
MATCH
syntax for some queries that you can
execute against the movie database.
Find the actor named "Tom Hanks"
Neo4j's Cypher:
MATCH (tom:Person {name: "Tom Hanks"})
RETURN tom
OrientDB's M ATCH:
MATCH {class: Person, as: tom, where: (name = 'Tom Hanks')}
RETURN $pathElements
Find the movie with title "Cloud Atlas"
Neo4j's Cypher:
MATCH (cloudAtlas:Movie {title: "Cloud Atlas"})
RETURN cloudAtlas
OrientDB's M ATCH:
MATCH {class: Movie, as: cloudAtlas, where: (title = 'Cloud Atlas')}
RETURN $pathElements
Find 10 people
Neo4j's Cypher:
MATCH (people:Person)
RETURN people.name
LIMIT 10
OrientDB's M ATCH:
MATCH {class: Person, as: people}
RETURN people.name
LIMIT 10
Find the movies released in the 1990s
Neo4j's Cypher:
176
Import Tutorials
MATCH (nineties:Movie)
WHERE nineties.released > 1990 AND nineties.released < 2000
RETURN nineties.title
OrientDB's M ATCH:
MATCH {class: Movie, as: nineties, WHERE: (released > 1990 AND released < 2000 )}
RETURN nineties.title
List all Tom Hanks movies
Neo4j's Cypher:
MATCH (tom:Person {name: "Tom Hanks"})-[:ACTED_IN]->(tomHanksMovies)
RETURN tom, tomHanksMovies
OrientDB's M ATCH:
MATCH {class: Person, as: tom, where: (name = 'Tom Hanks')}-ACTED_IN->{as: tomHanksMovies}
RETURN $pathElements
Find out who directed "Cloud Atlas"
Neo4j's Cypher:
MATCH (cloudAtlas {title: "Cloud Atlas"})<-[:DIRECTED]-(directors)
RETURN directors.name
OrientDB's M ATCH:
MATCH {class: Movie, as: cloudAtlas, where: (title = 'Cloud Atlas')}<-DIRECTED-{as: directors}
RETURN directors.name
Find Tom Hanks' co-actors
Neo4j's Cypher:
MATCH (tom:Person {name:"Tom Hanks"})-[:ACTED_IN]->(m)<-[:ACTED_IN]-(coActors)
RETURN DISTINCT coActors.name
OrientDB's M ATCH:
MATCH {class: Person, as: tom, where: (name = 'Tom Hanks')}-ACTED_IN->{as: m}<-ACTED_IN-{class: Person,as: coActors}
RETURN coActors.name
Find how people are related to "Cloud Atlas"
Neo4j's Cypher:
MATCH (people:Person)-[relatedTo]-(:Movie {title: "Cloud Atlas"})
RETURN people.name, Type(relatedTo), relatedTo
OrientDB's M ATCH:
MATCH {class: Person, as: people}--{as: m, where: (title = 'Cloud Atlas')}
RETURN $pathElements
177
General Information
General Information
This Chapter includes some General Information on OrientDB.
178
Supported Types
Supported Data Types
OrientDB supports several data types natively. Below is the complete table.
#id
Type
S QL type
Description
Autoconversion
from/to
Minimum
Maximum
Java type
0
Boolean
BOOLEAN
Handles only
the values
True or False
java.lang.Boolean
boolean
or
0
1
String
1
Integer
INTEGER
32-bit signed
Integers
java.lang.Integer
int
or
-2,147,483,648
+2,147,483,647
Any
Number,
String
2
Short
SHORT
Small 16-bit
signed
integers
java.lang.Short
short
-32,768
32,767
Any
Number,
String
3
Long
LONG
Big 64-bit
signed
integers
java.lang.Long
long
-263
+263-1
Any
Number,
String
4
Float
FLOAT
Decimal
numbers
java.lang.Float
float
2-149
(2-2-23)*2127
Any
Number,
String
DOUBLE
Decimal
numbers
with high
precision
java.lang.Double
double
2-1074
(2-2-52)*21023
Any
Number,
String
DATETIM E
Any date
with the
precision up
to
milliseconds.
To know
more about
it, look at
M anaging
Dates
java.util.Date
1002020303
Date, Long,
String
java.lang.String
-
-
5
6
Double
Datetime
or
or
or
or
7
String
STRING
Any string
as
alphanumeric
sequence of
chars
8
Binary
BINARY
Can contain
any value as
byte array
byte[]
0
2,147,483,647
String
EM BEDDED
The Record
is contained
inside the
owner. The
contained
Record has
no Record
ID
ORecord
-
ORecord
List