TableofContents
Introduction
1.1
GettingStarted
1.2
Installation
1.2.1
InstallasServiceonUnix
1.2.1.1
InstallasServiceonWindows
1.2.1.2
InstallwithDocker
1.2.1.3
Runtheserver
1.2.2
Runtheconsole
1.2.3
RuntheStudio
1.2.4
DataM odeling
1.3
GraphorDocumentAPI?
1.3.1
BasicConcepts
1.3.2
SupportedTypes
1.3.2.1
Inheritance
1.3.2.2
Concurrency
1.3.2.3
Schema
1.3.2.4
ClusterSelection
1.3.2.5
M anagingDates
1.3.2.6
Classes
1.3.3
Clusters
1.3.4
RecordID
1.3.5
Relationships
1.3.6
WorkingwithGraphs
1.3.7
UsingSchemawithGraphs
1.3.8
GraphConsistency
1.3.9
FetchingStrategies
1.3.10
UseCases
1.3.11
TimeSeries
1.3.11.1
Chat
1.3.11.2
KeyValue
1.3.11.3
Queuesystem
1.3.11.4
Administration
ConsoleCommandReference
1.4
1.4.1
Backup
1.4.1.1
Begin
1.4.1.2
BrowseClass
1.4.1.3
BrowseCluster
1.4.1.4
ListClasses
1.4.1.5
ClusterStatus
1.4.1.6
ListClusters
1.4.1.7
ListServers
1.4.1.8
1
ListServerUsers
1.4.1.9
Commit
1.4.1.10
Config
1.4.1.11
ConfigGet
1.4.1.12
ConfigSet
1.4.1.13
Connect
1.4.1.14
CreateCluster
1.4.1.15
CreateDatabase
1.4.1.16
CreateIndex
1.4.1.17
CreateLink
1.4.1.18
CreateProperty
1.4.1.19
DeclareIntent
1.4.1.20
Delete
1.4.1.21
DictionaryGet
1.4.1.22
DictionaryKeys
1.4.1.23
DictionaryPut
1.4.1.24
DictionaryRemove
1.4.1.25
Disconnect
1.4.1.26
DisplayRecord
1.4.1.27
DisplayRawRecord
1.4.1.28
DropCluster
1.4.1.29
DropDatabase
1.4.1.30
DropServerUser
1.4.1.31
ExportDatabase
1.4.1.32
ExportRecord
1.4.1.33
FreezeDB
1.4.1.34
Get
1.4.1.35
GREM LIN
1.4.1.36
ImportDatabase
1.4.1.37
Indexes
1.4.1.38
Info
1.4.1.39
InfoClass
1.4.1.40
InfoProperty
1.4.1.41
Insert
1.4.1.42
ListDatabases
1.4.1.43
ListConnections
1.4.1.44
LoadRecord
1.4.1.45
Profiler
1.4.1.46
Properties
1.4.1.47
ReleaseDB
1.4.1.48
ReloadRecord
1.4.1.49
Restore
1.4.1.50
Rollback
1.4.1.51
Set
1.4.1.52
2
SetServerUser
1.4.1.53
Sleep
1.4.1.54
Upgrading
1.4.2
Backwardcompatibility
1.4.2.1
From2.1.xto2.2.x
1.4.2.2
From2.0.xto2.1.x
1.4.2.3
From1.7.xto2.0.x
1.4.2.4
From1.6.xto1.7.x
1.4.2.5
From1.5.xto1.6.x
1.4.2.6
From1.4.xto1.5.x
1.4.2.7
From1.3.xto1.4.x
1.4.2.8
BackupandRestore
1.4.3
ExportandImport
1.4.4
Exportformat
1.4.4.1
ImportFromRDBM S
1.4.4.2
ToDocumentM odel
1.4.4.2.1
ToGraphM odel
1.4.4.2.2
ImportFromNeo4j
ETL
1.4.4.3
1.4.5
Configuration
1.4.5.1
Blocks
1.4.5.2
Sources
1.4.5.3
Extractors
1.4.5.4
Transformers
1.4.5.5
Loaders
1.4.5.6
ImportthedatabaseofBeers
1.4.5.7
ImportfromCSVtoaGraph
1.4.5.8
Importatreestructure
1.4.5.9
ImportfromJSON
1.4.5.10
ImportfromRDBM S
1.4.5.11
ImportfromDB-Pedia
1.4.5.12
ImportfromParse(Facebook)
1.4.5.13
Logging
1.4.6
Studio
1.4.7
Query
1.4.7.1
EditDocument
1.4.7.2
EditVertex
1.4.7.3
Schema
1.4.7.4
Class
1.4.7.5
GraphEditor
1.4.7.6
Functions
1.4.7.7
Security
1.4.7.8
DatabaseM anagement
1.4.7.9
ServerM anagement
1.4.7.10
3
Auditing
Troubleshooting
1.4.7.11
1.4.8
Java
1.4.8.1
QueryExamples
1.4.8.2
PerformanceTuning
1.4.9
SettingConfiguration
1.4.9.1
GraphAPI
1.4.9.2
DocumentAPI
1.4.9.3
ObjectAPI
1.4.9.4
Profiler
1.4.9.5
Distributedtuning
1.4.9.6
Security
1.4.10
Databasesecurity
1.4.10.1
Serversecurity
1.4.10.2
Databaseencryption
1.4.10.3
SecureSSLconnections
1.4.10.4
ServerM anagement
APIsandDrivers
1.4.11
1.5
Functions
1.5.1
AvailablePluginsandTools
1.5.2
JavaAPI
1.5.3
JavaAPIIntroduction
1.5.3.1
GraphAPI
1.5.3.2
Factory
1.5.3.2.1
Schema
1.5.3.2.2
Partitioned
1.5.3.2.3
Comparison
1.5.3.2.4
LightweightEdges
1.5.3.2.5
DocumentAPI
1.5.3.3
Schema
1.5.3.3.1
FieldPart
1.5.3.3.2
Comparison
1.5.3.3.3
ObjectAPI
Binding
1.5.3.4
1.5.3.4.1
Traverse
1.5.3.5
LiveQuery
1.5.3.6
M ulti-Threading
1.5.3.7
Transactions
1.5.3.8
BinaryData
1.5.3.9
WebApps
1.5.3.10
JDBCDriver
1.5.3.11
JPA
1.5.3.12
JM X
1.5.4
GremlinAPI
1.5.5
4
Javascript
JavascriptAPI
1.5.6
1.5.6.1
ScalaAPI
1.5.7
HTTPAPI
1.5.8
BinaryProtocol
1.5.9
CSVSerialization
1.5.9.1
SchemalessSerialization
1.5.9.2
Commands
1.5.9.3
SQLReference
CRUDOperations
1.6
1.6.1
Select
1.6.1.1
Insert
1.6.1.2
Update
1.6.1.3
Delete
1.6.1.4
M atch
1.6.1.5
Commands
1.6.2
AlterClass
1.6.2.1
AlterCluster
1.6.2.2
AlterDatabase
1.6.2.3
AlterProperty
1.6.2.4
AlterSequence
1.6.2.5
CreateClass
1.6.2.6
CreateCluster
1.6.2.7
CreateEdge
1.6.2.8
CreateFunction
1.6.2.9
CreateIndex
1.6.2.10
CreateLink
1.6.2.11
CreateProperty
1.6.2.12
CreateSequence
1.6.2.13
CreateUser
1.6.2.14
CreateVertex
1.6.2.15
M oveVertex
1.6.2.16
Updateedge
1.6.2.17
DeleteEdge
1.6.2.18
DeleteVertex
1.6.2.19
DropClass
1.6.2.20
DropCluster
1.6.2.21
DropIndex
1.6.2.22
DropProperty
1.6.2.23
DropSequence
1.6.2.24
DropUser
1.6.2.25
Explain
1.6.2.26
FindReferences
1.6.2.27
Grant
1.6.2.28
5
OptimizeDatabase
1.6.2.29
RebuildIndex
1.6.2.30
Revoke
1.6.2.31
Traverse
1.6.2.32
TruncateClass
1.6.2.33
TruncateCluster
1.6.2.34
TruncateRecord
1.6.2.35
Filtering
1.6.3
Functions
1.6.4
M ethods
1.6.5
Batch
1.6.6
Pagination
1.6.7
Sequencesandautoincrement
1.6.8
PivotingwithQuery
1.6.9
CommandCache
Indexing
1.6.10
1.7
SB-Tree
1.7.1
Hash
1.7.2
FullText
1.7.3
LuceneFullText
1.7.4
LuceneSpatialIndex
1.7.5
LuceneSpatialM odule
Scaling
1.7.5.1
1.8
WorkingwithDistributedGraphs
1.8.1
Lifecycle
1.8.2
Configuration
1.8.3
RuntimeConfiguration
1.8.3.1
ServerM anager
1.8.4
Replication
1.8.5
Sharding
1.8.6
Cache
1.8.7
SetupaDistributedDatabase
1.8.8
Internals
1.9
Storages
1.9.1
M emorystorage
1.9.1.1
PLocalstorage
1.9.1.2
Engine
1.9.1.2.1
Disk-Cache
1.9.1.2.2
WAL(Journal)
1.9.1.2.3
Localstorage(deprecated)
1.9.1.3
Clusters
1.9.2
Limits
1.9.3
RidBag
1.9.4
SQLSyntax
1.9.5
6
CustomIndexEngine
1.9.6
Caching
1.9.7
Transaction
1.9.8
Hooks-Triggers
1.9.9
DynamicHooks
1.9.10
Java(Native)Hooks
1.9.10.1
JavaHookTutorial
1.9.10.2
Server
1.9.11
EmbedtheServer
1.9.11.1
WebServer
1.9.11.2
Plugins
1.9.12
AutomaticBackup
1.9.12.1
M ail
1.9.12.2
JM X
1.9.12.3
Rexster
1.9.12.4
GephiGraphRender
1.9.12.5
spider-box
1.9.12.6
ContributetoOrientDB
TheTeam
1.10
1.10.1
Hackaton
1.10.1.1
Reportanissue
1.10.1.2
Getintouch
1.10.2
M oreTutorials
1.10.3
Presentations
Roadmap
EnterpriseEdition
Auditing
1.10.3.1
1.10.4
1.11
1.11.1
7
Introduction
OrientDBManual-version2.1.x
QuickNavigation
GettingS tarted
MainTopics
Developers
IntroductiontoOrientDB
BasicConcepts
SQL
Installation
SupportedDataTypes
Gremlin
FirstSteps
Inheritance
HTTPAPI
Troubleshooting
Security
JavaAPI
EnterpriseEdition
Indexes
NodeJS
ACIDTransactions
PHP
Functions
Python
CachingLevels
.NET
CommonUseCases
OtherDrivers
NetworkBinaryProtocol
Javadocs
Operations
Installation
3rdpartyPlugins
Upgrade
Configuration
DistributedArchitecture(replication,shardingandhigh-availability)
PerformanceTuning
ETLtoImportanykindofdataintoOrientDB
ImportfromRelationalDB
BackupandRestore
ExportandImport
QuickReferences
8
Introduction
Console
Studiowebtool
Workbench(EnterpriseEdition)
OrientDBServer
Network-Binary-Protocol
GephiGraphAnalysisVisualtool
RexsterSupportandconfiguration
Continuousintegration
Resources
UserGroup-Havequestion,troubles,problems?
#orientdbIRCchannelonfreenode
ProfessionalSupport
Training-Trainingandclasses.
Events-FollowOrientDBatthenextevent!
Team-M eettheteambehindOrientDB
Contribute-Contributetotheproject.
WhoisusingOrientDB?-ClientsusingOrientDBinproduction.
QuestionsorNeedHelp?
CheckoutourGetinTouchpagefordifferentwaysofgettingintouchwithus.
PDF
ThisdocumentationisalsoavailableinPDFformat.
Pastreleases
v1.7.8
v2.0.x
WelcometoOrientDB-thefirstM ulti-M odelOpenSourceNoSQLDBM Sthatbringstogetherthepowerofgraphsandtheflexibility
ofdocumentsintoonescalablehigh-performanceoperationaldatabase.
Everyefforthasbeenmadetoensuretheaccuracyofthismanual.However,OrientTechnologies,LTD.makesnowarranties
withrespecttothisdocumentationanddisclaimsanyimpliedwarrantiesofmerchantabilityandfitnessforaparticularpurpose.
Theinformationinthisdocumentissubjecttochangewithoutnotice.
9
GettingStarted
GettingStarted
Overthepastfewyears,therehasbeenanexplosionofmanyNoSQLdatabasesolutionsandproducts.Themeaningoftheword
"NoSQL"isnotacampaignagainsttheSQLlanguage.Infact,OrientDBallowsforSQLsyntax!NoSQLisprobablybestdescribedby
thefollowing:
NoSQL,meaning"notonlySQL",isamovementencouragingdevelopersandbusinesspeopletoopentheirmindsandconsider
newpossibilitiesbeyondtheclassicrelationalapproachtodatapersistence.
Alternativestorelationaldatabasemanagementsystemshaveexistedformanyyears,buttheyhavebeenrelegatedprimarilytonicheuse
casessuchastelecommunications,medicine,CADandothers.InterestinNoSQLalternativeslikeOrientDBisincreasingdramatically.
Notsurprisingly,manyofthelargestwebcompanieslikeGoogle,Amazon,Facebook,FoursquareandTwitterareusingNoSQLbased
solutionsintheirproductionenvironments.
Whatmotivatescompaniestoleavethecomfortofawellestablishedrelationaldatabaseworld?Itisbasicallythegreatneedtobetter
solvetoday'sdataproblems.Specifically,thereareafewkeyareas:
Performance
Scalability(oftenhuge)
Smallerfootprint
Developerproductivityandfriendliness
Schemaflexibility
M ostoftheseareasalsohappentobetherequirementsofmodernwebapplications.Afewyearsago,developersdesignedsystemsthat
couldhandlehundredsofconcurrentusers.Todayitisnotuncommontohaveapotentialtargetofthousandsormillionsofusers
connectedandservedatthesametime.
Changingtechnologyrequirementshavebeentakenintoaccountontheapplicationfrontbycreatingframeworks,introducingstandards
andleveragingbestpractices.However,inthedatabaseworld,thesituationhasremainedmoreorlessthesameforover30years.From
the1970suntilrecently,relationalDBM Sshaveplayedthedominantrole.Programminglanguagesandmethodologieshaveevolved,but
theconceptofdatapersistenceandtheDBM Shaveremainedunchangedforthemostpart:itisallstilltables,recordsandjoins.
NoSQLModels
NoSQL-basedsolutionsingeneralprovideapowerful,scalable,andflexiblewaytosolvedataneedsandusecases,whichhave
previouslybeenmanagedbyrelationaldatabases.TosummarizetheNoSQLoptions,we'llexaminethemostcommonmodelsor
categories:
Key/Valuedatabases:wherethedatamodelisreducedtoasimplehashtable,whichconsistsofkey/valuepairs.Itisoften
easilydistributedacrossmultipleservers.ThemostrecognizedproductsofthisgroupincludeRedis,Dynamo,andRiak.
Column-orienteddatabases:wherethedataisstoredinsectionsofcolumnsofferingmoreflexibilityandeasyaggregation.
Facebook'sCassandra,Google'sBigTable,andAmazon'sSimpleDBaresomeexamplesofcolumn-orienteddatabases.
Documentdatabases:wherethedatamodelconsistsofdocumentcollections,inwhicheachindividualdocumentcanhave
multiplefieldswithoutnecessarilyhavingadefinedschema.ThebestknownproductsofthisgroupareM ongoDBandCouchDB.
Graphdatabases:wherethedomainmodelconsistsofverticesinterconnectedbyedgescreatingrichgraphstructures.Thebest
knownproductsofthisgroupareOrientDB,Neo4jandTitan.
OrientDBisadocument-graphdatabase,meaningithasfullnativegraphcapabilitiescoupledwithfeaturesnormallyonlyfound
indocumentdatabases.
Eachofthesecategoriesormodelshasitsownpeculiarities,strengthsandlimitations.Thereisnosinglecategoryormodel,whichis
betterthantheothers.However,certaintypesofdatabasesarebetteratsolvingspecificproblems.ThisleadstothemottoofNoSQL:
choosethebesttoolforyourspecificusecase.
ThegoalofOrientTechnologiesinbuildingOrientDBwastocreatearobust,highlyscalabledatabasethatcanperformoptimallyinthe
widestpossiblesetofusecases.Ourproductisdesignedtobeafantastic"goto"solutionforpracticallyallofyourdatapersistence
needs.Inthefollowingpartsofthistutorial,wewilllookcloselyatOrientDB,oneofthebestopen-source,multi-model,next
10
GettingStarted
generationNoSQLproductsonthemarkettoday.
11
Installation
Installation
OrientDBisavailableintwoeditions:
CommunityEditionThiseditionisreleasedasanopensourceprojectundertheApache2license.Thislicenseallowsunrestricted
freeusageforbothopensourceandcommercialprojects.
EnterpriseEditionOrientDBEnterpriseEditioniscommercialsoftwarebuiltontopoftheCommunityEdition.Enterpriseis
developedbythesameteamthatdevelopedtheOrientDBengine.ItservesasanextensionoftheCommunityEdition,providing
Enterprisefeatures,suchas:
QueryProfiler
DistributedClusteringconfiguration
M etricsRecording
LiveM onitoringwithconfigurableAlerts
TheCommunityEditionisavailableasabinarypackagefordownloadorassourcecodeonGitHub.TheEnterpriseEditionlicenseis
includedwithSupportpurchases.
Prerequisites
BotheditionsofOrientDBrunonanyoperatingsystemthatimplementstheJavaVirtualmachine(JVM ).Examplesoftheseinclude:
Linux,alldistributions,includingARM (RaspberryPi,etc.)
M acOSX
M icrosoftWindows,from95/NTandlater
Solaris
HP-UX
IBM AIX
OrientDBrequiresJava,version1.7orhigher.
Note:InOSGicontainers,OrientDBusesa ConcurrentLinkedHashMapimplementationprovidedbyconcurrentlinkedhashmapto
createtheLRUbasedcache.Thislibraryactivelyusesthesun.miscpackagewhichisusuallynotexposedasasystempackage.
Toovercomethislimitationyoushouldaddproperty org.osgi.framework.system.packages.extrawithvalue sun.misctoyour
listofframeworkproperties.
ItmaybeassimpleaspassinganargumenttotheVM startingtheplatform:
$java-Dorg.osgi.framework.system.packages.extra=sun.misc
InstallingOrientDB
TherearetwomethodsavailabletoinstallOrientDB,withsomevariationsoneachdependingonyouroperatingsystem.Thefirst
methodistodownloadabinarypackagefromOrientDB.Theothermethodistocompilethepackagefromthesourcecode.
BinaryInstallation
OrientDBprovidesapre-compiledbinarypackagetoinstallthedatabaseonyoursystem.Dependingonyouroperatingsystem,thisis
atarredorzippedpackagethatcontainsalltherelevantfilesyouneedtorunOrientDB.Fordesktopinstallations,gotoOrientDB
Downloadsandselectthepackagethatbestsuitsyoursystem.
Onserverinstallations,youcanusethe wgetutility:
$wgethttps://orientdb.com/download.php?file=orientdb-community-2.1.2.tar.gz
12
Installation
Whetheryouuseyourwebbrowseror wget,unziporextractthedownloadedfileintoadirectoryconvenientforyouruse,(for
example, /opt/orientdb/onLinux).Thiscreatesadirectorycalled orientdb-community-2.1.2withrelevantfilesandscripts,which
youwillneedtorunOrientDBonyoursystem.
SourceCodeInstallation
Inadditiontodownloadingthebinarypackages,youalsohavetheoptionofcompilingOrientDBfromtheCommunityEditionsource
code,availableonGitHub.ThisprocessrequiresthatyouinstallGitandApacheM avenonyoursystem.
TocompileOrientDBfromsourcecode,clonetheCommunityEditionrepository,thenrunM aven( mvn)inthenewlycreated
directory:
$gitclonehttps://github.com/orientechnologies/orientdb
$gitcheckoutdevelop
$cdorientdb
$mvncleaninstall
Itispossibletoskiptests:
$mvncleaninstall-DskipTests
ThedevelopbranchcontainscodeforthenextversionofOrientDB.Stableversionsaretaggedonmasterbranch.Foreachmaintained
versionOrientDBhasitsown hotfixbranch.Asthetimeofwritingthisnotes,thestateofbranchesis:
develop:workinprogressfornext2.2.xrelease(2.2.0-SNAPSHOT)
2.1.x:hotfixfornext2.1.xstablerelease(2.1.10-SNAPSHOT)
2.0.x:hotfixfornext2.0.xstablerelease(2.0.17-SNAPSHOT)
lasttagonmasteris2.1.9
Thebuildprocessinstallsalljarsinthelocalmavenrepositoryandcreatesarchivesunderthe distributionmoduleinsidethe target
directory.Atthetimeofwriting,buildingfrombranch2.1.xgave:
$ls-ldistribution/target/
total199920
108826Jan09:57archive-tmp
10226Jan09:57databases
10226Jan09:57orientdb-community-2.1.10-SNAPSHOT.dir
4881438626Jan09:57orientdb-community-2.1.10-SNAPSHOT.tar.gz
5354223126Jan09:58orientdb-community-2.1.10-SNAPSHOT.zip
$
Thedirectory orientdb-community-2.1.10-SNAPSHOT.dircontainstheOrientDBdistributionuncompressed.TakealooktoContribute
toOrientDBifyouwanttobeinvolved.
UpdatePermissions
ForLinux,M acOSXandUNIX-basedoperatingsystem,youneedtochangethepermissionsonsomeofthefilesaftercompilingfrom
source.
$chmod755bin/*.sh
$chmod-R777config
Thesecommandsupdatetheexecutepermissionsonfilesinthe config/directoryandshellscriptsin bin/,ensuringthatyoucan
runthescriptsorprogramsthatyou'vecompiled.
Post-installationTasks
Fordesktopusersinstallingthebinary,OrientDBisnowinstalledandcanberunthroughshellscriptsfoundinthepackage bin
directoryoftheinstallation.Forservers,therearesomeadditionalstepsthatyouneedtotakeinordertomanagethedatabaseserverfor
OrientDBasaservice.Theprocedureforthisvaries,dependingonyouroperatingsystem.
13
Installation
InstallasServiceonUnix,LinuxandM acOSX
InstallasServiceonM icrosoftWindows
Upgrading
WhenthetimecomestoupgradetoanewerversionofOrientDB,themethodsvarydependingonhowyouchosetoinstallitinthefirst
place.Ifyouinstalledfrombinarydownloads,repeatthedownloadprocessaboveandupdateanysymboliclinksorshortcutstopoint
tothenewdirectory.
ForsystemswhereOrientDBwasbuiltfromsource,pulldownthelatestsourcecodeandcompilefromsource.
$gitpulloriginmaster
$mvncleaninstall
Bearinmindthatwhenyoubuildfromsource,youcanswitchbranchestobuilddifferentversionsofOrientDBusingGit.Forexample,
$gitcheckout2.1.x
$mvncleaninstall
buildsthe 2.1.xbranch,insteadof master.
OtherResources
TolearnmoreabouthowtoinstallOrientDBonspecificenvironments,pleaserefertotheguidesbelow:
InstallwithDocker
InstallonLinuxUbuntu
InstallonJBossAS
InstallonGlassFish
InstallonUbuntu12.04VPS(DigitalOcean)
InstallonVagrant
14
InstallasServiceonUnix
InstallasServiceonUnix/Linux
Followingtheinstallationguideabove,whetheryouchosetodownloadbinariesorbuildfromsource,doesnotinstallOrientDBata
system-level.Thereareafewadditionalstepsyouneedtotakeinordertomanagethedatabasesystemasaservice.
OrientDBshipswithascript,whichallowsyoutomanagethedatabaseserverasasystem-leveldaemon.Youcanfinditinthe bin/
pathofyourinstallationdirectory,(thatis,at $ORIENTDB_HOME/bin/orientdb.sh.
Thescriptsupportsthreeparameters:
start
stop
status
ConfiguringtheScript
Inordertousethescriptonyoursystem,youneedtoeditthefiletodefinetwovariables:thepathtotheinstallationdirectoryandthe
useryouwanttorunthedatabaseserver.
$vi$ORIENTDB_HOME/bin/orientdb.sh
#!/bin/sh
#OrientDBservicescript
#
#Copyright(c)OrientTechnologiesLTD(http://www.orientechnologies.com)
#chkconfig:23452080
#description:OrientDbinitscript
#processname:orientdb.sh
#YouhavetoSETtheOrientDBinstallationdirectoryhere
ORIENTDB_DIR="YOUR_ORIENTDB_INSTALLATION_PATH"
ORIENTDB_USER="USER_YOU_WANT_ORIENTDB_RUN_WITH"
Editthe ORIENTDB_DIRvariabletoindicatetheinstallationdirectory.Editthe ORIENTDB_USERvariabletoindicatetheuseryouwantto
runthedatabaseserver,(forinstance, orientdb).
InstallingtheScript
DifferentoperatingsystemsandLinuxdistributionshavedifferentprocedureswhenitcomestomanagingsystemdaemons,aswellas
theprocedureforstartingandstoppingthemduringbootupandshutdown.Belowaregenericguidesforinitandsystemdbasedunix
systemsaswellM acOSX.Formoreinformation,checkthedocumentationforyourparticularsystem.
Installingforinit
M anyUnix-likeoperatingsystemssuchasFreeBSD,mostolderdistributionsofLinuxaswellascurrentreleasesofDebian,Ubuntu
andtheirderivativesusevariationsonSysV-styleinitfortheseprocesses.Thesearetypicallythesystemsthatmanagesuchprocesses
usingthe servicecommand.
ToinstallOrientDBasaserviceonaninit-basedunixorLinuxsystem,copythemodified orientdb.shfilefrom $ORIENTDB_HOME/bin
into /etc/init.d/:
#cp$ORIENTDB_HOME/bin/orientdb.sh/etc/init.d/orientdb
15
InstallasServiceonUnix
Oncethisisdone,youcanstartandstopOrientDBusingthe servicecommand:
#serviceorientdbstart
StartingOrientDBserverdaemon...
Installingforsystemd
M ostnewerreleasesofLinux,especiallyamongtheRPM -baseddistributionslikeRedHat,FedoraandCentOS,aswellasfuture
releasesofDebianandUbuntuusesystemdfortheseprocesses.Thesearethesystemsthatmanagesuchprocessesusingthe
systemctlcommand.
InstallingOrientDBonasystemd-basedLinuxdistributionrequiresthatyouwriteaservicefilesettousethe orientdb.shscriptin
launchingthedatabaseserver.Placethisfileinthesystemdconfigurationdirectory,(forinstance, /etc/systemd/:
#vi/etc/systemd/system/orientdb.service
[Unit]
Description=OrientDBServer
After=network.target
After=syslog.target
[Install]
WantedBy=multi-user.target
[Service]
Type=forking
ExecStart=$ORIENTDB_HOME/bin/orientdb.shstart
ExecStop=$ORIENTDB_HOME/bin/orientdb.shstop
ExecStatus=$ORIENTDB_HOME/bin/orientdb.shstatus
Youmaywanttousetheabsolutepathinsteadoftheenvironmentalvariable $ORIENTDB_HOME.Oncethisfileissaved,youcanstartand
stoptheOrientDBserverusingthe systemctlcommand:
#systemctlstartorientdb.service
Additionally,withthe orientdb.servicefilesaved,youcansetsystemdtostartthedatabaseserverautomaticallyduringbootby
issuingthe enablecommand:
#systemctlenableorientdb.service
Synchronizingstateoforientdb.servicewithSysVinitwith/usr/lib/systemd/systemd-sysvinstall...
Executing/usr/lib/systemd/systemd-sysv-installenableorientdb
Createdsymlinkfrom/etc/systemd/system/multi-user.target.wants/orientdb.serviceto
/etc/systemd/system/orientdb.service.
InstallingforMacOSX
ForM acOSX,createanaliastoOrientDBsystemdaemonscriptandtheconsole.
$aliasorientdb-server=/path/to/$ORIENTDB_HOME/bin/orientdb.sh
$aliasorientdb-console=/path/to/$ORIENTDB_HOME/bin/console.sh
YoucannowstarttheOrientDBdatabaseserverusingthefollowingcommand:
$orientdb-serverstart
16
InstallasServiceonUnix
Oncethedatabasestarts,itisaccessiblethroughtheconsolescript.
$orientdb-console
OrientDBconsolev.1.6www.orientechnologies.com
Type'HELP'todisplayallthecommandssupported.
orientdb>
Otherresources
TolearnmoreabouthowtoinstallOrientDBonspecificenvironmentpleasefollowtheguidebelow:
InstallonLinuxUbuntu
InstallonJBossAS
InstallonGlassFish
InstallonUbuntu12.04VPS(DigitalOcean)
InstallasserviceonUnix,LinuxandM acOSX
InstallasserviceonWindows
17
InstallasServiceonWindows
InstallasaServiceonWindows
OrientDBisaJavaserverapplication.Asmostserverapplications,theyhavetoperformseveraltasks,beforebeingabletoshutdown
theVirtualM achineprocess,hencetheyneedaportablewaytobenotifiedoftheimminentVirtualM achineshutdown.Atthemoment,
theonlywaytoproperlyshutdownanOrientDBserverinstance(notembedded)istoexecutetheshutdown.bat(orshutdown.sh)
scriptshippedwiththeOrientDBdistribution,butit'suptotheusertotakecareofthis.Thisimpliesthattheserverinstanceisn't
stoppedcorrectly,whenthecomputeronwhichitisdeployed,isshutdownwithoutexecutingtheabovescript.
ApacheCommonsDaemon
ApacheCommonsDaemonisasetofapplicationsandAPIenablingJavaserverapplicationtorunasnativenoninteractiveserver
applicationsunderUnixandWindows.InUnix,serverapplicationsrunninginthebackgroundarecalleddaemonsandarecontrolledby
theoperatingsystemwithasetofspecifiedsignals.UnderWindows,suchprogramsarecalledservicesandarecontrolledby
appropriatecallstospecificfunctionsdefinedintheapplicationbinary.Althoughthewaysofdealingwithrunningdaemonsorservices
aredifferent,inbothcasestheoperatingsystemcannotifyaserverapplicationofitsimminentshutdown,andtheunderlying
applicationhastheabilitytoperformcertaintasks,beforeitsprocessofexecutionisdestroyed.WrappingOrientDBasaUnixdaemon
orasaWindowsserviceenablesthemanagementofthisserverapplicationlifecyclethroughthemechanismsprovidednativelybyboth
UnixandWindowsoperatingsystems.
Installation
ThistutorialisfocusedonWindows,soyouhavetodownloadprocrun.Procrunisasetofapplications,whichallowWindowsusersto
wrap(mostly)Javaapplications(e.g.Tomcat)asaWindowsservice.Theservicecanbesettoautomaticallystart,whenthemachine
bootsandwillcontinuetorunwithnouserloggedontothemachine.
1. PointyoubrowsertotheApacheCommonsDaemondownloadpage.
2. ClickonBrowsenativebinariesdownloadarea...:youwillseetheindexcommons/daemon/binaries/(evenifthetitleinthe
pagereportsIndexofdist/commons).
3. Clickonwindows.Nowyoucanseetheindexofcommons/daemon/binaries/windows.
4. Clickoncommons-daemon-1.0.7-bin-windows.zip.Thedownloadstarts.
5. Unzipthefileinadirectoryofyourchoice.Thecontentofthearchiveisdepictedbelow:
commons-daemon-1.0.7-bin-windows
|
\---amd64
|
\---prunsrv.exe
|
\---ia64
|
\---prunsrv.exe
|
\---LICENCE.txt
|
\---NOTICE.txt
|
\---prunmgr.exe
|
\---prunsrv.exe
|
\---RELEASE-NOTES.txt
prunmgrisaGUIapplicationformonitoringandconfiguringWindowsserviceswrappedwithprocrun.prunsrvisaserviceapplication
forrunningapplicationsasservices.Itcanconvertanyapplication(notjustJavaapplications)torunasaservice.Thedirectoryamd64
containsaversionofprunsrvforx86-64machineswhilethedirectoryia64containsaversionofprunsrvforItanium64machines.
Onceyoudownloadedtheapplications,youhavetoputtheminafolderundertheOrientDBinstallationfolder.
1. GototheOrientDBfolder,inthefollowingreferredas%ORIENTDB_HOME%
18
InstallasServiceonWindows
2. Createanewdirectoryandnameitservice
3. Copytheretheappropriateversionsofprunsrvandprunmgraccordingtothearchitectureofyourmachine.
Configuration
Inthissection,wewillshowhowtowrapOrientDBasaWindowsService.InordertowrapOrientDBasaservice,youhavetoexecute
ashortscriptthatusestheprunsrvapplicationtoconfigureaWindowsService.
BeforedefiningtheWindowsService,youhavetorenameprunsrvandprunmgraccordingtothenameoftheservice.Bothapplications
requirethenameoftheservicetomanageandmonitorasparameterbutyoucanavoiditbynamingthemwiththenameoftheservice.In
thiscase,renamethemrespectivelyOrientDBGraphandOrientDBGraphwasOrientDBGraphisthenameoftheservicethatyou
aregoingtoconfigurewiththescriptbelow.Ifyouwanttouseadifferenceservicename,youhavetorenamebothapplication
respectivelymyservicenameandmyservicenamew(forexample,ifyouarewrappingOrientDBandthenameoftheserviceis
OrientDB,youcouldrenameprunsrvasOrientDBandprunmgrasOrientDBw).Afterthat,createthefile
%ORIENTDB_HOME%\service\installS ervice.batwiththecontentdepictedbelow:
::OrientDBWindowsServiceInstallation
@echooff
remRemovesurroundingquotesfromthefirstparameter
setstr=%~1
remCheckJVMDLLlocationparameter
if"%str%"==""gotomissingJVM
setJVM_DLL=%str%
remRemovesurroundingquotesfromthesecondparameter
setstr=%~2
remCheckOrientDBHomelocationparameter
if"%str%"==""gotomissingOrientDBHome
setORIENTDB_HOME=%str%
setCONFIG_FILE=%ORIENTDB_HOME%/config/orientdb-server-config.xml
setLOG_FILE=%ORIENTDB_HOME%/config/orientdb-server-log.properties
setLOG_CONSOLE_LEVEL=info
setLOG_FILE_LEVEL=fine
setWWW_PATH=%ORIENTDB_HOME%/www
setORIENTDB_ENCODING=UTF8
setORIENTDB_SETTINGS=-Dprofiler.enabled=true-Dcache.level1.enabled=false-Dcache.level2.strategy=1
setJAVA_OPTS_SCRIPT=-XX:+HeapDumpOnOutOfMemoryError
remInstallservice
OrientDBGraphX.X.X.exe//IS--DisplayName="OrientDBGraphEdX.X.X"^
--Description="OrientDBGraphEdition,akaGraphEd,containsOrientDBserverintegratedwiththelatestreleaseoftheTinkerP
opOpenSourcetechnologystacksupportingpropertygraphdatamodel."^
--StartClass=com.orientechnologies.orient.server.OServerMain--StopClass=com.orientechnologies.orient.server.OServerShutdownMa
in^
--Classpath="%ORIENTDB_HOME%\lib\*"--JvmOptions"-Dfile.Encoding=%ORIENTDB_ENCODING%;-Djava.util.logging.config.file="%LOG_FI
LE%";-Dorientdb.config.file="%CONFIG_FILE%";-Dorientdb.www.path="%WWW_PATH%";-Dlog.console.level=%LOG_CONSOLE_LEVEL%;-Dlog.fil
e.level=%LOG_FILE_LEVEL%;-Dorientdb.build.number="@BUILD@";-DORIENTDB_HOME=%ORIENTDB_HOME%"^
--StartMode=jvm--StartPath="%ORIENTDB_HOME%\bin"--StopMode=jvm--StopPath="%ORIENTDB_HOME%\bin"--Jvm="%JVM_DLL%"--LogPath=
"%ORIENTDB_HOME%\log"--Startup=auto
EXIT/B
:missingJVM
echoInserttheJVMDLLlocation
gotoprintUsage
:missingOrientDBHome
echoInserttheOrientDBHome
gotoprintUsage
:printUsage
echousage:
echoinstallServiceJVM_DLL_locationOrientDB_Home
EXIT/B
Thescriptrequirestwoinputparameters:
1. Thelocationofjvm.dll,forexampleC:\ProgramFiles\Java\jdk1.6.0_26\jre\bin\server\jvm.dll
19
InstallasServiceonWindows
2. ThelocationoftheOrientDBinstallationfolder,forexampleD:\orientdb-graphed-1.0rc5
TheserviceisactuallyinstalledwhenexecutingOrientDBGraph.exe(originallyprunsrv)withtheappropriatesetofcommandline
argumentsandparameters.Thecommandlineargument//IS statesthattheexecutionofthatapplicationwillresultinaservice
installation.Belowthereisthetablewiththecommandlineparametersusedintheabovescript.
Parameter
name
Description
S ource
-DisplayName
ThenamedisplayedintheWindowsServices
M anagementConsole
Custom
--Description
ThedescriptiondisplayedintheWindows
ServicesM anagementConsole
Custom
--StartClass
Classthatcontainsthestartupmethod(=the
methodtobecalledtostarttheapplication).
Thedefaultmethodtobecalledisthe main
method
Theclassinvokedinthe*/bin/server.bat*script
--StopClass
ClassthatwillbeusedwhenreceivingaStop
servicesignal.Thedefaultmethodtobecalled
isthe mainmethod
Theclassinvokedinthe*/bin/shutdown.bat*script
--Classpath
SettheJavaclasspath
Thevalueofthe -cpparameterspecifiedinthe
_%ORIENTDB_HOM E%\bin\server.bat_script
-JvmOptions
ListofoptionstobepassedtotheJVM
separatedusingeither#or;characters
Thelistofoptionsintheformof-Dor-Xspecifiedinthe
_%ORIENTDB_HOM E%\bin\server.bat_scriptandthe
definitionoftheORIENTDB_HOM Esystemproperty
--StartM ode
Specifyhowtostarttheprocess.Inthiscase,
itwillstartJavain-processandnotasa
separateimage
BasedonApacheTomcatconfiguration
--StartPath
WorkingpathfortheStartClass
_%ORIENTDB_HOM E%\bin_
--StopM ode
Thesameas--StartM ode
BasedonApacheTomcatconfiguration
--StopPath
WorkingpathfortheStopClass
_%ORIENTDB_HOM E%\bin_
--Jvm
Which*jvm.dll*touse:thedefaultoneorthe
onelocatedinthespecifiedfullpath
Thefirstinputparameterofthisscript.Ensurethatyou
insertthelocationoftheJavaHotSpotServerVM asa
fullpath.Wewillusetheserverversionforbothstartand
stop.
--LogPath
Pathusedbyprunsrvforlogging
ThedefaultlocationoftheApacheCommonsDaemonlog
--Startup
Statesiftheserviceshouldstartatmachine
startupormanually
auto
Foracompletereferencetoallavailableparametersandargumentsforprunsrvandprunmgr,visittheProcrunpage.
Inordertoinstalltheservice:
1. OpentheWindowscommandshell
2. Goto%ORIENTDB_HOME%\service,forexampletypingintheshell >cdD:\orientdb-graphed-1.0rc5\service
3. ExecutetheinstallService.batspecifyingthejvm.dlllocationandtheOrientDBHomeasfullpaths,forexampletypingintheshell
>installService.bat"C:\ProgramFiles\Java\jdk1.6.0_26\jre\bin\server\jvm.dll"D:\orientdb-graphed-1.0rc5
4. OpentheWindowsServicesM anagementConsole-fromthetaskbar,clickonStart,ControlPanel,AdministrativeToolsandthen
Service-andchecktheexistanceofaservicewiththesamenamespecifiedasvalueofthe --DisplayNameparameter(inthiscase
OrientDBGraphEd1.0rc5).Youcanalsouse%ORIENTDB_HOME%\service\OrientDBGraphw.exetomanageandmonitorthe
OrientDBGraphservice.
Otherresources
TolearnmoreabouthowtoinstallOrientDBonspecificenvironmentpleasefollowtheguidebelow:
InstallonLinuxUbuntu
InstallonJBossAS
InstallonGlassFish
20
InstallasServiceonWindows
InstallonUbuntu12.04VPS(DigitalOcean)
InstallasserviceonUnix,LinuxandM acOSX
InstallasserviceonWindows
21
InstallwithDocker
InstallinginaDockerContainer
OrientDBisthefirstM ulti-M odelOpenSourceNoSQLDBM Sthatcombinesthepowerofgraphsandtheflexibilityofdocuments
intoonescalable,high-performanceoperationaldatabase.
Thisrepositoryisadockerfileforcreatinganorientdbimagewith:
explicitorientdbversion(orientdb-2.0)forimagecachestability
initbysupervisord
config,databasesandbackupfoldersexpectedtobemountedasvolumes
Andlotsofinformationfrommyorientdb+dockerexplorations.Readon!
Buildingtheimageonyourown
1. Clonethisprojecttoalocalfolder:
gitclonehttps://github.com/orientechnologies/orientdb-docker.git
2. Buildtheimage:
dockerbuild-t<YOUR_DOCKER_HUB_USER>/orientdb-2.0.
3. PushittoyourDockerHubrepository(itwillaskforyourlogincredentials):
dockerpush<YOUR_DOCKER_HUB_USER>/orientdb-2.0
Allexamplesbelowareusinganimagefromnesrait/orientdb-2.0.Ifyoubuildyourownimagepleasefind/replace"nesrait"withyour
DockerHubuser.
RunningOrientdb
Toruntheimage,run:
dockerrun--nameorientdb-d-v<config_path>:/opt/orientdb/config-v<databases_path>:/opt/orientdb/databases-v<backup_pat
h>:/opt/orientdb/backup-p2424-p2480nesrait/orientdb-2.0
ThedockerimagecontainsaunconfiguredOrientdbinstallationandforrunningit,youneedtoprovideyourownconfigfolderfrom
whichOrientDBwillreaditsstartupsettings.
Thesameappliesforthedatabasesfolderwhichiflocaltotherunningcontainerwouldgoawayassoonasitdied/youkilledit.
ThebackupfolderonlyneedstobemappedifyouactivatethatsettingonyourOrientDBconfigurationfile.
PersistentdistributedstorageusingBTSync
Ifyou'renotrunningOrientDBinadistributedconfigurationyouneedtotakespecialcaretobackupyourdatabase(incaseyourhost
goesdown).
Belowisasimple,yethackish,waytodothis:usingBTSyncdatacontainerstopropagatetheOrientDBconfig,LIVEdatabasesand
backupfolderstoremotelocation(s).Note:don'ttrusttheremotecopyoftheLIVEdatabasefolderunlesstheserverisdownandithas
correctlyflushedchangestodisk.
1. CreateBTSyncsharedfoldersonanyremotelocationforthevariousfolderyouwanttoreplicate
1.1.config:orientdbconfigurationinsidetheconfigfolder
22
InstallwithDocker
1.2.databases:theLIVEdatabasesfolder
1.3.backup:theplacewhereOrientDBwillstorethezippedbackups(ifyouactivatethebackupintheconfigurationfile)
2. TakenoteoftheBTSyncfoldersecretsCONFIG_FOLDER_SECRET,DATABASES_FOLDER_SECRET,
BACKUP_FOLDER_SECRET
3. LaunchBTSyncdatacontainersforeachofthesynchedfolderyoucreatedgivingthempropernames:
dockerrun-d--nameorientdb_config-v/opt/orientdb/confignesrait/btsync/opt/orientdb/configCONFIG_FOLDER_SECRET
dockerrun-d--nameorientdb_databases-v/opt/orientdb/databasesnesrait/btsync/opt/orientdb/databasesDATABASES_FOLDE
R_SECRET
dockerrun-d--nameorientdb_backup-v/opt/orientdb/backupnesrait/btsync/opt/orientdb/backupBACKUP_FOLDER_SECRET
4. WaituntilallfileshavemagicallyappearedinsideyourBTSyncdatavolumes:```bashdockerrun--rm-i-t--volumes-from
orientdb_config--volumes-fromorientdb_databases--volumes-fromorientdb_backupubuntudu-h/opt/orientdb/config
/opt/orientdb/databases/opt/orientdb/backup
5.Finallyyou'rereadytostartyourOrientDBserver
```bash
dockerrun--nameorientdb-d\
--volumes-fromorientdb_config\
--volumes-fromorientdb_databases\
--volumes-fromorientdb_backup\
-p2424-p2480\
nesrait/orientdb-2.0
OrientDBdistributed
Ifyou'rerunningOrientDBdistributed*youwon'thavetheproblemoflosingthecontentsofyourdatabasesfoldersincetheyare
alreadyreplicatedtotheotherOrientDBnodes.Fromthesetupabovesimplyleaveoutthe"--volumes-fromorientdb_databases"
argumentandOrientDBwillusethecontainerstoragetoholdyourdatabases'files.
*note:someextraworkmightbeneededtocorrectlysetuphazelcastrunninginsidedockercontainers(seethisdiscussion).
Ad-hocbackups
WithOrientDB2.0wecannowcreatead-hocbackupsbytakingadvantageofthenewbackup.shscript:
Usingtheorientdb_backupdatacontainerthatwascreatedabove:
dockerrun-i-t--volumes-fromorientdb_config--volumes-fromorientdb_backupnesrait/orientdb-2.0./backup.sh<dburl><
user><password>/opt/orientdb/backup/<backup_file>[<type>]
Orusingahostfolder:
dockerrun-i-t--volumes-fromorientdb_config-v<host_backup_path>:/backupnesrait/orientdb-2.0./backup.sh<dburl><user>
<password>/backup/<backup_file>[<type>]
Eitherway,whenthebackupcompletesyouwillhavethebackupfilelocatedoutsideoftheOrientDBcontainerandreadfor
safekeeping.
Note:Ihaven'ttriedthenon-blockingbackup(type=lvm)yetbutfoundthisdiscussionaboutadockerLVM dependencyissue.
RunningtheOrientdbconsole
23
InstallwithDocker
dockerrun--rm-it\
--volumes-fromorientdb_config\
--volumes-fromorientdb_databases\
--volumes-fromorientdb_backup\
nesrait/orientdb-2.0\
/opt/orientdb/bin/console.sh
24
Runtheserver
RunningtheOrientDBServer
WhenyoufinishinstallingOrientDB,whetheryoubuilditfromsourceordownloadthebinarypackage,youarereadytolaunchthe
databaseserver.Youcaneitherstartitthroughthesystemdaemonorthroughtheprovidedserverscript.Thisarticleonlycoversthe
latter.
Note:IfyouwouldliketorunOrientDBasaserviceonyoursystem,therearesomeadditionalstepsthatyouneedtotake.This
providesalternatemethodsforstartingtheserverandallowsyoutolaunchitasadaemonwhenyoursystemboots.Formore
informationonthisprocesssee:
InstallOrientDBasaServiceonUnix,LinuxandM acOSX
InstallOrientDBasaServiceonM icrosoftWindows
StartingtheDatabaseServer
Whileyoucanrunthedatabaseserverassystemdaemon,youalsohavetheoptionofstartingitdirectly.IntheOrientDBinstallation
directory,(thatis $ORIENTDB_HOME),under bin,thereisafilenamed server.shonUnix-basedsystemsand server.baton
Windows.Executingthisfilestartstheserver.
TolaunchtheOrientDBdatabaseserver,runthefollowingcommands:
25
Runtheserver
$cd$ORIENTDB_HOME/bin
$./server.sh
.
.``
,`:.
`,`,:`
.,.:,,
.,,,,,
..,.:::::````
,`.::,,,,::.,,,,,,`;;.:
`,.::,,,,,,,:.,,.``.:
,,:,:,,,,,,,,::.````.:
,,:.,,,,,,,,,:`::,,,::,::`::,::`::::
,:,,,,,,,,,,::,:,,:.::::.:
:,,,,,,,,,,:,::,,::::.:
`:,,,,,,,,,,:,::,,,.::::::::::.:
`,...,,:,,,,,,,,,:.:,.,,,,::.:
.,,,,::,,,,,,,:`:,,,:`::.:
...,::,,,,::..`:.,,:,:::.:
,::::,,,.`:,,:::::::.:
,,:``,,.
,,,.,`
,,.`,SERVER
```.
``
`
2012-12-2801:25:46:319INFOLoadingconfigurationfrom:config/orientdb-serverconfig.xml...[OServerConfigurationLoaderXml]
2012-12-2801:25:46:625INFOOrientDBServerv1.6isstartingup...[OServer]
2012-12-2801:25:47:142INFO->Loadedmemorydatabase'temp'[OServer]
2012-12-2801:25:47:289INFOListeningbinaryconnectionson0.0.0.0:2424
[OServerNetworkListener]
2012-12-2801:25:47:290INFOListeninghttpconnectionson0.0.0.0:2480
[OServerNetworkListener]
2012-12-2801:25:47:317INFOOrientDBServerv1.6isactive.[OServer]
Thedatabaseserverisnowrunning.Itisaccessibleonyoursystemthroughports 2424and 2480.Atthefirststartuptheserverwill
askfortherootuserpassword.Thepasswordisstoredintheconfigfile.
StoptheServer
OntheconsolewheretheserverisrunningasimpleCTRL+cwillshutdowntheserver.
Theshutdown.sh(shutdown.bat)scriptcouldbeusedtostoptheserver:
$cd$ORIENTDB_HOME/bin
$./shutdown.sh-pROOT_PASSWORD
On*nixsystemsasimplecalltoshutdown.shwillstoptheserverrunningonlocalhost:
$cd$ORIENTDB_HOME/bin
$./shutdown.sh
26
Runtheserver
Itispossibletostopserversrunningonremotehostsorevenondifferentportsonlocalhost:
$cd$ORIENTDB_HOME/bin
$./shutdown.sh-hodb1.mydomain.com-P2424-2430-uroot-pROOT_PASSWORD
Listofparams
-h|--hostHOS TNAMEorIPADDRES S :thehostoripwhereOrientDBisrunning,defaulttolocalhost
-P|--portsPORTorPORTRANGE:singleportvalueorrangeofports;defaultto2424-2430
-u|--userROOTUS ERNAME:root'susername;deafulttoroot
-p|--passwordROOTPAS S WORD:root'suserpassword;mandatory
NOTEOnWindowssystemspasswordisalwaysmandatorybecausethescriptisn'tabletodiscoverthepidoftheOrientDB's
process.
ServerLogMessages
Followingthemasthead,thedatabaseserverbeginstoprintlogmessagestostandardoutput.Thisprovidesyouwithaguidetowhat
OrientDBdoesasitstartsuponyoursystem.
1. Thedatabaseserverloadsitsconfigurationfilefromthefile $ORIENTDB_HOME/config/orientdb-server-config.xml.
Formoreinformationonthisstep,seeOrientDBServer.
2. Thedatabaseserverloadsthe tempdatabaseintomemory.Youcanusethisdatabaseinstoringtemporarydata.
3. Thedatabaseserverbeginslisteningforbinaryconnectionsonport 2424forallconfigurednetworks,( 0.0.0.0).
4. ThedatabaseserverbeginslisteningforHTTPconnectionsonport 2480forallconfigurednetworks,( 0.0.0.0).
AccessingtheDatabaseServer
Bydefault,OrientDBlistensontwodifferentportsforexternalconnections.
Binary:OrientDBlistensonport 2424forbinaryconnectionsfromtheconsoleandforclientsanddriversthatsupportthe
NetworkBinaryProtocol.
HTTP:OrientDBlistensonport 2480forHTTPconnectionsfromOrientDBStudioWebToolandclientsanddriversthat
supporttheHTTP/RESTprotocol,orsimilartools,suchascURL.
IfyouwouldlikethedatabaseservertolistenatdifferentportsorIPaddress,youcandefinethesevaluesintheconfigurationfile
config/orientdb-server-config.xml.
27
Runtheconsole
RunningtheOrientDBConsole
Therearevariousmethodsyoucanusetoconnecttoyourdatabaseserverandtheindividualdatabases,oncetheserverisrunning,such
astheNetworkBinaryandHTTP/RESTprotocols.Inadditiontothese,OrientDBprovidesacommand-lineinterfaceforconnectingto
andworkingwiththedatabaseserver.
StartingtheOrientDBConsole
IntheOrientDBinstallationdirectory,(thatis, $ORIENTDB_HOME,whereyouinstalledthedatabase),under bin,thereisafilecalled
console.shonUnix-basedsystemsandonWindows console.bat.
TolaunchtheOrientDBconsole,runthefollowingcommandafteryoustartthedatabaseserver:
$cd$ORIENTDB_HOME/bin
$./console.sh
OrientDBconsolev.X.X.X(build0)www.orientdb.com
Type'HELP'todisplayallthecommandssupported.
InstallingextensionsforGREMLINlanguagev.X.X.X
orientdb>
TheOrientDBconsoleisnowrunning.Fromthispromptyoucanconnecttoandmanageanyremoteorlocaldatabasesavailabletoyou.
Usingthe HELPCommand
IntheeventthatyouareunfamiliarwithOrientDBandtheavailablecommands,orifyouneedhelpatanytime,youcanusethe HELP
command,ortype ?intotheconsoleprompt.
orientdb>HELP
AVAILABLECOMMANDS:
*alterclass<command-text>Alteraclassinthedatabaseschema
*altercluster<command-text>Alterclassinthedatabaseschema
......
*helpPrintthishelp
*exitClosetheconsole
Foreachconsolecommandavailabletoyou, HELPdocumentsitsbasicuseandwhatitdoes.Ifyouknowtheparticularcommandand
needdetailsonitsuse,youcanprovideargumentsto HELPforfurtherclarification.
orientdb>HELPSELECT
COMMAND:SELECT
-Executeaqueryagainstthedatabaseanddisplaytheresults.
SYNTAX:select<query-text>
WHERE:
-<query-text>:Thequerytoexecute
ConnectingtoServerInstances
28
Runtheconsole
Therearesomeconsolecommands,suchas LISTDATABASESor CREATEDATABASE,whichyoucanrunwhileonlyconnectedtothe
serverinstance.Forothercommands,however,youmustalsoconnecttoadatabase,beforetheyrunwithouterror.
Beforeyoucanconnecttoafreshserverinstanceandfullycontrolit,youneedtoknowtherootpasswordforthedatabase.The
rootpasswordislocatedintheconfigurationfileat config/orientdb-server-config.xml.Youcanfinditbysearchingforthe
<users>element.Ifyouwanttochangeit,edittheconfigurationfileandrestarttheserver.
...
<users>
<userresources="*"
password="my_root_password"
name="root"/>
<userresources="connect,server.listDatabases,server.dblist"
password="my_guest_password"
name="guest"/>
</users>
...
Withtherequiredcredentials,youcanconnecttothedatabaseserverinstanceonyoursystem,orestablisharemoteconnectiontoone
runningonadifferentmachine.
orientdb>CONNECTremote:localhostrootmy_root_password
ConnectingtoremoteServerinstance[remote:localhost]withuser'root'...OK
Onceyouhaveestablishedaconnectiontothedatabaseserver,youcanbegintoexecutecommandsonthatserver,suchas LIST
DATABASESand CREATEDATABASE.
orientdb>LISTDATABASES
Found1databases:
*GratefulDeadConcerts(plocal)
Toconnecttothisdatabaseortoadifferentone,usethe CONNECTcommandfromtheconsoleandspecifytheserverURL,username,
andpassword.Bydefault,eachdatabasehasan adminuserwithapasswordof admin.
Warning:Alwayschangethedefaultpasswordonproductiondatabases.
Theabove LISTDATABASEScommandshowsa GratefulDeadConcertsinstalledonthelocalserver.Toconnecttothisdatabase,runthe
followingcommand:
orientdb>CONNECTremote:localhost/GratefulDeadConcertsadminadmin
Connectingtodatabase[remote:localhost/GratefulDeadConcerts]withuser'admin'...OK
The CONNECTcommandtakesaspecificsyntaxforitsURL.Thatis, remote:localhost/GratefulDeadConcertsintheexample.Ithas
threeparts:
Protocol:Thefirstpartofthedatabaseaddressistheprotocoltheconsoleshoulduseintheconnection.Intheexample,thisis
remote,indicatingthatitshouldusetheTCP/IPprotocol.
Address:ThesecondpartofthedatabaseaddressishostnameorIPaddressofthedatabaseserverthatyouwanttheconsoleto
connectto.Intheexample,thisis localhost,sincetheconnectionismadetoaserverinstancerunningonthelocalfilesystem.
Database:Thethirdpartoftheaddressisthenameofthedatabasethatyouwanttouse.Inthecaseoftheexample,thisis
GratefulDeadConcerts.
Formoredetailedinformationaboutthecommands,seeConsoleCommands.
29
Runtheconsole
Note:TheOrientDBdistributioncomeswiththebundleddatabase GratefulDeadConcertswhichrepresentstheGraphofthe
GratefulDead'sconcerts.ThisdatabasecanbeusedbyanyonetostartexploringthefeaturesandcharacteristicsofOrientDB.
30
RuntheStudio
RuntheStudio
Intheeventthatyou'remorecomfortableinteractingwithdatabasesystemsthroughagraphicalinterface,youcanaccomplishmost
commondatabasetaskswiththewebinterfaceOrientDBStudio.
ConnectingtoStudio
Bydefault,therearenoadditionalstepsthatyouneedtotaketostartOrientDBStudio.WhenyoulaunchtheServer,whetherthrough
thestart-upscript server.shorasasystemdaemon,theStudiowebinterfaceopensautomaticallywithit.
$firefoxhttp://localhost:2480
Fromhereyoucancreateanewdatabase,connecttoordropanexistingdatabase,importapublicdatabaseandnavigatetotheServer
managementinterface.
FormoreinformationontheOrientDBStudio,seeStudio.
31
DataM odeling
Multi-Model
TheOrientDBenginesupportsGraph,Document,Key/Value,andObjectmodels,soyoucanuseOrientDBasareplacementfora
productinanyofthesecategories.However,themainreasonwhyuserschooseOrientDBisbecauseofitstrueMulti-ModelDBM S
abilities,whichcombineallthefeaturesofthefourmodelsintothecore.Theseabilitiesarenotjustinterfacestothedatabaseengine,but
rathertheengineitselfwasbuilttosupportallfourmodels.Thisisalsothemaindifferencetoothermulti-modelDBM Ss,asthey
implementanadditionallayerwithanAPI,whichmimicsadditionalmodels.However,underthehood,they'retrulyonlyonemodel,
thereforetheyarelimitedinspeedandscalability.
TheDocumentModel
Thedatainthismodelisstoredinsidedocuments.Adocumentisasetofkey/valuepairs(alsoreferredtoasfieldsorproperties),where
thekeyallowsaccesstoitsvalue.Valuescanholdprimitivedatatypes,embeddeddocuments,orarraysofothervalues.Documentsare
nottypicallyforcedtohaveaschema,whichcanbeadvantageous,becausetheyremainflexibleandeasytomodify.Documentsare
storedincollections,enablingdeveloperstogroupdataastheydecide.OrientDBusestheconceptsof"classes"and"clusters"asits
formof"collections"forgroupingdocuments.Thisprovidesseveralbenefits,whichwewilldiscussinfurthersectionsofthe
documentation.
OrientDB'sDocumentmodelalsoaddstheconceptofa"LINK"asarelationshipbetweendocuments.WithOrientDB,youcandecide
whethertoembeddocumentsorlinktothemdirectly.Whenyoufetchadocument,allthelinksareautomaticallyresolvedbyOrientDB.
ThisisamajordifferencetootherDocumentDatabases,likeM ongoDBorCouchDB,wherethedevelopermusthandleanyandall
relationshipsbetweenthedocumentsherself.
Thetablebelowillustratesthecomparisonbetweentherelationalmodel,thedocumentmodel,andtheOrientDBdocumentmodel:
RelationalModel
DocumentModel
OrientDBDocumentModel
Table
Collection
ClassorCluster
Row
Document
Document
Column
Key/valuepair
Documentfield
Relationship
notavailable
Link
TheGraphModel
Agraphrepresentsanetwork-likestructureconsistingofVertices(alsoknownasNodes)interconnectedbyEdges(alsoknownasArcs).
OrientDB'sgraphmodelisrepresentedbytheconceptofapropertygraph,whichdefinesthefollowing:
Vertex-anentitythatcanbelinkedwithotherVerticesandhasthefollowingmandatoryproperties:
uniqueidentifier
setofincomingEdges
setofoutgoingEdges
Edge-anentitythatlinkstwoVerticesandhasthefollowingmandatoryproperties:
uniqueidentifier
linktoanincomingVertex(alsoknownashead)
linktoanoutgoingVertex(alsoknownastail)
labelthatdefinesthetypeofconnection/relationshipbetweenheadandtailvertex
Inadditiontomandatoryproperties,eachvertexoredgecanalsoholdasetofcustomproperties.Thesepropertiescanbedefinedby
users,whichcanmakeverticesandedgesappearsimilartodocuments.Inthetablebelow,youcanfindacomparisonbetweenthegraph
model,therelationaldatamodel,andtheOrientDBgraphmodel:
32
DataM odeling
RelationalModel
GraphModel
OrientDBGraphModel
Table
VertexandEdgeClass
Classthatextends"V"(forVertex)and"E"(forEdges)
Row
Vertex
Vertex
Column
VertexandEdgeproperty
VertexandEdgeproperty
Relationship
Edge
Edge
TheKey/ValueModel
Thisisthesimplestmodelofthethree.Everythinginthedatabasecanbereachedbyakey,wherethevaluescanbesimpleandcomplex
types.OrientDBsupportsDocumentsandGraphElementsasvaluesallowingforarichermodel,thanwhatyouwouldnormallyfindin
theclassicKey/Valuemodel.TheclassicKey/Valuemodelprovides"buckets"togroupkey/valuepairsindifferentcontainers.Themost
classicusecasesoftheKey/ValueM odelare:
POSTthevalueaspayloadoftheHTTPcall-> /<bucket>/<key>
GETthevalueaspayloadfromtheHTTPcall-> /<bucket>/<key>
DELETEthevaluebyKey,bycallingtheHTTPcall-> /<bucket>/<key>
Thetablebelowillustratesthecomparisonbetweentherelationalmodel,theKey/Valuemodel,andtheOrientDBKey/Valuemodel:
RelationalModel
Key/ValueModel
OrientDBKey/ValueModel
Table
Bucket
ClassorCluster
Row
Key/Valuepair
Document
Column
notavailable
DocumentfieldorVertex/Edgeproperty
Relationship
notavailable
Link
TheObjectModel
ThismodelhasbeeninheritedbyObjectOrientedprogrammingandsupportsInheritancebetweentypes(sub-typesextendsthe
super-types),PolymorphismwhenyourefertoabaseclassandDirectbindingfrom/toObjectsusedinprogramminglanguages.
Thetablebelowillustratesthecomparisonbetweentherelationalmodel,theObjectmodel,andtheOrientDBObjectmodel:
RelationalModel
ObjectModel
OrientDBObjectModel
Table
Class
ClassorCluster
Row
Object
DocumentorVertex
Column
Objectproperty
DocumentfieldorVertex/Edgeproperty
Relationship
Pointer
Link
33
GraphorDocumentAPI?
GraphorDocumentAPI?
InOrientDB,wecreated2differentAPIs:theDocumentAPIandtheGraphAPI.TheGraphAPIworksontopoftheDocumentAPI.
TheDocumentAPIcontainstheDocument,Key/ValueandObjectOrientedmodels.TheGraphAPIhandlestheVertexandEdge
relationships.
YOU,THEUSER
||||
_||_||
\/||
\/_||_
+-------------+\/
|GraphAPI|\/
+-------------+-----------------+
|DocumentAPI|
+-------------------------------+
|Key/ValueandObjectOriented|
+-------------------------------+
GraphAPI
WithOrientDB2.0,weimprovedourGraphAPItosupportallmodelsinjustoneM ulti-M odelAPI.ThisAPIwillprobablycover
80%ofyourdatabaseusecases,soitshouldbeyour"goto"API,ifyou'restartingwithOrientDB.
UsingtheGraphAPI:
YourData('records'intheRDBM Sworld)willbemodeledasVerticesandEdges.Youcanstorepropertiesinboth.
YoucanstillworkinSchema-Less,Schema-FullorHybridmodes.
RelationshipsaremodeledasBidirectionalEdges.IftheLightweightedgesettingisactive,OrientDBusesLightweightEdgesin
caseswhereedgeshavenoproperties,soithasthesameimpactonspeedandspaceaswithDocumentLINKs,butwiththe
additionalbonusofhavingbidirectionalconnections.Thismeansyoucanusethe MOVEVERTEXcommandtorefactoryourgraph
withnobrokenLINKs.FormoreinformationhowEdgesaremanaged,pleaserefertoLightweightEdges.
DocumentAPI
Whatabouttheremaining20%ofyourdatabaseusecases?ShouldyouneedaDocumentDatabase(whileretainingtheadditional
OrientDBfeatures,likeLINKs)oryoucomefromtheDocumentDatabaseworld,usingtheDocumentAPIcouldbetherightchoice.
ThesearetheProsandConsofusingtheDocumentAPI:
TheDocumentAPIissimplerthantheGraphAPIingeneral.
Relationshipsareonlymono-directional.Ifyouneedbidirectionalrelationships,itisyourresponsibilitytomaintainbothLINKs.
ADocumentisanatomicunit,whilewithGraphs,therelationshipsaremodeledthroughInandOutproperties.Forthisreason,
Graphoperationsmustbedonewithintransactions.Incontrast,whenyoucreatearelationshipbetweendocumentswithaLINK,
thetargetedlinkeddocumentisnotinvolvedinthisoperation.ThisresultsinbetterM ulti-Threadedsupport,especiallywith
insert,deleteandupdateoperations.
34
BasicConcepts
BasicConcepts
TheRecord
Thesmallestunitthatyoucanloadfromandstoreinthedatabase.Recordscomeinfourtypes:
Document
RecordBytes
Vertex
Edge
ARecordisthesmallestunitthatcanbeloadedfromandstoredintothedatabase.ArecordcanbeaDocument,aRecordBytesrecord
(BLOB)aVertexorevenanEdge.
Documents
TheDocumentisthemostflexiblerecordtypeavailableinOrientDB.Documentsaresoftlytypedandaredefinedbyschemaclasses
withdefinedconstraints,butyoucanalsousetheminaschema-lessmodetoo.
Documentshandlefieldsinaflexiblemanner.YoucaneasilyimportandexporttheminJSONformat.Forexample,
{
"name":"Jay",
"surname":"Miner",
"job":"Developer",
"creations":[
{
"name":"Amiga1000",
"company":"CommodoreInc."
},{
"name":"Amiga500",
"company":"CommodoreInc."
}
]
}
ForDocuments,OrientDBalsosupportscomplexrelationships.Fromtheperspectiveofdevelopers,thiscanbeunderstoodasa
persistent Map<String,Object>.
RecordBytes
InadditiontotheDocumentrecordtype,OrientDBcanalsoloadandstorebinarydata.TheRecordBytesrecordtypeissimilartothe
BLOBdatatypeinRelationaldatabases.
Vertex
InGraphdatabases,themostbasicunitofdataisthenode,whichinOrientDBiscalledavertex.TheVertexstoresinformationforthe
database.ThereisaseparaterecordtypecalledtheEdgethatconnectsonevertextoanother.
Verticesarealsodocuments.Thismeanstheycancontainembeddedrecordsandarbitraryproperties.
Edge
InGraphdatabases,anarcistheconnectionbetweentwonodes,whichinOrientDBiscalledanedge.Edgesarebidirectionalandcan
onlyconnecttwovertices.
Edgescanberegularorlightweight.TheRegularEdgesavesasaDocument,whiletheLightweightEdgedoesnot.Foranunderstanding
ofthedifferencesbetweenthese,seeLightweightEdges.
Formoreinformationonconnectingverticesingeneral,seeRelationships,below.
35
BasicConcepts
RecordID
WhenOrientDBgeneratesarecord,itauto-assignsauniqueunitidentifier,calledaRecordID,orRID.ThesyntaxfortheRecordIDis
thepoundsignwiththeclusteridentifierandtheposition.Theformatislikethis:
#<cluster>:<position>.
ClusterIdentifier:Thisnumberindicatestheclustertowhichtherecordbelongs.Positivenumbersintheclusteridentifier
indicatepersistentrecords.Negativenumbersindicatetemporaryrecords,suchasthosethatappearinresult-setsforqueriesthat
useprojections.
Position:Thisnumberdefinestheabsolutepositionoftherecordinthecluster.
NOTE:Theprefixcharacter #ismandatorytorecognizeaRecordID.
Recordsneverlosetheiridentifiersunlesstheyaredeleted.Whendeleted,OrientDBneverrecyclesidentifiers,exceptwith local
storage.Additionally,youcanaccessrecordsdirectlythroughtheirRecordID's.Forthisreason,youdon'tneedtocreateafieldtoserve
astheprimarykey,asyoudoinRelationaldatabases.
RecordVersion
Recordsmaintaintheirownversionnumber,whichincrementsoneachupdate.Inoptimistictransactions,OrientDBcheckstheversion
inordertoavoidconflictsatcommittime.
Class
TheconceptoftheClassistakenfromtheObjectOrientedProgrammingparadigm.InOrientDB,classesdefinerecords.Itisclosestto
theconceptofatableinRelationaldatabases.
Classescanbeschema-less,schema-fulloramix.Theycaninheritfromotherclasses,creatingatreeofclasses.Inheritance,inthis
context,meansthatasub-classextendsaparentclass,inheritingallofitsattributes.
Eachclasshasitsowncluster.Aclassmusthaveatleastoneclusterdefined,whichfunctionsasitsdefaultcluster.But,aclasscan
supportmultipleclusters.Whenyouexecuteaqueryagainstaclass,itautomaticallypropagatestoallclustersthatarepartoftheclass.
Whenyoucreateanewrecord,OrientDBselectstheclustertostoreitinusingaconfigurablestrategy.
Whenyoucreateanewclass,bydefault,OrientDBcreatesanewpersistentclusterwiththesamenameastheclass,inlowercase.
AbstractClass
TheconceptofanAbstractClassisonefamiliartoObject-Orientedprogramming.InOrientDB,thisfeaturehasbeenavailablesince
version1.2.0.Abstractclassesareclassesusedasthefoundationfordefiningotherclasses.Theyarealsoclassesthatcannothave
instances.Formoreinformationonhowtocreateanabstractclass,seeCREATECLASS.
ThisconceptisessentialtoObjectOrientation,withoutthetypicalspammingofthedatabasewithalwaysempty,auto-createdclusters.
FormoreinformationonAbstractClassasaconcept,seeAbstractTypeandAbstractM ethodsandClasses
Classvs.ClusterinQueries
Thecombinationofclassesandclustersisverypowerfulandhasanumberofusecases.Consideranexamplewhereyoucreateaclass
Invoice,withtwoclusters invoice2015and invoice2016.Youcanqueryallinvoicesusingtheclassasatargetwith SELECT.
orientdb>SELECTFROMInvoice
Inadditiontothis,youcanfiltertheresult-setbyyear.Theclass Invoiceincludesa yearfield,youcanfilteritthroughthe WHERE
clause.
orientdb>SELECTFROMInvoiceWHEREyear=2012
36
BasicConcepts
Youcanalsoqueryspecificobjectsfromasinglecluster.Bysplittingtheclass Invoiceacrossmultipleclusters,(thatis,oneperyear),
youcanoptimizethequerybynarrowingthepotentialresult-set.
orientdb>SELECTFROMCLUSTER:invoice2012
Duetotheoptimization,thisqueryrunssignificantlyfaster,becauseOrientDBcannarrowthesearchtothetargetedcluster.
Relationships
OrientDBsupportstwokindsofrelationships:referencedandembedded.Itcanmanagerelationshipsinaschema-fullorschema-less
scenario.
ReferencedRelationships
InRelationaldatabases,tablesarelinkedthrough JOINcommands,whichcanprovecostlyoncomputingresources.OrientDBmanges
relationshipsnativelywithoutcomputing JOIN's.Instead,itstoresdirectlinkstothetargetobjectsoftherelationship.Thisbooststhe
loadspeedfortheentiregraphofconnectedobjects,suchasinGraphandObjectdatabasesystems.
Forexample
customer
RecordA------------->RecordB
CLASS=InvoiceCLASS=Customer
RID=5:23RID=10:2
Here,record Acontainsthereferencetorecord Bintheproperty customer.Notethatbothrecordsarereachablebyotherrecords,
giventhattheyhaveaRecordID.
WiththeGraphAPI,Edgesarerepresentedwithtwolinksstoredonbothverticestohandlethebidirectionalrelationship.
1:1and1:nReferencedRelationships
OrientDBexpressesrelationshipsofthesekindsusinglinksofthe LINKtype.
1:nandn:nReferencedRelationships
OrientDBexpressesrelationshipsofthesekindsusingacollectionoflinks,suchas:
LINKLISTAnorderedlistoflinks.
LINKSETAnunorderedsetoflinks,whichdoesnotacceptduplicates.
LINKMAPAnorderedmapoflinks,with Stringasthekeytype.Duplicateskeysarenotaccepted.
WiththeGraphAPI,Edgesconnectonlytwovertices.Thismeansthat1:nrelationshipsarenotallowed.Tospecifya1:nrelationship
withgraphs,createmultipleedges.
EmbeddedRelationships
WhenusingEmbeddedrelationships,OrientDBstorestherelationshipwithintherecordthatembedsit.Theserelationshipsarestronger
thanReferencerelationships.YoucanrepresentitasaUM LCompositionrelationship.
EmbeddedrecordsdonothavethierownRecordID,giventhatyoucan'tdirectlyreferenceitthroughotherrecords.Itisonlyaccessible
throughthecontainerrecord.
Intheeventthatyoudeletethecontainerrecord,theembeddedrecordisalsodeleted.Forexample,
address
RecordA<>---------->RecordB
CLASS=AccountCLASS=Address
RID=5:23NORID!
37
BasicConcepts
Here,record Acontainstheentiretyofrecord Bintheproperty address.Youcanreachrecord Bonlybytraversingthecontainer
record.Forexample,
orientdb>SELECTFROMAccountWHEREaddress.city='Rome'
1:1andn:1EmbeddedRelationships
OrientDBexpressesrelationshipsofthesekindsusingthe EMBEDDEDtype.
1:nandn:nEmbeddedRelationships
OrientDBexpressesrelationshipsofthesekindsusingacollectionoflinks,suchas:
EMBEDDEDLISTAnorderedlistofrecords.
EMBEDDEDSETAnunorderedsetofrecords,thatdoesn'tacceptduplicates.
EMBEDDEDMAPAnorderedmapofrecordsasthevalueandastringasthekey,itdoesn'tacceptduplicatekeys.
InverseRelationships
InOrientDB,allEdgesintheGraphmodelarebidirectional.ThisdiffersfromtheDocumentmodel,whererelationshipsarealways
unidirectional,requiringthedevelopertomaintaindataintegrity.Inaddition,OrientDBautomaticallymaintainstheconsistencyofall
bidirectionalrelationships.
Database
ThedatabaseisaninterfacetoaccesstherealStorage.ITunderstandshigh-levelconceptssuchasqueries,schemas,metadata,indices
andsoon.OrientDBalsoprovidesmultipledatabasetypes.Formoreinformationonthesetypes,seeDatabaseTypes.
EachserverorJavaVM canhandlemultipledatabaseinstances,butthedatabasenamemustbeunique.Youcan'tmanagetwodatabases
atthesametime,eveniftheyareindifferentdirectories.Tohandlethiscase,usethe $dollarcharacterasaseparatorinsteadofthe
/slashcharacter.OrientDBbindstheentirename,soitbecomesunique,butatthefilesystemlevelitconverts $with /,allowing
multipledatabaseswiththesamenameindifferentpaths.Forexample,
test$customers->test/customers
production$customers=production/customers
Toopenthedatabase,usethefollowingcode:
test=newODatabaseDocumentTx("remote:localhost/test$customers");
production=newODatabaseDocumentTx("remote:localhost/production$customers");
DatabaseURL
OrientDBusesitsownURLformat,ofengineanddatabasenameas <engine>:<db-name>.
Engine
Description
Example
plocal
Thisenginewritestothefilesystemtostoredata.ThereisaLOG
ofchangestorestorethestorageincaseofacrash.
plocal:/temp/databases/petshop/petshop
memory
Openadatabasecompletelyinmemory
memory:petshop
remote
Thestoragewillbeopenedviaaremotenetworkconnection.It
requiresanOrientDBServerupandrunning.Inthismode,the
databaseissharedamongmultipleclients.Syntax: remote:<server>:
[<port>]/db-name.Theportisoptionalanddefaultsto2424.
remote:localhost/petshop
DatabaseUsage
38
BasicConcepts
Youmustalwaysclosethedatabaseonceyoufinishworkingonit.
NOTE:OrientDBautomaticallyclosesallopeneddatabases,whentheprocessdiesgracefully(notbykillingitbyforce).Thisis
assurediftheOperatingSystemallowsagracefulshutdown.
39
SupportedTypes
SupportedTypes
OrientDBsupportsseveraltypesnatively.Belowisthecompletetable.
#id
Type
Description
Autoconversion
from/to
Minimum
Maximum
Javatype
0
Boolean
HandlesonlythevaluesTrueor
False
java.lang.Booleanor
boolean
0
1
String
1
Integer
32-bitsignedIntegers
java.lang.Integeror
int
-2,147,483,648
+2,147,483,647
Any
Number,
String
2
Short
Small16-bitsignedintegers
java.lang.Shortor
short
-32,768
32,767
Any
Number,
String
3
Long
Big64-bitsignedintegers
java.lang.Longor
long
-263
+263-1
Any
Number,
String
4
Float
Decimalnumbers
java.lang.Floator
float
2-149
-23 127
(2-2 )*2
Any
Number,
String
5
Double
Decimalnumberswithhigh
precision
java.lang.Doubleor
double
2-1074
-52 1023
(2-2 )*2
Any
Number,
String
6
Datetime
Anydatewiththeprecisionupto
milliseconds.Toknowmoreabout
it,lookatM anagingDates
java.util.Date
1002020303
Date,Long,
String
7
String
Anystringasalphanumeric
sequenceofchars
java.lang.String
-
-
8
Binary
Cancontainanyvalueasbytearray
byte[]
0
2,147,483,647
String
9
Embedded
TheRecordiscontainedinsidethe
owner.ThecontainedRecordhas
noRecordId
ORecord
-
ORecord
Embedded
list
TheRecordsarecontainedinside
theowner.Thecontainedrecords
havenoRecordIdsandare
reachableonlybynavigatingthe
ownerrecord
List<Object>
0
41,000,000
items
String
Embedded
set
TheRecordsarecontainedinside
theowner.ThecontainedRecords
havenoRecordIdandarereachable
onlybynavigatingtheowner
record
Set<Object>
0
41,000,000
items
String
12
Embedded
map
TheRecordsarecontainedinside
theownerasvaluesoftheentries,
whilethekeyscanonlybeStrings.
ThecontainedordsenoRecordIds
andarereachableonlyby
navigatingtheownerRecord
Map<String,ORecord>
0
41,000,000
items
13
Link
LinktoanotherRecord.It'sa
commonone-to-onerelationship
ORID, <?extends
ORecord>
1:-1
32767:2^63-1
String
14
Linklist
LinkstootherRecords.It'sa
commonone-to-manyrelationship
whereonlytheRecordIdsare
stored
List<?extends
ORecord
0
41,000,000
items
String
10
11
0
Collection<?
extends
ORecord<?>>,
String
Collection<?
40
SupportedTypes
15
Linkset
LinkstootherRecords.It'sa
commonone-to-manyrelationship
Set<?extends
ORecord>
41,000,000
items
Map<String,?
extendsRecord>
0
41,000,000
items
String
java.lang.Byteor
byte
-128
+127
Any
Number,
String
extends
ORecord>,
String
16
Linkmap
LinkstootherRecordsasvalueof
theentries,whilekeyscanonlybe
Strings.It'sacommonOne-toM anyRelationship.Onlythe
RecordIdsarestored
17
Byte
Singlebyte.Usefultostoresmall8bitsignedintegers
18
Transient
Anyvaluenotstoredondatabase
19
Date
Anydateasyear,monthandday.
Toknowmoreaboutit,lookat
M anagingDates
java.util.Date
--
Date,Long,
String
20
Custom
usedtostoreacustomtype
providingthemarshalland
unmarshallmethods
OSerializableStream
0
X
-
21
Decimal
Decimalnumberswithoutrounding
java.math.BigDecimal
?
?
Any
Number,
String
22
LinkBag
ListofRecordIdsasspecRidBag
ORidBag
?
?
-
23
Any
Notdeterminatedtype,usedto
specifyCollectionsofmixedtype,
andnull
-
-
-
41
Inheritance
Inheritance
UnlikemanyObject-relationalmappingtools,OrientDBdoesnotsplitdocumentsbetweendifferentclasses.Eachdocumentresidesin
oneoranumberofclustersassociatedwithitsspecificclass.Whenyouexecuteaqueryagainstaclassthathassubclasses,OrientDB
searchestheclustersofthetargetclassandallsubclasses.
DeclaringInheritanceinSchema
Indevelopingyourapplication,bearinmindthatOrientDBneedstoknowtheclassinheritancerelationship.Thisisanabstractconcept
thatappliestobothPOJO'sandDocuments.
Forexample,
OClassaccount=database.getMetadata().getSchema().createClass("Account");
OClasscompany=database.getMetadata().getSchema().createClass("Company").setSuperClass(account);
UsingPolymorphicQueries
Bydefault,OrientDBtreatsallqueriesaspolymorphic.Usingtheexampleabove,youcanrunthefollowingqueryfromtheconsole:
orientdb>SELECTFROMAccountWHEREname.toUpperCase()='GOOGLE'
Thisqueryreturnsallinstancesoftheclasses Accountand Companythathaveapropertynamethatmatches Google.
HowInheritanceWorks
Consideranexample,whereyouhavethreeclasses,listedherewiththeclusteridentifierintheparentheses.
Account(10)<|---Company(13)<|---OrientTechnologiesGroup(27)
Bydefault,OrientDBcreatesaseparateclusterforeachclass.Itindicatesthisclusterbythe defaultClusterIdpropertyintheclass
OClassandindicatestheclusterusedbydefaultwhennotspecified.However,theclass OClasshasaproperty clusterIds,(as
int[]),thatcontainsalltheclustersabletocontaintherecordsofthatclass. clusterIdsand defaultClusterIdarethesameby
default.
Whenyouexecuteaqueryagainstaclass,OrientDBlimitstheresult-setstoonlytherecordsoftheclusterscontainedinthe
clusterIdsproperty.Forexample,
orientdb>SELECTFROMAccountWHEREname.toUpperCase()='GOOGLE'
Thisqueryreturnsalltherecordswiththenamepropertysetto GOOGLEfromallthreeclasses,giventhatthebaseclass Accountwas
specified.Fortheclass Account,OrientDBsearchesinsidetheclusters 10, 13and 17,followingtheinheritancespecifiedinthe
schema.
42
Concurrency
Concurrency
OrientDBusesanoptimisticapproachtoconcurrency.OptimisticConcurrencyControl,orOCCassumesthatmultipletransactionscan
competefrequentlywithoutinterferingwitheachother.
OptimisticConcurrencyinOrientDB
Optimisticconcurrencycontrolisusedinenvironmentswithlowdatacontention.Thatis,whereconflictsarerareandtransactionscan
completewithouttheexpenseofmanaginglocksandwithouthavingtransactionswaitforlockstoclear.Thismeansareduced
throughputoverotherconcurrencycontrolmethods.
OrientDBusesOCCforbothAtomicOperationsandTransactions.
AtomicOperations
OrientDBsupportsM ulti-VersionConcurrencyControl,orM VCC,withatomicoperations.Thisallowsittoavoidlockingserverside
resources.Atthesametime,itcheckstheversioninthedatabase.Iftheversionisequaltotherecordversioncontainedintheoperation,
theoperationissuccessful.Iftheversionfoundishigherthantherecordversioncontainedintheoperation,thenanotherthreadoruser
hasalreadyupdatedthesamerecord.Inthiscase,OrientDBgeneratesan OConcurrentModificationExceptionexception.
Giventhatbehaviorofthiskindisnormalonsystemsthatuseoptimisticconcurrencycontrol,developersneedtowriteconcurrencyproofcode.Underthisdesign,theapplicationretriestransactionsxtimesbeforereportingtheerror.Itdoesthisbycatchingthe
exception,reloadingtheaffectedrecordsandattemptingtoupdatethemagain.Forexample,considerthecodeforsavingadocument,
intmaxRetries=10;
List<ODocument>result=db.query("SELECTFROMClientWHEREid='39w39D32d2d'");
ODocumentaddress=result.get(0);
for(intretry=0;retry<maxRetries;++retry){
try{
//LOOKUPFORTHEINVOICEVERTEX
address.field("street",street);
address.field("zip",zip);
address.field("city",cityName);
address.field("country",countryName);
address.save();
//EXITFROMRETRYLOOP
break;
}
catch(ONeedRetryExceptione){
//IFSOMEONEUPDATESTHEADDRESSDOCUMENT
//ATTHESAMETIME,RETRYIT.
}
}
Transactions
OrientDBsupportsoptimistictransactions.Thedatabasedoesnotuselockswhentransactionsarerunning,butwhenthetransaction
commits,eachrecord(documentorgraphelement)versionischeckedtoseeiftherehavebeenupdatesfromanotherclient.Forthis
reason,youneedtocodeyourapplicationstobeconcurrency-proof.
Optimisticconcurrencyrequiresthatyouretirethetransactionintheeventofconflicts.Forexample,consideracasewhereyouwantto
connectanewvertextoanexistingvertex:
43
Concurrency
intmaxRetries=10;
for(intretry=0;retry<maxRetries;++retry){
try{
//LOOKUPFORTHEINVOICEVERTEX
Vertexinvoice=graph.getVertices("invoiceId",2323);
//CREATEANEWITEM
VertexinvoiceItem=graph.addVertex("class:InvoiceItem");
invoiceItem.field("price",1000);
//ADDITTOTHEINVOICE
invoice.addEdge(invoiceItem);
graph.commit();
//EXITFROMRETRYLOOP
break;
}
catch(OConcurrentModificationExceptione){
//SOMEONEHASUPDATEDTHEINVOICEVERTEX
//ATTHESAMETIME,RETRYIT
}
}
ConcurrencyLevel
Inordertoguaranteeatomicityandconsistency,OrientDBusesanexclusivelockonthestorageduringtransactioncommits.Thismeans
thattransactionsareserialized.
Giventhislimitation,developerswithOrientDBareworkingonimprovingparallelismtoachievebetterscalabilityonmulti-core
machines,byoptimizinginternalstructuretoavoidexclusivelocking.
ConcurrencywhenAddingEdges
Considerthecasewheremultipleclientsattempttoaddedgesonthesamevertex.OrientDBcouldthrowthe
OConcurrentModificationExceptionexception.Thisoccursbecausecollectionsofedgesarekeptonvertices,meaningthat,everytime
OrientDBaddsorremovesanedge,bothverticesupdateandtheirversionsincrement.YoucanavoidthisissuebyusingRIDBAG
Bonsaistructure,whichareneverembedded,sotheedgeneverupdatesthevertices.
Tousethisconfigurationatrun-time,beforelaunchingOrientDB,usethiscode:
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
Alternatively,youcansetaparameterfortheJavavirtual-machineonstartup,orevenatrun-time,beforeOrientDBisused:
$java-DridBag.embeddedToSbtreeBonsaiThreshold=-1
WhilerunningindistributedmodeS BTreesarenotsupported.Ifusingadistributeddatabase
thenyoumustset
ridBag.embeddedToSbtreeBonsaiThreshold=Integer.MAX\_VALUE
toavoidreplicationerrors.
Troubleshooting
ReduceTransactionSize
44
Concurrency
Onoccasion,OrientDBthrowsthe OConcurrentModificationExceptionexceptionevenwhenyouconcurrentlyupdatethefirstelement.
Inparticularlylargetransactions,whereyouhavethousandsofrecordsinvolvedinatransaction,onechangedrecordisenoughtorollthe
entireprocessbackwithan OConcurrentModificationExceptionexception.
Toavoidissuesofthiskind,ifyouplantoupdatemanyelementsinthesametransactionwithhigh-concurrencyonthesamevertices,a
bestpracticeistoreducethetransactionsize.
45
Schema
Schema
WhileOrientDbcanworkinaschema-lessmode,youmayfinditnecessaryattimestoenforceaschemaonyourdatamodel.OrientDB
supportsbothschema-fullandschema-hybridsolutions.
Inthecaseofschema-hybridmode,youonlysetconstraintsforcertainfieldsandleavetheusertoaddcustomfieldstotherecord.This
modeoccursataclasslevel,meaningthatyoucanhavean Employeeclassasschema-fullandan EmployeeInformationclassasschemaless.
S chema-fullEnablesstrict-modeataclass-levelandsetsallfieldsasmandatory.
S chema-lessEnablesclasseswithnoproperties.Defaultisnon-strict-mode,meaningthatrecordscanhavearbitraryfields.
S chema-hybridEnablesclasseswithsomefields,butallowsrecordstodefinecustomfields.Thisisalsosometimescalledschemamixed.
NOTEChangestotheschemaarenottransactional.Youmustexecutethesecommandsoutsideofatransaction.
YoucanaccesstheschemathroughSQLorthroughtheJavaAPI.Exampleshereusethelatter.ToaccesstheschemaAPIinJava,you
needtheSchemainstanceofthedatabaseyouwanttouse.Forexample,
OSchemaschema=database.getMetadata().getSchema();
Class
OrientDBdrawsfromtheObjectOrientedprogrammingparadigmintheconceptoftheClass.Aclassisatypeofrecord.Incomparison
toRelationaldatabasesystems,itismostsimilarinconceptiontothetable.
Classescanbeschema-less,schema-fullorschema-hybrid.Theycaninheritfromotherclasses,shapingatreeofclasses.Inotherwords,
asub-classextendstheparentclass,inheritingallattributes.
Eachclasshasitsownclusters.Bydefault,theseclustersarelogical,buttheycanalsobephysical.Agivenclassmusthaveatleastone
clusterdefinedasitsdefault,butitcansupportmultipleclusters.OrientDBwritesnewrecordsintothedefaultcluster,butalways
readsfromalldefinedclusters.
Whenyoucreateanewclass,OrientDBcreatesadefaultphysicalclusterthatusesthesamenameastheclass,butinlowercase.
CreatingPersistentClasses
Classescontainoneormoreproperties.ThismodeissimilartotheclassicalmodeloftheRelationaldatabase,whereyoumustdefine
tablesbeforeyoucanbegintostorerecords.
TocreateapersistentclassinJava,usethe createClass()method:
OClassaccount=database.getMetadata().getSchema().createClass("Account");
Thismethodcreatestheclass Accountonthedatabase.Itsimultaneouslycreatesthephysicalcluster account,toprovidestoragefor
recordsintheclass Account.
GettingPersistentClasses
Withthenewpersistentclasscreated,youmayalsoneedtogetitscontents.
ToretrieveapersistentclassinJava,usethe getClass()method:
OClassaccount=database.getMetadata().getSchema().getClass("Account");
Thismethodretrievesfromthedatabasethepersistentclass Account.Ifthequeryfindsthatthe Accountclassdoesnotexist,it
returns NULL.
46
Schema
DroppingPersistentClasses
Intheeventthatyounolongerwanttheclass,youcandrop,ordelete,itfromthedatabase.
TodropapersistentclassinJava,usethe OSchema.dropClass()method:
database.getMetadata().getSchema().dropClass("Account");
Thismethoddropstheclass Accountfromyourdatabase.Itdoesnotdeleterecordsthatbelongtothisclassunlessyouexplicitlyask
ittodoso:
database.command(newOCommandSQL("DELETEFROMAccount")).execute();
database.getMetadata().getSchema().dropClass("Account");
Constraints
Workinginschema-fullmoderequiresthatyousetthestrictmodeattheclass-level,bydefiningthe setStrictMode()methodto
TRUE.Inthiscase,recordsofthatclasscannothaveundefinedproperties.
Properties
InOrientDB,apropertyisafieldassignedtoaclass.Forthepurposesofthistutorial,considerPropertyandFieldassynonymous.
CreatingClassProperties
Afteryoucreateaclass,youcandefinefieldsforthatclass.Todefineafield,usethe createProperty()method.
OClassaccount=database.getMetadata().getSchema().createClass("Account");
account.createProperty("id",OType.Integer);
account.createProperty("birthDate",OType.Date);
Theselinescreateaclass Account,thendefinestwoproperties idand birthDate.Bearinmindthateachfieldmustbelongtoone
ofthesupportedtypes.Herethesearetheintegeranddatetypes.
DroppingClassProperties
Intheeventthatyouwouldliketoremovepropertiesfromaclassyoucandosousingthe dropProperty()methodunder OClass.
database.getMetadata().getSchema().getClass("Account").dropProperty("name");
Whenyoudropapropertyfromaclass,itdoesnotremoverecordsfromthatclassunlessyouexplicitlyaskforit,usingthe UPDATE...
REMOVEstatements.Forinstance,
database.getMetadata().getSchema().getClass("Account").dropProperty("name");
database.command(newOCommandSQL("UPDATEAccountREMOVEname")).execute();
Thefirstmethoddropsthepropertyfromtheclass.Thesecondupdatesthedatabasetoremovetheproperty.
Relationships
OrientDBsupportstwotypesofrelationships:referencedandembedded.
ReferencedRelationships
Inthecaseofreferencedrelationships,OrientDBusesadirectlinktothereferencedrecordorrecords.Thisallowsthedatabasetoavoid
thecostly JOINoperationsusedbyRelationaldatabases.
47
Schema
customer
RecordA------------->RecordB
CLASS=InvoiceCLASS=Customer
RID=5:23RID=10:2
Intheexample,RecordAcontainsthereferencetoRecordBintheproperty customer.Bothrecordsareaccessiblebyanyother
recordssinceeachhasaRecordID.
1:1andn:1ReferenceRelationships
Inonetooneandmanytoonerelationships,thereferencerelationshipisexpressedusingteh LINKtype.Forinstance.
OClasscustomer=database.getMetadata().getSchema().createClass("Customer");
customer.createProperty("name",OType.STRING);
OClassinvoice=database.getMetadata().getSchema().createClass("Invoice");
invoice.createProperty("id",OType.INTEGER);
invoice.createProperty("date",OType.DATE);
invoice.createProperty("customer",OType.LINK,customer);
Here,recordsoftheclass Invoicelinktoarecordoftheclass Customer,throughthefield customer.
1:nandn:nReferenceRelationships.
Inonetomanyandmanytomanyrelationships,OrientDBexpressesthereferencedrelationshipusingcollectionsoflinks.
LINKLISTAnorderedlistoflinks.
LINKSETAnunorderedsetoflinks,thatdoesnotacceptduplicates.
LINKMAPAnorderedmapoflinks,withastringkey.Itdoesnotacceptduplicatekeys.
Forexample,
OClassorderItem=db.getMetadata().getSchema().createClass("OrderItem");
orderItem.createProperty("id",OType.INTEGER);
orderItem.createProperty("animal",OType.LINK,animal);
OClassorder=db.getMetadata().getSchema().createClass("Order");
order.createProperty("id",OType.INTEGER);
order.createProperty("date",OType.DATE);
order.createProperty("items",OType.LINKLIST,orderItem);
Here,youhavetwoclasses: Orderand OrderItemanda1:nreferencedrelationshipiscreatedbetweenthem.
EmbeddedRelationships
Inthecaseofembeddedrelationships,OrientDBcontainstherelationshipwithintherecord.Embeddedrelationshipsarestrongerthan
referencedrelationships,buttheembeddedrecorddoesnothaveitsownRecordID.Becauseofthis,youcannotreferencethemdirectly
throughotherrecords.Therelationshipisonlyaccessiblethroughthecontainerrecord.Ifthecontainerrecordisdeleted,thenthe
embeddedrecordisalsodeleted.
address
RecordA<>---------->RecordB
CLASS=AccountCLASS=Address
RID=5:23NORID!
Here,RecordAcontainstheentiretyofRecordBintheproperty address.YoucanonlyreachRecordBbytraversingthecontainer,
RecordA.
orientdb>SELECTFROMAccountWHEREAddress.city='Rome'
1:1andn:1EmbeddedRelationships
48
Schema
Foronetooneandmanytooneembeddedrelationships,OrientDBuseslinksofthe EMBEDDEDtype.Forexample,
OClassaddress=database.getMetadata().getSchema().createClass("Address");
OClassaccount=database.getMetadata().getSchema().createClass("Account");
account.createProperty("id",OType.INTEGER);
account.createProperty("birthDate",OType.DATE);
account.createProperty("address",OType.EMBEDDED,address);
Here,recordsoftheclass Accountembedrecordsfortheclass Address.
1:nandn:nEmbeddedRelationships
Inthecaseofonetomanyandmanytomanyrelationships,OrientDBsuesacollectionembeddedlinktypes:
EMBEDDEDLISTAnorderedlistofrecords.
EMBEDDEDSETAnunorderedsetofrecords.Itdoesn'tacceptduplicates.
EMBEDDEDMAPAnorderedmapofrecordsaskey-valuepairs.Itdoesn'tacceptduplicatekeys.
Forexample,
OClassorderItem=db.getMetadata().getSchema().createClass("OrderItem");
orderItem.createProperty("id",OType.INTEGER);
orderItem.createProperty("animal",OType.LINK,animal);
OClassorder=db.getMetadata().getSchema().createClass("Order");
order.createProperty("id",OType.INTEGER);
order.createProperty("date",OType.DATE);
order.createProperty("items",OType.EMBEDDEDLIST,orderItem);
Thisestablishesaonetomanyrelationshipbetweentheclasses Orderand OrderItem.
Constraints
OrientDBsupportsanumberofconstraintsforeachfield.Formoreinformationonsettingconstraints,seethe ALTERPROPERTY
command.
MinimumValue: setMin()Thefieldacceptsastring,becauseitworksalsofordateranges.
MaximumValue: setMax()Thefieldacceptsastring,becauseitworksalsofordaterangers.
Mandatory: setMandatory()Thisfieldisrequired.
ReadOnly: setReadonly()Thisfieldcannotupdateafterbeingcreated.
NotNull: setNotNull()Thisfieldcannotbenull.
Unique:Thisfielddoesn'tallowduplicatesorspeedupsearches.
Regex:ThisfieldmustsatisfyRegularExpressions
Forexample,
profile.createProperty("nick",OType.STRING).setMin("3").setMax("30").setMandatory(true).setNotNull(true);
profile.createIndex("nickIdx",OClass.INDEX_TYPE.UNIQUE,"nick");//Createsuniqueconstraint
profile.createProperty("name",OType.STRING).setMin("3").setMax("30");
profile.createProperty("surname",OType.STRING).setMin("3").setMax("30");
profile.createProperty("registeredOn",OType.DATE).setMin("2010-01-0100:00:00");
profile.createProperty("lastAccessOn",OType.DATE).setMin("2010-01-0100:00:00");
IndicesasConstraints
Todefineapropertyvalueasunique,usethe UNIQUEindexconstraint.Forexample,
profile.createIndex("EmployeeId",OClass.INDEX_TYPE.UNIQUE,"id");
Youcanalsoconstrainagroupofpropertiesasuniquebycreatingacompositeindexmadefrommultiplefields.Forinstance,
49
Schema
profile.createIndex("compositeIdx",OClass.INDEX_TYPE.NOTUNIQUE,"name","surname");
FormoreinformationaboutindexeslookatIndexguide.
50
ClusterSelection
ClusterSelection
Whenyoucreateanewrecordandspecifytheclasstowhichitbelongs,OrientDBautomaticallyselectsacluster,whereitstoresthe
physicaldataoftherecord.ThereareanumberofconfigurationstrategiesavailableforyoutouseindetermininghowOrientDBselects
theappropriateclusterforthenewrecord.
defaultItselectstheclusterusingthe defaultClusterIdpropertyfromtheclass.Priortoversion1.7,thiswasthedefault
method.
round-robinItarrangestheconfiguredclustersfortheclassintosequenceandassignseachnewrecordtothenextclusterinorder.
balancedItchecksthenumberofrecordsintheconfiguredclustersfortheclassandassignsthenewrecordtowhicheveristhe
smallestatthetime.Toavoidlatencyissuesondatainsertions,OrientDBcalculatesclustersizeeveryfivesecondsorlonger.
localWhenthedatabaseisrunindistributedmode,itselectsthemasterclusteronthecurrentnode.Thishelpstoavoidconflicts
andreducenetworklatencywithremotecallsbetweennodes.
Whicheverclusterselectionstrategyworksbestforyourapplication,youcanassignitthroughthe ALTERCLASS...CLUSTERSELECTION
command.Forexample,
orientdb>ALTERCLASSAccountCLUSTERSELECTIONround-robin
Whenyourunthiscommand,itupdatesthe Accountclasstousethe round-robinselectionstrategy.Itcyclesthroughavailable
clusters,addingnewrecordstoeachinsequence.
CustomClusterSelectionStrategies
Inadditiontotheclusterselectionstrategieslistedabove,youcanalsodevelopyourownselectstrategiesthroughtheJavaAPI.This
ensuresthatitthestrategiesthatareavailablebydefaultdonotmeetyourparticularneeds,youcandeveloponethatdoes.
1. Usingyourpreferredtexteditor,createtheimplementationinJava.Inordertouseacustomstrategy,theclassmustimplementthe
OClusterSelectionStrategyinterface.
packagemypackage;
publicclassRandomSelectionStrategyimplementsOClusterSelectionStrategy{
publicintgetCluster(finalOClassiClass,finalODocumentdoc){
finalint[]clusters=iClass.getClusterIds();
//RETURNARANDOMCLUSTERIDINTHELIST
returnnewRandom().nextInt(clusters.length);
}
publicStringgetName(){return"random";}
}
Bearinmindthatthemethod getCluster()alsoreceivesthe ODocumentclustertoinsert.Youmayfindthisuseful,ifyouwant
toassignthe clusterIdvariable,basedontheDocumentcontent.
2. Registertheimplementationasaservice.Youcandothisbycreatinganewfileunder META-INF/service.Usethefilename
com.orientechnologies.orient.core.metadata.schema.clusterselection.OClusterSelectionStrategy.Foritscontents,codeyour
classwiththefullpackage.Forinstance,
mypackage.RandomSelectionStrategy
ThisaddstothedefaultcontentintheOrientDBcore:
com.orientechnologies.orient.core.metadata.schema.clusterselection.ORoundRobinClusterSelectionStrategy
com.orientechnologies.orient.core.metadata.schema.clusterselection.ODefaultClusterSelectionStrategy
com.orientechnologies.orient.core.metadata.schema.clusterselection.OBalancedClusterSelectionStrategy
51
ClusterSelection
3. Fromthedatabaseconsole,assignthenewselectionstrategytoyourclasswiththe ALTERCLASS...CLUSTERSELECTIONcommand.
orientdb>ALTERCLASSEmployeeCLUSTERSELECTIONrandom
Theclass Employeenowselectsclustersusing random,yourcustomstrategy.
52
M anagingDates
ManagingDates
OrientDBtreatsdatesasfirstclasscitizens.Internally,itsavesdatesintheUnixtimeformat.M eaning,itstoresdatesasa long
variable,whichcontainsthecountinmillisecondssincetheUnixEpoch,(thatis,1January1970).
DateandDatetimeFormats
InordertomaketheinternalcountfromtheUnixEpochintosomethinghumanreadable,OrientDBformatsthecountintodateand
datetimeformats.Bydefault,theseformatsare:
DateFormat: yyyy-MM-dd
DatetimeFormat: yyyy-MM-ddHH:mm:ss
Intheeventthatthesedefaultformatsarenotsufficientfortheneedsofyourapplication,youcancustomizethemthrough ALTER
DATABASE...DATEFORMATand DATETIMEFORMATcommands.Forinstance,
orientdb>ALTERDATABASEDATEFORMAT"ddMMMMyyyy"
ThiscommandupdatesthecurrentdatabasetousetheEnglishformatfordates.Thatis,14Febr2015.
SQLFunctionsandMethods
Tosimplifythemanagementofdates,OrientDBSQLautomaticallyparsesdatestoandfromstringsandlongs.Thesefunctionsand
methodsprovideyouwithmorecontroltomanagedates:
S QL
Description
DATE()
Functionconvertsdatestoandfromstringsanddates,alsousescustomformats.
SYSDATE()
Functionreturnsthecurrentdate.
.format()
M ethodreturnsthedateindifferentformats.
.asDate()
M ethodconvertsanytypeintoadate.
.asDatetime()
M ethodconvertsanytypeintodatetime.
.asLong()
M ethodconvertsanydateintolongformat,(thatis,Unixtime).
Forexample,consideracasewhereyouneedtoextractonlytheyearsfordateentriesandtoarrangetheminorder.Youcanusethe
.format()methodtoextractdatesintodifferentformats.
orientdb>SELECT@RID,id,date.format('yyyy')ASyearFROMOrder
--------+----+------+
@RID|id|year|
--------+----+------+
#31:10|92|2015|
#31:10|44|2014|
#31:10|32|2014|
#31:10|21|2013|
--------+----+------+
Inadditiontothis,youcanalsogrouptheresults.Forinstance,extractingthenumberofordersgroupedbyyear.
53
M anagingDates
orientdb>SELECTdate.format('yyyy')ASYear,COUNT(*)ASTotal
FROMOrderORDERBYYear
------+--------+
Year|Total|
------+--------+
2015|1|
2014|2|
2013|1|
------+--------+
Datesbefore1970
WhileyoumayfindthedefaultsystemformanagingdatesinOrientDBsufficientforyourneeds,therearesomecaseswhereitmaynot
proveso.Forinstance,consideradatabaseofarchaeologicalfinds,anumberofwhichdatetoperiodsnotonlybefore1970butpossibly
evenbeforetheCommonEra.Youcanmanagethisbydefininganeraorepochvariableinyourdates.
Forexample,consideraninstancewhereyouwanttoaddarecordnotingthedateforthefoundationofRome,whichistraditionally
referredtoasApril21,753BC.ToenterdatesbeforetheCommonEra,firstrunthe[ ALTERDATABASEDATETIMEFORMAT]commandtoadd
the GGvariabletouseinreferencingtheepoch.
orientdb>ALTERDATABASEDATETIMEFORMAT"yyyy-MM-ddHH:mm:ssGG"
Onceyou'verunthiscommand,youcancreatearecordthatreferencesdateanddatetimebyepoch.
orientdb>CREATEVERTEXVSETcity="Rome",date=DATE("0753-04-2100:00:00BC")
orientdb>SELECT@RID,city,dateFROMV
-------+------+------------------------+
@RID|city|date|
-------+------+------------------------+
#9:10|Rome|0753-04-2100:00:00BC|
-------+------+------------------------+
Using .format()onInsertion
Inadditiontotheabovemethod,insteadofchangingthedateanddatetimeformatsforthedatabase,youcanformattheresultsasyou
insertthedate.
orientdb>CREATEVERTEXVSETcity="Rome",date=DATE("yyyy-MM-ddHH:mm:ssGG")
orientdb>SELECT@RID,city,dateFROMV
------+------+------------------------+
@RID|city|date|
------+------+------------------------+
#9:4|Rome|0753-04-2100:00:00BC|
------+------+------------------------+
Here,youagaincreateavertexforthetraditionaldateofthefoundationofRome.However,insteadofalteringthedatabase,youformat
thedatefieldin CREATEVERTEXcommand.
ViewingUnixTime
54
M anagingDates
Inadditiontotheformatteddateanddatetime,youcanalsoviewtheunderlyingcountfromtheUnixEpoch,usingthe asLong()
methodforrecords.Forexample,
orientdb>SELECT@RID,city,date.asLong()FROM#9:4
------+------+------------------------+
@RID|city|date|
------+------+------------------------+
#9:4|Rome|-85889120400000|
------+------+------------------------+
M eaningthat,OrientDBrepresentsthedateofApril21,753BC,as-85889120400000inUnixtime.Youcanalsoworkwithdates
directlyaslongs.
orientdb>CREATEVERTEXVSETcity="Rome",date=DATE(-85889120400000)
orientdb>SELECT@RID,city,dateFROMV
-------+------+------------------------+
@RID|city|date|
-------+------+------------------------+
#9:11|Rome|0753-04-2100:00:00BC|
-------+------+------------------------+
UseISO8601Dates
AccordingtoISO8601,CombineddateandtimeinUTC:2014-12-20T00:00:00.Tousethisstandardchangethedatetimeformatinthe
database:
ALTERDATABASEDATETIMEFORMATyyyy-MM-dd'T'HH:mm:ss.SSS'Z'
55
Classes
Classes
M ulti-modelsupportintheOrientDBengineprovidesanumberofwaysinapproachingandunderstandingitsbasicconcepts.These
conceptsareclearestwhenviewedfromtheperspectiveoftheDocumentDatabaseAPI.Likemanydatabasemanagementsystems,
OrientDBusestheRecordasanelementofstorage.Therearemanytypesofrecords,butwiththeDocumentDatabaseAPI,records
alwaysusetheDocumenttype.Documentsareformedbyasetofkey/valuepairs,referredtoasfieldsandproperties,andcanbelongto
aclass.
TheClassisaconceptdrawnfromtheObject-orientedprogrammingparadigm.Itisatypeofdatamodelthatallowsyoutodefine
certainrulesforrecordsthatbelongtoit.InthetraditionalDocumentdatabasemodel,itiscomparabletothecollection,whileinthe
Relationaldatabasemodelitiscomparabletothetable.
Formoreinformationonclassesingeneral,seeWikipedia.
Tolistalltheconfiguredclassesonyoursystem,usethe CLASSEScommandintheconsole:
orientdb>CLASSES
CLASSES:
-------------------+------------+----------+-----------+
NAME|SUPERCLASS|CLUSTERS|RECORDS|
-------------------+------------+----------+-----------+
AbstractPerson||-1|0|
Account||11|1126|
Actor||91|3|
Address||19|166|
Animal||17|0|
....|....|....|....|
Whiz||14|1001|
-------------------+------------+----------+-----------+
TOTAL22775|
-------------------------------------------------------+
WorkingwithClasses
Inordertostartusingclasseswithyourownapplications,youneedtounderstandhowtocreateandconfigurethemforuse.Asa
concept,theclassinOrientDBhastheclosestrelationshipwiththetableinrelationaldatabases,but(unliketables)classescanbe
schema-less,schema-fullormixed.Classescaninheritfromotherclasses,creatingtreesofclasses.Eachclasshasitsownclusteror
clusters,(createdbydefault,ifnonearedefined).
FormoreinformationonclassesinOrientDB,seeClass.
Tocreateanewclass,usethe CREATECLASScommand:
orientdb>CREATECLASSStudent
Classcreatedsuccessfully.Totalclassesindatabasenow:92
Thiscreatesaclasscalled Student.Giventhatnoclusterwasdefinedinthe CREATECLASScommand,OrientDBcreatesadefault
clustercalled student,tocontainrecordsassignedtothisclass.Forthemoment,theclasshasnorecordsorpropertiestiedtoit.Itis
nowdisplayedinthe CLASSESlistings.
AddingPropertiestoaClass
56
Classes
Asmentionedabove,OrientDBdoesallowyoutoworkinaschema-lessmode.Thatis,itallowsyoutocreateclasseswithoutdefining
theirproperties.However,intheeventthatyouwouldliketodefineindexesorconstraintsforyourclass,propertiesaremandatory.
Followingthecomparisontorelationaldatabases,ifclassesinOrientDBaresimilartotables,propertiesarethecolumnsonthosetables.
Tocreatenewpropertieson Student,usethe CREATEPROPERTYcommandintheconsole:
orientdb>CREATEPROPERTYStudent.nameSTRING
Propertycreatedsuccessfullywithid=1
orientdb>CREATEPROPERTYStudent.surnameSTRING
Propertycreatedsuccessfullywithid=2
orientdb>CREATEPROPERTYStudent.birthDateDATE
Propertycreatedsuccessfullywithid=3
Thesecommandscreatethreenewpropertiesonthe Studentclasstoprovideyouwithareastodefinetheindividualstudent'sname,
surnameanddateofbirth.
DisplayingClassInformation
Onoccasion,youmayneedtoreferenceaparticularclasstoseewhatclustersitbelongstoandanypropertiesconfiguredforitsuse.
Usingthe INFOCLASScommand,youcandisplayinformationonthecurrentconfigurationandpropertiesofaclass.
Todisplayinformationontheclass Student,usethe INFOCLASScommand:
orientdb>INFOCLASSStudent
Class................:Student
Defaultcluster......:student(id=96)
Supportedclusterids:[96]
Properties:
-----------+--------+--------------+-----------+----------+----------+-----+-----+
NAME|TYPE|LINKEDTYPE/|MANDATORY|READONLY|NOTNULL|MIN|MAX|
||CLASS||||||
-----------+--------+--------------+-----------+----------+----------+-----+-----+
birthDate|DATE|null|false|false|false|||
name|STRING|null|false|false|false|||
surname|STRING|null|false|false|false|||
-----------+--------+--------------+-----------+----------+----------+-----+-----+
AddingConstraintstoProperties
Constraintscreatelimitsonthedatavaluesassignedtoproperties.Forinstance,thetype,theminimumormaximumsizeof,whetheror
notavalueismandatoryorifnullvaluesarepermittedtotheproperty.
Toaddaconstraint,usethe ALTERPROPERTYcommand:
orientdb>ALTERPROPERTYStudent.nameMIN3
Propertyupdatedsuccessfully
57
Classes
Thiscommandaddsaconstraintto Studentonthe nameproperty.Itsetsitsothatanyvaluegiventothisclassandpropertymust
haveaminimumofthreecharacters.
ViewingRecordsinaClass
ClassescontainanddefinerecordsinOrientDB.Youcanviewallrecordsthatbelongtoaclassusingthe BROWSECLASScommandand
databelongingtoaparticularrecordwiththe DISPLAYRECORDcommand.
Intheaboveexamples,youcreateda Studentclassanddefinedtheschemaforrecordsthatbelongtothatclass,butyoudidnotcreate
theserecordsoraddanydata.Asaresult,runningthesecommandsonthe Studentclassreturnsnoresults.Instead,fortheexamples
below,considerthe OUserclass.
orientdb>INFOCLASSOUser
CLASS'OUser'
Superclasses........:[OIdentity]
Defaultcluster......:ouser(id=5)
Supportedclusterids:[5]
Clusterselection....:round-robin
Oversize.............:0.0
PROPERTIES
----------+---------+--------------+-----------+----------+----------+-----+-----+
NAME|TYPE|LINKEDTYPE/|MANDATORY|READONLY|NOTNULL|MIN|MAX|
||CLASS||||||
----------+---------+--------------+-----------+----------+----------+-----+-----+
password|STRING|null|true|false|true|||
roles|LINKSET|ORole|false|false|false|||
name|STRING|null|true|false|true|||
status|STRING|null|true|false|true|||
----------+---------+--------------+-----------+----------+----------+-----+-----+
INDEXES(1altogether)
-------------------------------+----------------+
NAME|PROPERTIES|
-------------------------------+----------------+
OUser.name|name|
-------------------------------+----------------+
OrientDBshipswithanumberofdefaultclasses,whichitusesinconfigurationandinmanagingdataonyoursystem,(theclasseswith
the Oprefixshowninthe CLASSEScommandoutput).The OUserclassdefinestheusersonyourdatabase.
Toseerecordsassignedtothe OUserclass,runthe BROWSECLASScommand:
orientdb>BROWSECLASSOUser
---+------+-------+--------+-----------------------------------+--------+-------+
#|@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]|
---+------+-------+--------+-----------------------------------+--------+-------+
58
Classes
Intheexample,youarelistingalloftheusersofthedatabase.Whilethisisfineforyourinitialsetupandasan
example,itisnotparticularlysecure.Tofurtherimprovesecurityinproductionenvironments,seeSecurity.
Whenyourun BROWSECLASS,thefirstcolumnintheoutputprovidestheidentifiernumber,whichyoucanusetodisplaydetailed
informationonthatparticularrecord.
Toshowthefirstrecordbrowsedfromthe OUserclass,runthe DISPLAYRECORDcommand:
orientdb>DISPLAYRECORD0
------------------------------------------------------------------------------+
Document-@class:OUser@rid:#5:0@version:1|
----------+-------------------------------------------------------------------+
Name|Value|
----------+-------------------------------------------------------------------+
name|admin|
password|{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873F8A81F6F2AB...|
status|ACTIVE|
roles|[#4:0=#4:0]|
----------+-------------------------------------------------------------------+
Bearinmindthatthiscommandreferencesthelastcallof BROWSECLASS.Youcancontinuetodisplayotherrecords,butyoucannot
displayrecordsfromanotherclassuntilyoubrowsethatparticularclass.
59
Clusters
Clusters
TheClusterisaplacewhereagroupofrecordsarestored.LiketheClass,itiscomparablewiththecollectionintraditionaldocument
databases,andinrelationaldatabaseswiththetable.However,thisisaloosecomparisongiventhatunlikeatable,clustersallowyouto
storethedataofaclassindifferentphysicallocations.
Tolistalltheconfiguredclustersonyoursystem,usethe CLUSTERScommandintheconsole:
orientdb>CLUSTERS
CLUSTERS:
-------------+------+-----------+-----------+
NAME|ID|TYPE|RECORDS|
-------------+------+-----------+-----------+
account|11|PHYSICAL|1107|
actor|91|PHYSICAL|3|
address|19|PHYSICAL|166|
animal|17|PHYSICAL|0|
animalrace|16|PHYSICAL|2|
....|....|....|....|
-------------+------+-----------+-----------+
TOTAL23481|
--------------------------------------------+
UnderstandingClusters
Bydefault,OrientDBcreatesoneclusterforeachClass.Startingfromv2.2,OrientDBautomaticallycreatesmultipleclusterspereach
class(thenumberofclusterscreatedisequalstothenumberofCPU'scoresavailableontheserver)toimproveusingofparallelism.All
recordsofaclassarestoredinthesamecluster,whichhasthesamenameastheclass.Youcancreateupto32,767(or,215-1)clusters
inadatabase.Understandingtheconceptsofclassesandclustersallowsyoutotakeadvantageofthepowerofclustersindesigningnew
databases.
Whilethedefaultstrategyisthateachclassmapstoonecluster,aclasscanrelyonmultipleclusters.Forinstance,youcanspawn
recordsphysicallyinmultiplelocations,therebycreatingmultipleclusters.
Here,youhaveaclass Customerthatreliesontwoclusters:
USA_customers,whichisaclusterthatcontainsallcustomersintheUnitedStates.
China_customers,whichisaclusterthatcontainsallcustomersinChina.
Inthisdeployment,thedefaultclusteris USA_customers.Whenevercommandsarerunonthe Customerclass,suchas INSERT
statements,OrientDBassignsthisnewdatatothedefaultcluster.
60
Clusters
Thenewentryfromthe INSERTstatementisaddedtothe USA_customerscluster,giventhatit'sthedefault.Insertingdataintoanondefaultclusterwouldrequirethatyouspecifytheclusteryouwanttoinsertthedataintoinyourstatement.
Whenyourunaqueryonthe Customerclass,suchas SELECTqueries,forinstance:
OrientDBscansallclustersassociatedwiththeclassinlookingformatches.
Intheeventthatyouknowtheclusterinwhichthedataisstored,youcanquerythatclusterdirectlytoavoidscanningallothersand
optimizethequery.
61
Clusters
Here,OrientDBonlyscansthe China_customersclusterofthe Customerclassinlookingformatches
Note:ThemethodOrientDBusestoselectthecluster,whereitinsertsnewrecords,isconfigurableandextensible.Formore
information,seeClusterSelection.
WorkingwithClusters
InOrientDBtherearetwotypesofclusters:
PhysicalCluster(knownaslocal)whichispersistentbecauseitwritesdirectlytothefilesystem
MemoryClusterwhereeverythingisvolatileandwillbelostonterminationoftheprocessorserverifthedatabaseisremote
Formostcases,physicalclustersarepreferredbecausedatabasesmustbepersistent.OrientDBcreatesphysicalclustersbydefault.
Youmayalsofinditbeneficialtolocatedifferentclustersondifferentservers,physicallyseparatingwhereyoustorerecordsinyour
database.Theadvantagesofthisinclude:
OptimizationFasterqueryexecutionagainstclusters,giventhatyouneedonlysearchasubsetoftheclustersinaclass.
IndexesWithgoodpartitioning,youcanreduceorremovetheuseofindexes.
ParallelQueries:Queriescanberuninparallelwhenmadetodataonmultipledisks.
S harding:Youcanshardlargedata-setsacrossmultipleinstances.
AddingClusters
Whenyoucreateaclass,OrientDBcreatesadefaultclusterofthesamename.Inorderforyoutotakeadvantageofthepowerof
clusters,youneedtocreateadditionalclustersontheclass.Thisisdonewiththe ALTERCLASSstatementinconjunctionwiththe
ADDCLUSTERparameter.
Toaddaclustertothe Customerclass,usean ALTERCLASSstatementintheconsole:
orientdb>ALTERCLASSCustomerADDCLUSTERUK_Customers
Classupdatedsuccessfully
Younowhaveathirdclusterforthe Customerclass,coveringthosecustomerslocatedintheUnitedKingdom.
ViewingRecordsinaCluster
ClustersstoretherecordscontainedbyaclassinOrientDB.Youcanviewallrecordsthatbelongtoaclusterusingthe BROWSECLUSTER
commandandthedatabelongingtoaparticularrecordwiththe DISPLAYRECORDcommand.
62
Clusters
Intheaboveexample,youaddedaclustertoaclassforstoringrecordscustomerinformationbasedontheirlocationsaroundtheworld,
butyoudidnotcreatetheserecordsoraddanydata.Asaresult,runningthesecommandsonthe Customerclassreturnsnoresults.
Instead,fortheexamplesbelow,considerthe ousercluster.
OrientDBshipswithanumberofdefaultclusterstostoredatafromitsdefaultclasses.Youcanseetheseusingthe CLUSTERS
command.Amongthese,thereisthe ousercluster,whichstoresdataoftheusersonyourdatabase.
Toseerecordsstoredinthe ousercluster,runthe BROWSECLUSTERcommand:
orientdb>BROWSECLUSTEROUser
---+------+--------+--------+----------------------------------+--------+-------+
#|@RID|@CLASS|name|password|status|roles|
---+------+-------+--------+-----------------------------------+--------+-------+
0|#5:0|OUser|admin|{SHA-256}8C6976E5B5410415BDE90...|ACTIVE|[1]|
1|#5:1|OUser|reader|{SHA-256}3D0941964AA3EBDCB00CC...|ACTIVE|[1]|
2|#5:2|OUser|writer|{SHA-256}B93006774CBDD4B299389...|ACTIVE|[1]|
---+------+--------+--------+----------------------------------+--------+-------+
Theresultsareidenticaltoexecuting BROWSECLASSonthe OUserclass,giventhatthereisonlyoneclusterforthe OUserclassinthis
example.
Intheexample,youarelistingalloftheusersofthedatabase.Whilethisisfineforyourinitialsetupandasan
example,itisnotparticularlysecure.Tofurtherimprovesecurityinproductionenvironments,seeSecurity.
Whenyourun BROWSECLUSTER,thefirstcolumnintheoutputprovidestheidentifiernumber,whichyoucanusetodisplaydetailed
informationonthatparticularrecord.
Toshowthefirstrecordbrowsedfromthe ousercluster,runthe DISPLAYRECORDcommand:
orientdb>DISPLAYRECORD0
------------------------------------------------------------------------------+
Document-@class:OUser@rid:#5:0@version:1|
----------+-------------------------------------------------------------------+
Name|Value|
----------+-------------------------------------------------------------------+
name|admin|
password|{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873F8A81F6F2AB...|
status|ACTIVE|
roles|[#4:0=#4:0]|
----------+-------------------------------------------------------------------+
Bearinmindthatthiscommandreferencesthelastcallof BROWSECLUSTER.Youcancontinuetodisplayotherrecords,butyoucannot
displayrecordsfromanotherclusteruntilyoubrowsethatparticularcluster.
63
RecordID
RecordID
InOrientDB,eachrecordhasitsownself-assigneduniqueIDwithinthedatabasecalledRecordIDorRID.Itiscomposedoftwoparts:
#<cluster-id>:<cluster-position>
Thatis,
<cluster-id>Theclusteridentifier.
<cluster-position>Thepositionofthedatawithinthecluster.
Eachdatabasecanhaveamaximumof32,767clusters,or215-1.Eachclustercanhandleupto9,223,372,036,780,000records,or263,
namely9,223,372trillionrecords.
Themaximumsizeofadatabaseis278records,or302,231,454,903trillionrecords.Duetolimitationsinhardwareresources,
OrientDBhasnotbeentestedatsuchhighnumbers,butthereareusersworkingwithOrientDBinthebillionsofrecordsrange.
LoadingRecords
EachrecordhasaRecordID,whichnotesthephysicalpositionoftherecordinsidethedatabase.Whatthismeansisthatwhenyouload
arecordbyitsRID,theloadissignificantlyfasterthanitwouldbeotherwise.
Indocumentandrelationaldatabases,themoredatathatyouhave,theslowerthedatabaseresponds.OrientDBhandlesrelationshipsas
physicallinkstotherecords.Therelationshipisassignedonlyonce,whentheedgeiscreated O(1).Youcancomparethistorelational
databases,whichcomputetherelationshipeverytimethedatabaseisrun O(logN).InOrientDB,thesizeofadatabasedoesnoteffect
thetraversespeed.Thespeedremainsconstant,whetherforonerecordoronehundredbillionrecords.Thisisacriticalfeatureintheage
ofBigData.
Todirectlyloadarecord,usethe LOADRECORDcommandintheconsole.
orientdb>LOADRECORD#12:4
-------------------------------------------------------ODocument-@class:Company@rid:#12:4@version:8
-------------+-----------------------------------------Name|Value
-------------+-----------------------------------------addresses|[NOTLOADED:#19:159]
salary|0.0
employees|100004
id|4
name|Microsoft4
initialized|false
salary2|0.0
checkpoint|true
created|SatDec2923:13:49CET2012
-------------+------------------------------------------
The LOADRECORDcommandreturnssomeusefulinformationaboutthisrecord.Itshows:
thatitisadocument.OrientDBsupportsdifferenttypesofrecords,butdocumentistheonlytypecoveredinthischapter.
thatitbelongstothe Companyclass.
thatitscurrentversionis 8.OrientDBusesanM VCCsystem.Everytimeyouupdatearecord,itsversionincrementsbyone.
64
RecordID
thatwehavedifferentfieldtypes:floatsin salaryand salary2,integersfor employeesand id,stringfor name,booleans
for initializedand checkpoint,anddate-timefor created.
thatthefield addresseshasbeen NOTLOADED.Itisalsoa LINKtoanotherrecord, #19:159.Thisisarelationship.Formore
informationonthisconcept,seeRelationships.
65
Relationships
Relationships
OneofthemostimportantfeaturesofGraphdatabasesliesinhowtheymanagerelationships.M anyuserscometoOrientDBfrom
M ongoDBduetoOrientDBhavingmoreefficientsupportforrelationships.
RelationsinRelationalDatabases
M ostdatabasedevelopersarefamiliarwiththeRelationalmodelofdatabasesandwithrelationaldatabasemanagementsystems,suchas
M ySQLandM S-SQL.Givenitsmorethanthirtyyearsofdominance,thishaslongbeenthoughtthebestwaytohandlerelationships.
Bycontrast,Graphdatabasessuggestamoremodernapproachtothisconcept.
Consider,asanexample,adatabasewhereyouneedtoestablishrelationshipsbetween Customerand Addresstables.
1-to-1Relationship
Relationaldatabasesstorethevalueofthetargetrecordinthe addressrowofthe Customertable.ThisistheForeignKey.The
foreignkeypointstothePrimaryKeyoftherelatedrecordinthe Addresstable.
ConsideracasewhereyouwanttoviewtheaddressofacustomernamedLuca.InaRelationaldatabase,likeM ySQL,thisishowyou
wouldquerythetable:
mysql>SELECTB.locationFROMCustomerA,AddressB
WHEREA.name='Luca'ANDA.address=B.id;
Whathappenshereisa JOIN.Thatis,thecontentsoftwotablesarejoinedtoformtheresults.Thedatabaseexecutesthe JOINevery
timeyouretrievetherelationship.
1-to-ManyRelationship
GiventhatRelationaldatabaseshavenoconceptofacollections,the Customertablecannothavemultipleforeignkeys.Theonlyway
tomanagea1-to-M anyRelationshipindatabasesofthiskindistomovetheForeignKeytothe Addresstable.
66
Relationships
Forexample,consideracasewhereyouwanttoreturnalladdressesconnectedtothecustomerLuca,thisishowyouwouldquerythe
table:
mysql>SELECTB.locationFROMCustomerA,AddressB
WHEREA.name='Luca'ANDB.customer=A.id;
Many-to-Manyrelationship
ThemostcomplicatedcaseistheM any-to-M anyrelationship.Tohandleassociationsofthiskind,Relationaldatabasesrequirea
separate,intermediarytablethatmatchesrowsfromboth Customerand Addresstablesinallrequiredcombinations.Thisresultsina
double JOINperrecordatruntime.
Forexample,consideracasewhereyouwanttoreturnalladdressforthecustomerLuca,thisishowyouwouldquerythetable:
mysql>SELECTB.locationFROMCustomerA,CustomerAddressB,AddressC
WHEREA.name='Luca'ANDB.id=A.idANDB.address=C.id;
Understanding JOIN
67
Relationships
Indocumentandrelationaldatabasesystems,themoredatathatyouhave,theslowerthedatabaserespondsand JOINoperationshave
aheavyruntimecost.
Forrelationaldatabasesystems,thedatabasecomputestherelationshipeverytimeyouquerytheserver.Thattranslatesto O(logN/
block_size).OrientDBhandlesrelationshipsasphysicallinkstotherecordsandassignsthemonlyonce,whentheedgeiscreated.
Thatis, O(1).
InOrientDB,thespeedoftraversalisnotaffectedbythesizeofthedatabase.Itisalwaysconstantregardlessofwhetherithasone
recordoronehundredbillionrecords.ThisisacriticalfeatureintheageofBigData.
Searchingforanidentifieratruntimeeachtimeyouexecuteaquery,foreveryrecordwillgrowveryexpensive.Thefirstoptimization
withrelationaldatabasesistheuseofindexing.Indexesspeedupsearches,buttheyslowdown INSERT, UPDATE,and DELETE
operations.Additionally,theyoccupyasubstantialamountofspaceonthediskandinmemory.
Consideralsowhethersearchinganindexisactuallyfast.
Indexesand JOIN
Inthedatabaseindustry,thereareanumberofindexingalgorithmsavailable.ThemostcommoninbothrelationalandNoSQLdatabase
systemsistheB+Tree.
Balancetreesallworkinasimilarmanner.Forexample,consideracasewhereyou'relookingforanentrywiththename Luca:after
onlyfivehops,therecordisfound.
Whilethisisfineonasmalldatabase,considerwhatwouldhappenifthereweremillionsorbillionsofrecords.Thedatabasewouldhave
togothroughmany,manymorehopstofind Luca.And,thedatabasewouldexecutethisoperationonevery JOINperrecord.
Picture:joiningfourtableswiththousandsofrecords.Thenumberof JOINoperationscouldruninthemillions.
RelationsinOrientDB
Thereisno JOINinOrientDB.Instead,ituses LINK. LINKisarelationshipmanagedbystoringthetargetRecordIDinthesource
record.Itissimilartostoringthepointerbetweentwoobjectsinmemory.
Whenyouhave Invoicelinkedto Customer,thenyouhaveapointerto Customerinside Invoiceasanattribute.Theyareexactly
thesame.Inthisway,it'sasthoughyourdatabasewaskeptinmemory:amemoryofseveralexabytes.
TypesofRelationships
In1-to-Nrelationships,OrientDBhandlestherelationshipasacollectionofRecordID's,asyouwouldwhenmanagingobjectsin
memory.
68
Relationships
OrientDBsupportsseveraldifferentkindsofrelationships:
LINKRelationshipthatpointstoonerecordonly.
LINKSETRelationshipthatpointstoseveralrecords.ItissimilartoJavasets,thesameRecordIDcanonlybeincludedonce.The
pointershavenoorder.
LINKLISTRelationshipthatpointstoseveralrecords.ItissimilartoJavalists,theyareorderedandcancontainduplicates.
LINKMAPRelationshipthatpointstoseveralrecordswithakeystoredinthesourcerecord.TheM apvaluesaretheRecordID's.
ItissimilartoJava Map<?,Record>.
69
WorkingwithGraphs
WorkingwithGraphs
Ingraphdatabases,thedatabasesystemgraphsdataintonetwork-likestructuresconsistingofverticesandedges.IntheOrientDB
Graphmodel,thedatabaserepresentsdatathroughtheconceptofapropertygraph,whichdefinesavertexasanentitylinkedwith
otherverticesandanedge,asanentitythatlinkstwovertices.
OrientDBshipswithagenericvertexpersistentclass,called V,aswellasaclassforedges,called E.Asanexample,youcancreatea
newvertexusingthe INSERTcommandwith V.
orientdb>INSERTINTOVSETname='Jay'
CreatedrecordwithRID#9:0
Ineffect,theGraphmodeldatabaseworksontopoftheunderlyingdocumentmodel.But,inordertosimplifythisprocess,OrientDB
introducesanewsetofcommandsformanaginggraphsfromtheconsole.Insteadof INSERT,use CREATEVERTEX
orientdb>CREATEVERTEXVSETname='Jay'
CreatedvertexwithRID#9:1
ByusingthegraphcommandsoverthestandardSQLsyntax,OrientDBensuresthatyourgraphsremainconsistent.Formore
informationontheparticularcommands,seethefollowingpages:
CREATEVERTEX
DELETEVERTEX
CREATEEDGE
DELETEEDGE
UseCase:SocialNetworkforRestaurantPatrons
Whileyouhavetheoptionofworkingwithvertexesandedgesinyourdatabaseastheyare,youcanalsoextendthestandard Vand
Eclassestosuittheparticularneedsofyourapplication.Theadvantagesofthisapproachare,
Itgrantsbetterunderstandingaboutthemeaningoftheseentities.
Itallowsforoptionalconstraintsattheclasslevel.
Itimprovesperformancethroughbetterpartitioningofentities.
Itallowsforobject-orientedinheritanceamongthegraphelements.
Forexample,considerasocialnetworkbasedonrestaurants.Youneedtostartwithaclassforindividualcustomersandanotherforthe
restaurantstheypatronize.Createtheseclassestoextendthe Vclass.
orientdb>CREATECLASSPersonEXTENDSV
orientdb>CREATECLASSRestaurantEXTENDSV
Doingthiscreatestheschemaforyoursocialnetwork.Nowthattheschemaisready,populatethegraphwithdata.
70
WorkingwithGraphs
orientdb>CREATEVERTEXPersonSETname='Luca'
CreatedrecordwithRID#11:0
orientdb>CREATEVERTEXPersonSETname='Bill'
CreatedrecordwithRID#11:1
orientdb>CREATEVERTEXPersonSETname='Jay'
CreatedrecordwithRID#11:2
orientdb>CREATEVERTEXRestaurantSETname='Dante',type='Pizza'
CreatedrecordwithRID#12:0
orientdb>CREATEVERTEXRestaurantSETname='Charlie',type='French'
CreatedrecordwithRID#12:1
Thisaddsthreeverticestothe Personclass,representingindividualusersinthesocialnetwork.Italsoaddstwoverticestothe
Restaurantclass,representingtherestaurantsthattheypatronize.
CreatingEdges
Forthemoment,theseverticesareindependentofoneanother,tiedtogetheronlybytheclassestowhichtheybelong.Thatis,theyare
notyetconnectedbyedges.Beforeyoucanmaketheseconnections,youfirstneedtocreateaclassthatextends E.
orientdb>CREATECLASSEatEXTENDSE
Thiscreatestheclass Eat,whichextendstheclass E. Eatrepresentstherelationshipbetweenthevertex Personandthevertex
Restaurant.
Whenyoucreatetheedgefromthisclass,notethattheorientationoftheverticesisimportant,becauseitgivestherelationshipits
meaning.Forinstance,creatinganedgeintheoppositedirection,(from Restaurantto Person),wouldcallforaseparateclass,such
as Attendee.
TheuserLucaeatsatthepizzajointDante.Createanedgethatrepresentsthisconnection:
orientdb>CREATEEDGEEatFROM(SELECTFROMPersonWHEREname='Luca')
TO(SELECTFROMRestaurantWHEREname='Dante')
CreatingEdgesfromRecordID
IntheeventthatyouknowtheRecordIDofthevertices,youcanconnectthemdirectlywithashorterandfastercommand.For
example,thepersonBillalsoeatsattherestaurantDanteandthepersonJayeatsattherestaurantCharlie.Createedgesintheclass
Eattorepresenttheseconnections.
orientdb>CREATEEDGEEatFROM#11:1TO#12:0
orientdb>CREATEEDGEEatFROM#11:2TO#12:1
71
WorkingwithGraphs
QueryingGraphs
Intheaboveexampleyoucreatedandpopulatedasmallgraphofasocialnetworkofindividualusersandtherestaurantsatwhichthey
eat.Youcannowbegintoexperimentwithqueriesonagraphdatabase.
Tocrossedges,youcanusespecialgraphfunctions,suchas:
OUT()Toretrievetheadjacentoutgoingvertices
IN()Toretrievetheadjacentincomingvertices
BOTH()Toretrievetheadjacentincomingandoutgoingvertices
Forexample,toknowallofthepeoplewhoeatintherestaurantDante,whichhasaRecordIDof #12:0,youcanaccesstherecordfor
thatrestaurantandtraversetheincomingedgestodiscoverwhichentriesinthe Personclassconnecttoit.
orientdb>SELECTIN()FROMRestaurantWHEREname='Dante'
-------+----------------+
@RID|in|
-------+----------------+
#-2:1|[#11:0,#11:1]|
-------+----------------+
ThisquerydisplaystherecordID'sfromthe PersonclassthatconnecttotherestaurantDante.Incasessuchasthis,youcanusethe
EXPAND()specialfunctiontotransformthevertexcollectionintheresult-setbyexpandingit.
orientdb>SELECTEXPAND(IN())FROMRestaurantWHEREname='Dante'
-------+-------------+-------------+---------+
@RID|@CLASS|Name|out_Eat|
-------+-------------+-------------+---------+
#11:0|Person|Luca|#12:0|
#11:1|Person|Bill|#12:0|
-------+-------------+-------------+---------+
CreatingEdgetoConnectUsers
Yourapplicationatthispointshowsconnectionsbetweenindividualusersandtherestaurantstheypatronize.Whilethisisinteresting,
itdoesnotyetfunctionasasocialnetwork.Todoso,youneedtoestablishedgesthatconnecttheuserstooneanother.
Tobegin,asbefore,createanewclassthatextends E:
orientdb>CREATECLASSFriendEXTENDSE
TheusersLucaandJayarefriends.TheyhaveRecordID'sof #12:0and #11:2.Createanedgethatconnectsthem.
orientdb>CREATEEDGEFriendFROM#12:0TO#11:2
Inthe Friendrelationship,orientationisnotimportant.Thatis,ifLucaisafriendofJay'sthenJayisafriendofLuca's.Therefore,
youshouldusethe BOTH()function.
72
WorkingwithGraphs
orientdb>SELECTEXPAND(BOTH('Friend'))FROMPersonWHEREname='Luca'
-------+-------------+-------------+---------+-----------+
@RID|@CLASS|Name|out_Eat|in_Friend|
-------+-------------+-------------+---------+-----------+
#11:2|Person|Jay|#12:1|#12:0|
-------+-------------+-------------+---------+-----------+
Here,the BOTH()functiontakestheedgeclass Friendasanargument,crossingonlyrelationshipsoftheFriendkind,(thatis,itskips
the Eatclass,atthistime).Noteintheresult-setthattherelationshipwithLuca,withaRecordIDof #12:0inthe in_field.
YoucanalsonowviewalltherestaurantspatronizedbyfriendsofLuca.
orientdb>SELECTEXPAND(BOTH('Friend').out('Eat'))FROMPerson
WHEREname='Luca'
-------+-------------+-------------+-------------+--------+
@RID|@CLASS|Name|Type|in_Eat|
-------+-------------+-------------+-------------+--------+
#12:1|Restaurant|Charlie|French|#11:2|
-------+-------------+-------------+-------------+--------+
LightweightEdges
Inversion1.4.x,OrientDBbeginstomanagesomeedgesasLightweightEdges.LightweightEdgesdonothaveRecordID's,butare
physicallystoredaslinkswithinvertices.NotethatOrientDBonlyusesaLightweightEdgeonlywhentheedgehasnoproperties,
otherwiseitusesthestandardEdge.
Fromthelogicpointofview,LightweightEdgesareEdgesinalleffects,sothatallgraphfunctionsworkwiththem.Thisistoimprove
performanceandreducediskspace.
BecauseLightweightEdgesdon'texistasseparaterecordsinthedatabase,somequerieswon'tworkasexpected.Forinstance,
orientdb>SELECTFROME
Formostcases,anedgeisusedconnectingvertices,sothisquerywouldnotcauseanyproblemsinparticular.But,itwouldnotreturn
LightweightEdgesintheresult-set.Intheeventthatyouneedtoqueryedgesdirectly,includingthosewithnoproperties,disablethe
LightweightEdgefeature.
TodisabletheLightweightEdgefeature,executethefollowingcommand.
orientdb>ALTERDATABASECUSTOMuseLightweightEdges=FALSE
Youonlyneedtoexecutethiscommandonce.OrientDBnowgeneratesnewedgesasthestandardEdge,ratherthantheLightweight
Edge.Notethatthisdoesnotaffectexistingedges.
FortroubleshootinginformationonLightweightEdges,seeWhyIcan'tseealltheedges.FormoreinformationintheGraphmodelin
OrientDB,seeGraphAPI.
73
UsingSchemawithGraphs
UsingSchemawithGraphs
OrientDB,throughtheGraphAPI,offersanumberoffeaturesaboveandbeyondthetraditionalGraphDatabasesgiventhatitsupports
conceptsdrawnfromboththeDocumentDatabaseandtheObjectOrientedworlds.Forinstance,considerthepowerofgraphs,when
usedinconjunctionwithschemasandconstraints.
UseCase:CarDatabase
Forthisexample,consideragraphdatabasethatmapstherelationshipbetweenindividualusersandtheircars.First,createthegraph
schemaforthe Personand Carvertexclasses,aswellasthe Ownsedgeclasstoconnectthetwo:
orientdb>CREATECLASSPersonEXTENDSV
orientdb>CREATECLASSCarEXTENDSV
orientdb>CREATECLASSOwnsEXTENDSE
Thesecommandslayouttheschemaforyourgraphdatabase.Thatis,theydefinetwovertexclassesandanedgeclasstoindicatethe
relationshipbetweenthetwo.Withthat,youcanbegintopopulatethedatabasewithverticesandedges.
orientdb>CREATEVERTEXPersonSETname='Luca'
Createdvertex'Person#11:0{name:Luca}v1'in0,012000sec(s).
orientdb>CREATEVERTEXCarSETname='FerrariModena'
Createdvertex'Car#12:0{name:FerrariModena}v1'in0,001000sec(s).
orientdb>CREATEEDGEOwnsFROM(SELECTFROMPerson)TO(SELECTFROMCar)
Creatededge'[e[#11:0->#12:0][#11:0-Owns->#12:0]]'in0,005000sec(s).
QueryingtheCarDatabase
Intheabovesection,youcreateacardatabaseandpopulateditwithverticesandedgestomapouttherelationshipbetweendriversand
theircars.Nowyoucanbegintoquerythisdatabase,showingwhatthoseconnectionsare.Forexample,whatisLuca'scar?Youcanfind
outbytraversingfromthevertexLucatotheoutgoingverticesfollowingthe Ownsrelationship.
orientdb>SELECTNAMEFROM(SELECTEXPAND(OUT('Owns'))FROMPerson
WHEREname='Luca')
----+-------+-----------------+
#|@RID|name|
----+-------+-----------------+
0|#-2:1|FerrariModena|
----+-------+-----------------+
Asyoucansee,thequeryreturnsthatLucaownsaFerrariM odena.Nowconsiderexpandingyourdatabasetotrackwhereeachperson
lives.
74
UsingSchemawithGraphs
AddingaLocationVertex
Considerasituation,inwhichyoumightwanttokeeptrackofthecountriesinwhicheachpersonlives.Inpractice,thereareanumber
ofreasonswhyyoumightwanttodothis,forinstance,forthepurposesofpromotionalmaterialorinalargerdatabasetoanalyzethe
connectionstoseehowresidenceaffectscarownership.
Tobegin,createavertexclassforthecountry,inwhichthepersonlivesandanedgeclassthatconnectstheindividualtotheplace.
orientdb>CREATECLASSCountryEXTENDSV
orientdb>CREATECLASSLivesEXTENDSE
Thiscreatestheschemaforthefeatureyou'readdingtothecarsdatabase.Thevertexclass Countryrecordingcountriesinwhich
peopleliveandtheedgeclass Livestoconnectindividualsinthevertexclass Persontoentriesin Country.
Withtheschemalaidout,createavertexfortheUnitedKingdomandconnectittothepersonLuca.
orientdb>CREATEVERTEXCountrySETname='UK'
Createdvertex'Country#14:0{name:UK}v1'in0,004000sec(s).
orientdb>CREATEEDGELivesFROM(SELECTFROMPerson)TO(SELECTFROMCountry
Creatededge'[e[#11:0->#14:0][#11:0-Lives->#14:0]]'in0,006000sec(s).
ThesecondcommandcreatesanedgeconnectingthepersonLucatothecountryUnitedKingdom.Nowthatyourcarsdatabaseis
definedandpopulated,youcanqueryit,suchasasearchthatshowsthecountrieswherethereareusersthatownaFerrari.
orientdb>SELECTnameFROM(SELECTEXPAND(IN('Owns').OUT('Lives'))
FROMCarWHEREnameLIKE'%Ferrari%')
---+-------+--------+
#|@RID|name|
---+-------+--------+
0|#-2:1|UK|
---+-------+--------+
Using inand outConstraintsonEdges
Intheabovesections,youmodeledthegraphusingaschemawithoutanyconstraints,butyoumightfinditusefultousesome.For
instance,itwouldbegoodtorequirethatan Ownsrelationshiponlyexistbetweenthevertex Personandthevertex Car.
orientdb>CREATEPROPERTYOwns.outLINKPerson
orientdb>CREATEPROPERTYOwns.inLINKCar
Thesecommandslinkoutgoingverticesofthe Personclasstoincomingverticesofthe Carclass.Thatis,itconfiguresyourdatabase
sothatausercanownacar,butacarcannotownauser.
Using MANDATORYConstraintsonEdges
Bydefault,whenOrientDBcreatesanedgethatlacksproperties,itcreatesitasaLightweightEdge.Thatis,itcreatesanedgethathas
nophysicalrecordinthedatabase.Usingthe MANDATORYsetting,youcanstopthisbehavior,forcingittocreatethestandardEdge,
withoutoutrightdisablingLightweightEdges.
75
UsingSchemawithGraphs
orientdb>ALTERPROPERTYOwns.outMANDATORY=TRUE
orientdb>ALTERPROPERTYOwns.inMANDATORY=TRUE
Using UNIQUEwithEdges
Forthesakeofsimplicity,consideracasewhereyouwanttolimitthewaypeopleareconnectedtocarstowheretheusercanonly
matchtothecaronce.Thatis,ifLucaownsaFerrariM odena,youmightprefernottohaveadoubleentryforthatcarintheeventthat
hebuysanewoneafewyearslater.Thisisparticularlyimportantgiventhatourdatabasecoversmakeandmodel,butnotyear.
Tomanagethis,youneedtodefinea UNIQUEindexagainstboththeoutandinproperties.
orientdb>CREATEINDEXUniqueOwnsONOwns(out,in)UNIQUE
Createdindexsuccessfullywith0entriesin0,023000sec(s).
Theindexreturnstellsusthatnoentriesareindexed.Youhavealreadycreatedthe OnwsrelationshipbetweenLucaandtheFerrari
M odena.Inthatcase,however,OrientDBhadcreatedaLightweightEdgebeforeyousettheruletoforcethecreationofdocumentsfor
Ownsinstances.Tofixthis,youneedtodropandrecreatetheedge.
orientdb>DELETEEDGEFROM#11:0TO#12:0
orientdb>CREATEEDGEOwnsFROM(SELECTFROMPerson)TO(SELECTFROMCar)
Toconfirmthatthiswassuccessful,runaquerytocheckthatarecordwascreated:
orientdb>SELECTFROMOwns
---+-------+-------+--------+
#|@RID|out|in|
---+-------+-------+--------+
0|#13:0|#11:0|#12:0|
---+-------+-------+--------+
Thisshowsthatarecordwasindeedcreated.Toconfirmthattheconstraintswork,attempttocreateanedgein Ownsthatconnects
LucatotheUnitedKingdom.
orientdb>CREATEEDGEOwnsFROM(SELECTFROMPerson)TO(SELECTFROMCountry)
Error:com.orientechnologies.orient.core.exception.OCommandExecutionException:
Erroronexecutionofcommand:sql.createedgeOwnsfrom(selectfromPerson)...
Error:com.orientechnologies.orient.core.exception.OValidationException:The
field'Owns.in'hasbeendeclaredasLINKoftype'Car'butthevalueisthe
document#14:0ofclass'Country'
Thisshowsthattheconstraintseffectivelyblockedthecreation,generatingasetoferrorstoexplainwhyitwasblocked.
Younowhaveatypedgraphwithconstraints.Formoreinformation,seeGraphSchema.
76
GraphConsistency
GraphConsistency
BeforeOrientDBv2.1.7,thegraphconsistencycouldbeassuredonlybyusingtransactions.Theproblemswithusingtransactionsfor
simpleoperationslikecreationofedgesare:
speed,thetransactionhasacostincomparisonwithnon-transactionaloperations
managementofoptimisticretryatapplicationlevel.Furthermore,with'remote'connectionsthismeanshighlatency
lowscalabilityonhighconcurrency(thiswillberesolvedinOrientDBv3.0,wherecommitswillnotlockthedatabaseanymore)
Asofv2.1.7,OrientDBprovidesanewmodetomanagegraphswithoutusingtransactions.ItusestheJavaclass OrientGraphNoTxor
viaSQLbychangingtheglobalsetting sql.graphConsistencyModetooneofthefollowingvalues:
tx,thedefault,usestransactionstomaintainconsistency.Thiswastheonlyavailablesettingbeforev2.1.7
notx_sync_repair,avoidstheuseoftransactions.Consistency,incaseofaJVM crash,isguaranteedthroughadatabaserepair
operation,whichrunsatstartupinsynchronousmode.Thedatabasecannotbeuseduntiltherepairisfinished.
notx_async_repair,alsoavoidstheuseoftransactions.Consistency,incaseofJVM crash,isguaranteedthroughadatabaserepair
operation,whichrunsatstartupinasynchronousmode.Thedatabasecanbeusedimmediately,astherepairprocedurewillrunin
thebackground.
Boththenewmodes notx_sync_repairand notx_async_repairwillmanageconflictsautomatically,withaconfigurableRETRY
(default=50).Incasechangestothegraphoccurconcurrently,anyconflictsarecaughttransparentlybyOrientDBandtheoperationsare
repeated.Theoperationsthatsupporttheauto-retryare:
CREATEEDGE
DELETEEDGE
DELETEVERTEX
Usage
Touseconsistencymodesthatdon'tusetransactions,setthe sql.graphConsistencyModeglobalsettingto notx_sync_repairor
notx_async_repairinOrientDB bin/server.shscriptorinthe config/orientdb-server-config.xmlfileunderpropertiessection.
Example:
...
<properties>
...
<entryname="sql.graphConsistencyMode"value="notx_sync_repair"/>
...
</properties>
Thesamecouldbesetbycode,beforeyouopenanyGraph.Example:
OGlobalConfiguration.SQL_GRAPH_CONSISTENCY_MODE.setValue("notx_sync_repair");
Tomakethissettingpersistent,setthe txRequiredForSQLGraphOperationspropertyinthestorageconfiguration,soduringthefollowing
openingoftheGraph,youdon'tneedtosettheglobalsettingagain:
g.getRawGraph().getStorage().getConfiguration().setProperty("txRequiredForSQLGraphOperations","false");
UsageviaJavaAPI
Inordertousenon-transactionalgraphs,afterhavingconfiguredtheconsistencymode(asabove),youcannowworkwiththe
OrientGraphNoTxclass.Example:
OrientGraphNoTxg=newOrientGraphNoTx("plocal:/temp/mydb");
...
v1.addEdge("Friend",v2);
77
GraphConsistency
Concurrentthreadsthatchangethegraphwillretrythegraphchangeincaseofconcurrentmodification(M VCC).Thedefaultvaluefor
maximumretriesis50.Tochangethisvalue,callthe setMaxRetries()API:
OrientGraphNoTxg=newOrientGraphNoTx("plocal:/temp/mydb");
g.setMaxRetries(100);
Thissettingwillbeusedontheactivegraphinstance.Youcanhavemultiplethreads,whichworkonthesamegraphbyusingmultiple
graphinstances,oneperthread.Eachthreadcanthenhavedifferentsettings.It'salsoallowedtowirkwiththreads,whichuse
transactions( OrientGraphclass)andtoworkwithconcurrentthreads,whichdon'tusetransactions.
78
FetchingStrategies
FetchingStrategies
Fetchplansareusedintwodifferentscopes:
1. ConnectionsthatusetheBinaryProtocolcanearlyloadrecordsontheclient's.Ontraversingofconnectedrecords,theclienthasn't
toexecutefurtherremotecallstotheserver,becausetherequestedrecordsarealreadyontheclient'scache
2. ConnectionsthatusetheHTTP/JSONProtocolcanexpandtheresultingJSONtoincludeconnectedrecordsasembeddedinthe
sameJSON.ThisisusefulonHTTPprotocoltofetchalltheconnectedrecordsinjustonecall
FormatforFetchPlans
Inbothsscopes,thefetchplansyntaxisthesame.Intermsoftheiruse,FetchPlansarestringsthatyoucanuseatrun-timeonqueries
andrecordloads.Thesyntaxforthesestringsis,
[[levels]]fieldPath:depthLevel
LevelsIsanoptionalvaluethattellswhichlevelstousewiththeFetchPlans.Levelsstartfrom 0.Asofversion2.1,levelsuse
thefollowingsyntax:
LevelThespecificlevelonwhichtousetheFetchPlan.Forexample,usingthelevel [0]wouldapplyonlytothefirstlevel.
RangeTherangeoflevelsonwhichtousetheFetchPlan.Forexample, [0-2]meanstouseitonthefirsttothirdlevel.You
canalsousethepartialrangesyntax: [-3]meansfromthefirsttofourthlevelwhile [4-]meansfromthefifthlevelto
infinity.
AnyThewildcardvariableindicatesthatyouwanttousetheFetchPlanonalllevels.Forexample, [*].
FieldPathIsthefieldnamepath,whichOrientDBexpectsindotnotation.Thepathbeginsfromeithertherootrecordorthe
wildcardvariable *toindicateanyfield.Youcanalsousethewildcardattheendofthepathtospecifyallpathstahtstartfora
name.
DepthLevelIsthedepthofthelevelrequested.Thedepthlevelvariableusesthefollowingsyntax:
0Indicatestoloadthecurrentrecord.
1-NIndicatestoloadthecurrentrecordtothenthrecord.
-1Indicatesanunlimitedlevel.
-2Indicatesanexcludedlevel.
IntheeventthatyouwanttoexpressmultiplerulesforyourFetchPlans,separatethembyspaces.
ConsiderthefollowingFetchPlansforusewiththeexampleabove:
FetchPlan
Description
*:-1
Fetchesrecursivelytheentiretree.
*:-1orders:0
Fetchesrecursivelyallrecords,butusesthefield ordersintherootclass.Notethatthefield
ordersonlyloadsitsdirectcontent,(thatis,therecords 8:12, 8:19,and 8:23).Noother
recordsinsideofthemload.
*:0
address.city.country:0
Fetchesonlynon-documentfieldsintherootclassandthefield address.city.country,(thatis,
records 10:1, 11:2and 12:3).
[*]in_*:-2out_*:-2
Fetchesallproperties,exceptforedgesatanylevel.
Earlyloadingofrecords
Bydefault,OrientDBloadslinkedrecordsinalazymanner.Thatistosay,itdoesnotloadlinkedfieldsuntilittraversesthesefields.In
situationswhereyouneedtheentiretreeofarecord,thiscanprovecostlytoperformance.Forinstance,
79
FetchingStrategies
Invoice
3:100
|
|customer
+--------->Customer
|5:233
|addresscitycountry
+--------->Address--------->City--------->Country
|10:111:212:3
|
|orders
+--------->*[OrderItemOrderItemOrderItem]
[8:128:198:23]
Here,youhaveaclass Invoice,withlinkedfields customer, cityand orders.Ifyouweretoruna SELECTqueryon Invoice,
itwouldnotloadthelinkedclass,itwouldrequiresevendifferentloadstobuildthereturnvalue.Intheeventthatyouhavearemote
connectionthatmeanssevennetworkcalls,aswell.
Inordertoavoidperformanceissuesthatmayarisefromthisbehavior,OrientDBsupportsfetchingstrategies,calledFetchPlans,that
allowyoutocustomizehowitloadslinkedrecords.TheaimofaFetchPlanistopre-loadconnectedrecordsinasinglecall,ratherthan
several.ThebestuseofFetchPlansisonrecordsloadedthroughremoteconnectionsandwhenusingJSONserializerstoproduceJSON
withnestedrecords.
NOTEOrientDBhandlescirculardependenciestoavoidanyloopswhileitfetcheslinkingrecords.
RemoteConnections
Underthedefaultconfiguration,whenaclientexecutesaqueryorloadsdirectlyasinglerecordtoaremotedatabase,itcontinuestosend
networkcallsforeachlinkedrecordinvolvedinthequery,(thatis,through OLazyRecordList).YoucanmitigatethiswithaFetchPlan.
Whentheclientexecutesaquery,setaFetchPlanwithaleveldifferentfrom 0.Thiscausestheservertotraversealltherecordsofthe
returnresult-set,sendingtheminresponsetoasinglecall.OrientDBloadsallconnectedrecordsintothelocalclient,meaningthatthe
collectionsremainlazy,butwhenaccessingcontent,therecordisloadedfromthelocalcachetomitigatetheneedforadditional
connections.
ExamplesusingtheJavaAPIs
Executeaquerywithacustomfetchplan
List<ODocument>resultset=database.query(newOSQLSynchQuery<ODocument>("select*fromProfile").setFetchPlan("*:-1"));
ExportadocumentanditsnesteddocumentsinJSON
Exportaninvoiceanditscustomer:
invoice.toJSON("fetchPlan:customer:1");
Exportaninvoice,itscustomerandorders:
invoice.toJSON("fetchPlan:customer:1orders:2");
Exportaninvoiceandalltheconnectedrecordsupto3rdlevelofdepth:
invoice.toJSON("fetchPlan:*:3");
FromSQL:
SELECT@this.toJSON('fetchPlan:out_Friend:4')FROM#10:20
80
FetchingStrategies
Exportpathinoutgoingdirectionbyremovingalltheincomingedgesbyusingwildcards(Since2.0):
SELECT@this.toJSON('fetchPlan:in_*:-2')FROM#10:20
NOTES ::
Toavoidlooping,therecordalreadytraversedbyfetchingareexportedonlybytheirRIDs(RecordID)form
"fetchPlan"settingiscasesensitive
Browseobjectsusingacustomfetchplan
for(Accounta:database.browseClass(Account.class).setFetchPlan("*:0addresses:-1")){
System.out.println(a.getName());
}
NOTE:FetchingObjectwillmeantheirpresenceinsideyourdomainentities.Soifyouloadanobjectusingfetchplan *:0all
LINKtypereferenceswon'tbeloaded.
81
UseCases
UseCases
Thispagecontainsthesolutiontothemostcommonusecases.Pleasedon'tconsiderthemasthedefinitivesolution,butassuggestions
wheretogettheideatosolveyourneeds.
Usecases
TimeSeries
Chat
UseOrientDBasaKey/ValueDBM S
Persistent,DistributedandTransactionalQueues
82
TimeSeries
TimeSeriesUseCase
M anagingrecordsrelatedtohistoricalinformationisprettycommon.Whenyouhavemillionsofrecords,indexesstartshowtheir
limitations,becausethecosttofindtherecordsisO(logN).ThisisalsothemainreasonwhyRelationalDBM Saresoslowwithhuge
databases.
Sowhenyouhavemillionsofrecordthebestwaytoscaleuplinearlyisavoidusingindexesatallorasmuchasyoucan.Buthowcan
youretrieverecordsinashorttimewithoutindexes?ShouldOrientDBscantheentiredatabaseateveryquery?No.Youshouldusethe
GraphpropertiesofOrientDB.Let'slookatasimpleexample,wherethedomainarelogs.
Atypicallogrecordhassomeinformationabouttheeventandadate.BelowistheLogrecordtouseinourexample.We'regoingtouse
theJSONformattosimplifyreading:
{
"date":12293289328932,
"priority":"critical",
"note":"Systemreboot"
}
Nowlet'screateatree(thatisadirected,noncyclicgraph)togrouptheLogrecordsbasedonthegranularityweneed.Example:
Year->month(map)->Month->day(map)->Day->hour(map)->Hour
WhereYear,M onth,DayandHourarevertexclasses.EachVertexlinkstheotherVerticesofsmallertype.Thelinksshouldbehandled
usingaM aptomakeeasierthewritingofqueries.
Createtheclasses:
CREATECLASSYear
CREATECLASSMonth
CREATECLASSDay
CREATECLASSHour
CREATEPROPERTYYear.monthLINKMAPMonth
CREATEPROPERTYMonth.dayLINKMAPDay
CREATEPROPERTYDay.hourLINKMAPHour
ExampletoretrievethevertexrelativetothedateM arch2012,20that10am(2012/03/2010:00:00):
SELECTmonth[3].day[20].hour[10].logsFROMYearWHEREyear="2012"
IfyouneedmoregranularitythantheHouryoucangoaheaduntiltheTimeunityouneed:
Hour->minute(map)->Minute->second(map)->Second
NowconnecttherecordtotherightCalendarvertex.IftheusualwaytoretrieveLogrecordsisbyhouryoucouldlinktheLogrecords
intheHour.Example:
Year->month(map)->Month->day(map)->Day->hour(map)->Hour->log(set)->Log
The"log"propertyconnectstheTimeUnittotheLogrecords.SotoretrieveallthelogofM arch2012,20that10am:
SELECTexpand(month[3].day[20].hour[10].logs)FROMYearWHEREyear="2012"
Thatcouldbeusedasstartingpointtoretrieveonlyasub-setoflogsthatsatisfycertainrules.Example:
83
TimeSeries
SELECTFROM(
SELECTexpand(month[3].day[20].hour[10].logs)FROMYearWHEREyear="2012"
)WHEREpriority='critical'
ThatretrievesalltheCRITICALlogsofM arch2012,20that10am.
Joinmultiplehours
Ifyouneedmultiplehours/days/monthsasresultsetyoucanusetheUNIONfunctiontocreateauniqueresultset:
SELECTexpand(records)from(
SELECTunion(month[3].day[20].hour[10].logs,month[3].day[20].hour[11].logs)ASrecords
FROMYearWHEREyear="2012"
)
Inthisexamplewecreateaunionbetweenthe10thand11thhours.Butwhataboutextractingallthehoursofadaywithoutwritinga
hugequery?TheshortestwayisusingtheTraverse.BelowtheTraversetogetallthehoursofoneday:
TRAVERSEhourFROM(
SELECTexpand(month[3].day[20])FROMYearWHEREyear="2012"
)
Soputtingalltogetherthisquerywillextractallthelogsofallthehoursinaday:
SELECTexpand(logs)FROM(
SELECTunion(logs)ASlogsFROM(
TRAVERSEhourFROM(
SELECTexpand(month[3].day[20])FROMYearWHEREyear="2012"
)
)
)
Aggregate
OnceyoubuiltupaCalendarinformofaGraphyoucanuseittostoreaggregatedvaluesandlinkthemtotherightTimeUnit.
Example:storeallthewinningticketofOnlineGames.Therecordstructureinourexampleis:
{
"date":12293289328932,
"win":10.34,
"machine":"AKDJKD7673JJSH",
}
YoucanlinkthisrecordtotheclosestTimeUnitlikeintheexampleabove,butyoucouldsumalltherecordsinthesameDayandlinkit
totheDayvertex.Example:
Createanewclasstostoretheaggregateddailyrecords:
CREATECLASSDailyLog
Createthenewrecordfromanaggregationofthehour:
INSERTINTODailyLog
SETwin=(
SELECTSUM(win)ASwinFROMHourWHEREdateBETWEEN'2012-03-2010:00:00'AND'2012-03-2011:00:00'
)
LinkitintheCalendargraphassumingthepreviouscommandreturned#23:45astheRecordIdofthebrandnewDailyLogrecord:
84
TimeSeries
UPDATE(
SELECTexpand(month[3].day[20])FROMYearWHEREyear="2012"
)ADDlogs=#23:45
85
Chat
ChatUseCase
OrientDBallowsmodelingofrichandcomplexdomains.Ifyouwanttodevelopachatbasedapplication,youcanusewhateveryou
wanttocreatetherelationshipsbetweenUserandRoom.
WesuggestavoidingusingEdgesorVerticesconnectedwithedgesformessages.ThebestwayisusingthedocumentAPIbycreating
oneclassperchatroom,withnoindex,tohavesuperfastaccesstolastXmessages.Infacts,OrientDBstoresnewrecordsinappend
only,andthe@ridisautogeneratedasincrementing.
The2mostcommonusecasesinachatare:
writingamessageinachatroom
loadlastpageofmessagesinachatroom
Createtheinitialschema
Inordertoworkwiththechatrooms,theruleofthethumbiscreatingabaseabstractclass("ChatRoom")andthenlettotheconcrete
classestorepresentindividualChatRooms.
CreatethebaseChatRoomclass
createclassChatRoom
alterclassChatRoomabstracttrue
createpropertyChatRoom.datedatetime
createpropertyChatRoom.textstring
createpropertyChatRoom.userLINKOUser
CreateanewChatRoom
createclassItalianRestaurantextendsChatRoom
Class"ItalianRestaurant"willextendallthepropertiesfromChatRoom.
Whycreatingabaseclass?Becauseyoucouldalwaysexecutepolymorphicqueriesthatarecross-chatrooms,likegetallthemessage
fromuser"Luca":
selectfromChatRoomwhereuser.name='Luca'
CreateanewmessageintheChatRoom
Tocreateanewmessageinthechatroomyoucanusethiscode:
publicODocumentaddMessage(StringchatRoom,Stringmessage,OUseruser){
ODocumentmsg=newODocument(chatRoom);
msg.field("date",newDate());
msg.field("text",message);
msg.field("user",user);
msg.save();
returnmsg;
}
Example:
addMessage("ItalianRestaurant","HaveyoueverbeenatPonzaisland?",database.getUser());
86
Chat
Retrievelastmessages
Youcaneasilyfetchpagesofmessagesorderedbydateindescendingorder,byusingtheOrientDB's @rid.Example:
selectfromItalianRestaurantorderby@riddescskip0limit50
Youcouldwriteagenericmethodtoaccesstoapageofmessages,likethis:
publicIterable<ODocument>loadMessages(StringchatRoom,fromLast,pageSize){
returngraph.getRawGraph().command("selectfrom"+chatRoom+"orderby@riddescskip"+fromLast+"limit"+pageSize
).execute();
}
Loadingthe2nd(last)pagefromchat"ItalianRestaurant",wouldbecomethisquery(withpageSize=50):
selectfromItalianRestaurantorderby@riddescskip50limit50
ThisissuperfastandO(1)evenwithmillionofmessages.
Limitations
SinceOrientDBcanhandleonly32kclusters,youcouldhavemaximum32kchatrooms.Unlessyouwanttorewritetheentire
FreeNode,32kchatroomswillbemorethanenoughformostofthecases.
However,ifyouneedmorethan32kchatrooms,thesuggestedsolutionisstillusingthisapproach,butwithmultipledatabases(even
onthesameserver,becauseoneOrientDBServerinstancecanhandlethousandsofdatabasesconcurrently).
Inthiscaseyoucoulduseonedatabasetohandleallthemetadata,likethefollowingclasses:
ChatRoom,containingallthechatrooms,andthedatabasewherearestored.Example: {"@class":"ChatRoom","description":
"OrientDBpublicchannel","databaseName","db1","clusterName":"orientdb"}
User,containingalltheinformationaboutaccountswiththeedgestotheChatRoomverticeswheretheyaresubscribed
OrientDBcannothandlecross-databaselinks,sowhenyouwanttoknowthemessage'sauthor,youhavetolookupintothe
"M etadata"databaseby@RID(thatisO(1)).
87
KeyValue
KeyValueUseCase
OrientDBcanalsobeusedasaKeyValueDBM SbyusingthesuperfastIndexes.YoucanhaveasmanyIndexesasyouneed.
HTTP
OrientDBRESTfulHTTPprotocolallowstotalkwithaOrientDBServerinstanceusingtheHTTPprotocolandJSON.OrientDB
supportsalsoahighlyoptimizedBinaryprotocolforsuperiorperformances.
Operations
TointeractagainstOrientDBindexesusethefourmethodsoftheHTTPprotocolinRESTfashion:
PUT,tocreateormodifyanentryinthedatabase
GET,toretrieveanentryfromthedatabase.It'sidempotentthatmeansnochangestothedatabasehappen.RememberthatinIE6
theURLcanbemaximumof2,083characters.OtherbrowserssupportslongerURLs,butifyouwanttostaycompatiblewithall
limitto2,083characters
DELETE,todeleteanentryfromthedatabase
Createanentry
TocreateanewentryinthedatabaseusetheIndex-PUTAPI.
Syntax: http://<server>:[<port>]/index/<index-name>/<key>
Example:
HTTPPUT: http://localhost:2480/index/customers/jay
{
"name":"Jay",
"surname":"Miner"
}
HTTPResponse204isreturned.
Retrieveanentry
ToretrieveanentryfromthedatabaseusetheIndex-GETAPI.
Syntax: http://<server>:[<port>]/index/<index-name>/<key>
Example:
HTTPGET: http://localhost:2480/index/customers/jay
HTTPResponse200isreturnedwiththisJSONaspayload:
{
"name":"Jay",
"surname":"Miner"
}
Removeanentry
88
KeyValue
ToremoveanentryfromthedatabaseusetheIndex-DELETEAPI.
Syntax: http://<server>:[<port>]/index/<index-name>/<key>
Example:
HTTPDELETE: http://localhost:2480/index/customers/jay
HTTPResponse200isreturned
Step-by-Steptutorial
Beforetostartassureyou'veaOrientDBserverupandrunning.Inthisexamplewe'llusecurlconsideringtheconnectiontolocalhostto
thedefaultHTTPpost2480.Thedefault"admin"userisused.
Createanewindex
TouseOrientDBasaKey/Valuestoreweneedabrandnewmanualindex,let'scallit"mainbucket".We'regoingtocreateitasUNIQUE
becausekeyscannotbeduplicated.Ifyoucanhavemultiplekeysconsider:
creatingtheindexasNOTUNIQUE
leaveitasUNIQUEbutasvaluehandlearrayofdocuments
Createthenewmanualuniqueindex"mainbucket":
>curl--basic-uadmin:adminlocalhost:2480/command/demo/sql-d"createindexmainbucketUNIQUE"
Response:
{"result":[
{"@type":"d","@version":0,"value":0,"@fieldTypes":"value=l"}
]
}
Storethefirstentry
Belowwe'regoingtoinsertthefirstentrybyusingtheHTTPPUTmethodpassing"jay"askeyintheURLandasvaluetheentire
documentinformofJSON:
>curl--basic-uadmin:admin-XPUTlocalhost:2480/index/demo/mainbucket/jay-d"{'name':'Jay','surname':'Miner'}"
Response:
Key'jay'correctlyinsertedintotheindexmainbucket.
Retrievetheentryjustinserted
Belowwe'regoingtoretrievetheentrywejustenteredbyusingtheHTTPGETmethodpassing"jay"askeyintheURL:
>curl--basic-uadmin:adminlocalhost:2480/index/demo/mainbucket/jay
Response:
89
KeyValue
[{
"@type":"d","@rid":"#3:477","@version":0,
"name":"Jay",
"surname":"Miner"
}]
Notethatanarrayisalwaysreturnedincasemultiplerecordsareassociatedtothesamekey(ifNOTUNIQUEindexisused).Lookalso
atthedocumenthasbeencreatedwithRID#3:477.YoucanloaditdirectlyifyouknowtheRID.Remembertoremovethe#character.
Example:
>curl--basic-uadmin:adminlocalhost:2480/document/demo/3:477
Response:
{
"@type":"d","@rid":"#3:477","@version":0,
"name":"Jay",
"surname":"Miner"
}
Dropanindex
Oncefinisheddroptheindex"mainbucket"createdfortheexample:
>curl--basic-uadmin:adminlocalhost:2480/command/demo/sql-d"dropindexmainbucket"
Response:
{"result":[
{"@type":"d","@version":0,"value":0,"@fieldTypes":"value=l"}
]
}
90
Queuesystem
Distributedqueuesusecase
Implementingapersistent,distributedandtransactionalqueuesystemusingOrientDBispossibleandeasy.Besidesthefactyoudon't
needaspecificAPIaccomplishaqueue,therearemultipleapproachesyoucanfollowdependingbyyourneeds.Theeasiestwayis
usingOrientDBSQL,sothisworkswitanydriver.
Createthequeueclassfirst:
createclassqueue
Youcouldhaveoneclassperqueue.Exampleofpushoperation:
insertintoqueuesettext="thisisthefirstmessage",date=date()
SinceOrientDBbydefaultkeepstheorderofcreationofrecords,asimpledeletefromthequeueclasswithlimit=1givestoyouthe
perfectpop:
deletefromqueuereturnbeforelimit1
The"returnbefore"allowsyoutohavethedeletedrecordcontent.Ifyouneedtopeekthequeue,youcanjustusetheselect:
selectfromqueuelimit1
That'sit.Yourqueuewillbepersistent,ifyouwanttransactionalandrunninginclusterdistributed.
91
Administration
Administration
OrientDBhasanumberoftoolstomakeadministrationofthedatabaseeasier.Thereistheconsole,whichallowsyoutorunalarge
numberofcommands.
ThereisalsotheOrientDBStudio,whichallowsyoutorunqueriesandvisuallylookatthegraph.
OrientDBalsooffersseveraltoolsfortheimportandexportofdata,loggingandtroubleshooting,alongwithETLtools.
AllofOrientDB'sadministrationfacilitiesareaimedtomakeyourusageofOrientDBassimpleandaseasyaspossible.
Formoreinformationsee:
CommandReference
BackupandRestore
ExportandImport
Logging
Studio
Troubleshooting
PerformanceTuning
ETLTools
92
ConsoleCommandReference
ConsoleTool
OrientDBprovidesaConsoleTool,whichisaJavaapplicationthatconnectstoandoperatesonOrientDBdatabasesandServer
instances.
ConsoleModes
Therearetwomodesavailabletoyou,whileexecutingcommandsthroughtheOrientDBConsole:interactivemodeandbatchmode.
InteractiveMode
Bydefault,theConsolestartsininteractivemode.Inthismode,theConsoleloadstoan orientdb>prompt.Fromthereyoucan
executecommandsandSQLstatementsasyoumightexpectinanyotherdatabaseconsole.
Youcanlaunchtheconsoleininteractivemodebyexecutingthe console.shforLinuxOSsystemsor console.batforWindows
systemsinthe bindirectoryofyourOrientDBinstallation.Notethatrunningthisfilerequiresexecutionpermissions.
$cd$ORIENTDB_HOME/bin
$./console.sh
OrientDBconsolev.X.X.X(build0)www.orientdb.com
Type'HELP'todisplayallthecommandssupported.
InstallingextensionsforGREMLINlanguagev.X.X.X
orientdb>
Fromhere,youcanbeginrunningSQLstatementsorcommands.Foralistofthesecommands,seecommands.
Batchmode
WhentheConsolerunsinbatchmode,ittakescommandsasargumentsonthecommand-lineorasatextfileandexecutesthecommands
inthatfileinorder.Usethesame console.shor console.batfilefoundin binattheOrientDBinstallationdirectory.
Command-line:Toexecutecommandsinbatchmodefromthecommandline,passthecommandsyouwanttoruninastring,
separatedbyasemicolon.
$$ORIENTDB_HOME/bin/console.sh"CONNECTREMOTE:localhost/demo;SELECTFROMProfile"
S criptCommands:Inadditiontoenteringthecommandsasastringonthecommand-line,youcanalsosavethecommandstoa
textfileasasemicolon-separatedlist.
$vimcommands.txt
CONNECTREMOTE:localhost/demo;SELECTFROMProfile
$$ORIENTDB_HOME/bin/console.shcommands.txt
IgnoringErrors
Whenrunningcommandsinbatchmode,youcantelltheconsoletoignoreerrors,allowingthescripttocontinuetheexecution,withthe
ignoreErrorssetting.
93
ConsoleCommandReference
$vimcommands.txt
SETignoreErrorsTRUE
EnablingEcho
Regardlessofwhetheryoucallthecommandsasanargumentorthroughafile,whenyourunconsolecommandsinbatchmode,you
mayalsoneedtodisplaythemastheyexecute.Youcanenablethisfeatureusingthe echosetting,nearthestartofyourcommands
list.
$vimcommands.txt
SETechoTRUE
Consolecommands
OrientDBimplementsanumberofSQLstatementsandcommandsthatareavailablethroughtheConsole.Intheeventthatyouneed
informationwhileworkingintheconsole,youcanaccessitusingeitherthe HELPor ?command.
Command
Description
ALTERCLASS
Changestheclassschema
ALTERCLUSTER
Changestheclusterattributes
ALTERDATABASE
Changesthedatabaseattributes
ALTERPROPERTY
Changestheclass'spropertyschema
BACKUPDATABASE
Backupadatabase
BEGIN
Beginsanewtransaction
BROWSECLASS
Browsesalltherecordsofaclass
BROWSECLUSTER
Browsesalltherecordsofacluster
CLASSES
Displaysalltheconfiguredclasses
CLUSTERSTATUS
Displaysthestatusofdistributedclusterofservers
CLUSTERS
Displaysalltheconfiguredclusters
COMMIT
Commitsanactivetransaction
CONFIG
Displaystheconfigurationwheretheopeneddatabaseislocated(localorremote)
CONFIGGET
Returnsaconfigurationvalue
CONFIGSET
Setaconfigurationvalue
CONNECT
Connectstoadatabase
CREATECLASS
Createsanewclass
CREATECLUSTER
Createsanewclusterinsideadatabase
CREATECLUSTER
Createsanewrecordcluster
CREATEDATABASE
Createsanewdatabase
CREATEEDGE
Createanewedgeconnectingtwovertices
CREATEINDEX
Createanewindex
CREATELINK
CreatealinkreadingaRDBM SJOIN
94
ConsoleCommandReference
CREATEVERTEX
Createanewvertex
DECLAREINTENT
Declaresanintent
DELETE
DeletesarecordfromthedatabaseusingtheSQLsyntax.ToknowmoreabouttheSQLsyntaxgohere
DICTIONARYKEYS
Displaysallthekeysinthedatabasedictionary
DICTIONARYGET
Loookupsforarecordusingthedictionary.Iffoundsetitasthecurrentrecord
DICTIONARYPUT
Insertsormodifyanentryinthedatabasedictionary.Theentryiscomposedbykey=String,value=recordid
DICTIONARY
REMOVE
Removestheassociationinthedictionary
DISCONNECT
Disconnectsfromthecurrentdatabase
DISPLAYRECORD
Displayscurrentrecord'sattributes
DISPLAYRAW
RECORD
Displayscurrentrecord'srawformat
DROPCLASS
Dropaclass
DROPCLUSTER
Dropacluster
DROPDATABASE
Dropadatabase
DROPINDEX
Dropanindex
DROPPROPERTY
Dropapropertyfromaschemaclass
EXPLAIN
Explainacommandbydisplayingtheprofilingvalueswhileexecutingit
EXPORTDATABASE
Exportsadatabase
EXPORTRECORD
Exportsarecordinanyofthesupportedformat(i.e.json)
FINDREFERENCES
Findthereferencestoarecord
FREEZEDATABASE
Freezesthedatabaselockingallthechanges.Usethistorawbackup.Oncefrozenitusesthe RELEASE
DATABASEtoreleaseit
GET
Returnsthevalueofaproperty
GRANT
Grantsapermissiontoauser
GREMLIN
ExecutesaGremlinscript
IMPORTDATABASE
Importsadatabasepreviouslyexported
INDEXES
Displaysinformationaboutindexes
INFO
Displaysinformationaboutcurrentstatus
INFOCLASS
Displaysinformationaboutaclass
INSERT
InsertsanewrecordinthecurrentdatabaseusingtheSQLsyntax.ToknowmoreabouttheSQLsyntaxgo
here
JS
ExecutesaJavascriptintheconsole
JSS
ExecutesaJavascriptintheserver
LISTDATABASES
Listtheavailabledatabases
LIST
CONNECTIONS
Listtheavailableconnections
LOADRECORD
Loadsarecordinmemoryandsetitasthecurrentone
PROFILER
ControlstheProfiler
PROPERTIES
Returnsalltheconfiguredproperties
pwd
Displaycurrentpath
REBUILDINDEX
Rebuildanindex
95
ConsoleCommandReference
RELEASE
DATABASE
ReleasesaConsoleFreezeDatabasedatabase
RELOADRECORD
Reloadsarecordinmemoryandsetitasthecurrentone
RELOADSCHEMA
Reloadstheschema
ROLLBACK
Rollbackstheactivetransactionstartedwithbegin
RESTORE
DATABASE
Restoreadatabase
SELECT
ExecutesaSQLqueryagainstthedatabaseanddisplaytheresults.ToknowmoreabouttheSQLsyntaxgo
here
REVOKE
Revokesapermissiontoauser
SET
Changesthevalueofaproperty
SLEEP
Sleepforthetimespecified.Usefulonscripts
TRAVERSE
Traverseagraphofrecords
TRUNCATECLASS
Removealltherecordsofaclass(bytruncatingalltheunderlyingconfiguredclusters)
TRUNCATE
CLUSTER
Removealltherecordsofacluster
TRUNCATERECORD
Truncatearecordyoucan'tdeletebecauseit'scorrupted
UPDATE
UpdatesarecordinthecurrentdatabaseusingtheSQLsyntax.ToknowmoreabouttheSQLsyntaxgo
here
HELP
Printsthishelp
EXIT
Closestheconsole
CustomCommands
InadditiontothecommandsimplementedbyOrientDB,youcanalsodevelopcustomcommandstoextendfeaturesinyourparticular
implementation.Todothis,edittheOConsoleDatabaseAppclassandaddtoitanewmethod.There'sanauto-discoverysystemin
placethataddsthenewmethodtotheavailablecommands.Toprovideadescriptionofthecommand,useannotations.Thecommand
namemustfollowtheJavacodeconventionofseparatingwordsusingcamel-case.
Forinstance,consideracaseinwhichyoumightwanttoadda MOVECLUSTERcommandtotheconsole:
@ConsoleCommand(description="Movethephysicallocationofclusterfiles")
publicvoidmoveCluster(
@ConsoleParameter(name="cluster-name",description="Thenameortheidoftheclustertoremove")StringiClusterName,
@ConsoleParameter(name="target-path",description="pathofthenewpositionwheretomovetheclusterfiles")StringiN
ewPath){
checkCurrentDatabase();//THEDBMUSTBEOPENED
System.out.println("Movingcluster'"+iClusterName+"'topath"+iNewPath+"...");
}
Onceyouhavethiscodeinplace, MOVECLUSTERnowappearsinthelistingofavailablecommandsshownby HELP.
96
ConsoleCommandReference
orientdb>HELP
AVAILABLECOMMANDS:
AVAILABLECOMMANDS:
*alterclassAlteraclassinthedatabaseschema
*alterclusterAlterclassinthedatabaseschema
......
*moveclusterMovethephysicallocationofclusterfiles
......
*helpPrintthishelp
*exitClosetheconsole
orientdb> MOVECLUSTERfoo/temp
Movingcluster'foo'topath/tmp...
Intheeventthatyoudevelopacustomcommandandfinditespeciallyusefulinyourdeployment,youcancontributeyourcodetothe
OrientDBCommunity!
97
Backup
Console- BACKUP
Executesacompletebackuponthecurrentlyopeneddatabase.ItthencompressesthebackupfileusingtheZIPalgorithm.Youcanthen
restoreadatabasefrombackups,usingthe RESTOREDATABASEcommand.YoucanautomatebackupsusingtheAutomatic-Backupserver
plugin.
Backupsandrestoresaresimilartothe EXPORTDATABASEand IMPORTDATABASE,buttheyofferbetterperformancethantheseoptions.
NOTE:OrientDBCommunityEditiondoesnotsupportbackingupremotedatabases.OrientDBEnterpriseEditiondoes
supportthisfeature.FormoreinformationonhowtoimplementthiswithEnterpriseEdition,seeRemoteBackups.
S yntax:
BACKUPDATABASE<output-file>[-incremental][-compressionLevel=<compressionLevel>][-bufferSize=<bufferSize>]
<output-file>Definesthepathtothebackupfile.
-incrementalOptiontoexecuteanincrementalbackup.Whenenabled,itcomputesthedatatobackupasallnewchangessince
thelastbackup.AvailableinOrientDBEnterpriseEditionversion2.2orlater.
- compressionLevelDefinesthelevelofcompressionforthebackupfile.Validlevelsare 0to 9.Thedefaultis 9.Availablein
1.7orlater.
-bufferSizeDefinesthecompressionbuffersize.Bydefault,thisissetto1M B.Availablein1.7orlater.
Example:
Backingupadatabase:
orientdb>CONNECTplocal:../databases/mydatabaseadminadmin
orientdb>BACKUPDATABASE/backups/mydb.zip
Backingcurrentdatabaseto:databasemydb.zip
Backupexecutedin0.52seconds
BackupAPI
InadditiontobackupscalledthroughtheConsole,youcanalsomanagebackupsthroughtheJavaAPI.Usingthis,youcanperform
eitherafullorincrementalbackuponyourdatabase.
FullBackup
InJavaoranyotherlanguagethatrunsontopoftheJVM ,youcaninitiateafullbackupbyusingthe backup()methodonadatabase
instance.
db.backup(out,options,callable,listener,compressionLevel,bufferSize);
outReferstothe OutputStreamthatitusestowritethebackupcontent.Usea FileOutputStreamtomakethebackup
persistentondisk.
optionsDefinesbackupoptionsasa Map<String,Object>object.
callableDefinesthecallbacktoexecutewhenthedatabaseislocked.
listenerDefinesthelistenedcalledforbackupmessages.
compressionLevelDefinesthelevelofcompressionforthebackup.Itsupportslevelsbetween 0and 9,where 0equalsno
compressionand 9themaximum.Highercompressionlevelsdomeansmallerfiles,buttheyalsomeanthebackuprequiresmore
fromtheCPUatexecutiontime.
bufferSizeDefinesthebuffersizeinbytes.Thelargerthebuffer,themoreefficientthecomrpession.
Example:
98
Backup
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/temp/mydb");
db.open("admin","admin");
try{
OCommandOutputListenerlistener=newOCommandOutputListener(){
@Override
publicvoidonMessage(StringiText){
System.out.print(iText);
}
};
OutputStreamout=newFileOutputStream("/temp/mydb.zip");
db.backup(out,null,null,listener,9,2048);
}finally{
db.close();
}
IncrementalBackup
Asofversion2.2,OrientDBEnterpriseEditionsupportsincrementalbackupsexecutedthroughJavaoranylanguagethatrunsontopof
theJVM ,usingthe incrementalBackup()methodagainstadatabaseinstance.
db.incrementalBackup(backupDirectory);
backupDirectoryDefinesthedirectorywhereitgeneratestheincrementalbackupfiles.
Itisimportantthatpreviousincrementalbackupfilesarepresentinthesamedirectory,inordertocomputethedatabaseportiontoback
up,basedonthelastincrementalbackup.
Example:
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/temp/mydb");
db.open("admin","admin");
try{
db.backup("/var/backup/orientdb/mydb");
}finally{
db.close();
}
Formoreinformation,see:
RestoreDatabase
ExportDatabase
ImportDatabase
Console-Commands
ODatabaseExportJavaclass
99
Begin
Console- BEGIN
Initiatesatransaction.Whenatransactionisopen,anycommandsyouexecuteonthedatabaseremaintemporary.Intheeventthatyou
aresatisfiedwiththechanges,youcancallthe COMMITcommandtocommitthemtothedatabase.Otherwise,youcancallthe
ROLLBACKcommand,torollthechangesbacktothepointwhereyoucalled BEGIN.
S yntax:
BEGIN
Examples
Beginatransaction:
orientdb>BEGIN
Transaction1isrunning
Attemptingtobeginatransactionwhenoneisalreadyopen:
orinetdb>BEGIN
Error:anactivetransactioniscurrentlyopen(id=1).Commitorrollback
beforestartinganewone.
M akingchangeswhenatransactionisopen:
orientdb>INSERTINTOAccount(name)VALUES('txtest')SELECTFROMAccountWHEREnameLIKE'tx%'
---+-------+---------#|RID|name
---+-------+---------0|#9:-2|txtest
---+-------+---------
Whenatransactionisopen,newrecordsallhavetemporaryRecordID's,whicharegivennegativevalues,(forinstance,likethe #9:-2
shownabove).Theseremainineffectuntilyourun COMMIT
FormoreinformationonTransactions,see
Transactions
ConsoleCommandCOM M IT
ConsoleCommandROLLBACK
ConsoleCommands
100
BrowseClass
Console- BROWSECLASS
Displaysallrecordsassociatedwiththegivenclass.
S yntax:
BROWSECLASS<class-name>
<class-name>Definestheclassfortherecordsyouwanttodisplay.
Example:
Browserecordsassociatedwiththeclass City:
orientdb>BROWSECLASSCity
----+------+------------------#|RID|NAME
----+------+------------------0|-6:0|Rome
1|-6:1|London
2|-6:2|Honolulu
----+------+-------------------
Formoreinformationonothercommands,seeConsoleCommands.
101
BrowseCluster
Console- BROWSECLUSTER
Displaysallrecordsassociatedwiththegivencluster.
S yntax:
BROWSECLUSTER<cluster-name>
<cluster-name>Definestheclusterfortherecordsyouwanttodisplay.
Example:
Browserecordsassociatedwiththecluster City:
orientdb>BROWSECLUSTERCity
----+------+------------------#|RID|NAME
----+------+------------------0|-6:0|Rome
1|-6:1|London
2|-6:2|Honolulu
----+------+-------------------
Formoreinformationonothercommands,seeConsoleCommands.
102
ListClasses
Console- LISTCLASSES
Displaysallconfiguredclassesinthecurrentdatabase.
S yntax:
LongSyntax:
LISTCLASSES
ShortSyntax:
CLASSES
Example
Listcurrentclassesinthedatabase:
orientdb>LISTCLASSES
CLASSES
-------------+------+-------------+----------NAME|ID|CLUSTERS|ELEMENTS
-------------+------+-------------+----------Person|0|person|7
Animal|1|animal|5
AnimalRace|2|AnimalRace|0
AnimalType|3|AnimalType|1
OrderItem|4|OrderItem|0
Order|5|Order|0
City|6|City|3
-------------+------+-------------+----------TOTAL16
-----------------------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
103
ClusterStatus
Console- CLUSTERSTATUS
Displaysthestatusoftheclusterindistributedconfiguration.
S yntax:
CLUSTERSTATUS
Example:
Displaythestatusofthecluster:
orientdb>CLUSTERSTATUS
{
"localName":"_hzInstance_1_orientdb",
"localId":"3735e690-9a7b-44d2-b4bc-27089da065e2",
"members":[
{
"id":"3735e690-9a7b-44d2-b4bc-27089da065e2",
"name":"node1",
"startedOn":"2015-05-1417:06:40:418",
"listeners":[
{
"protocol":"ONetworkProtocolBinary",
"listen":"10.3.15.55:2424"
},
{
"protocol":"ONetworkProtocolHttpDb",
"listen":"10.3.15.55:2480"
}
],
"databases":[]
}
]
}
Formoreinformationonothercommands,seeConsoleCommands.
104
ListClusters
Console- LISTCLUSTERS
Displaysallconfiguredclustersinthecurrentdatabase.
S yntax:
LongSyntax:
LISTCLUSTERS
ShortSyntax:
CLUSTERS
Example:
Listcurrentclustersondatabase:
orientdb>LISTCLUSTERS
CLUSTERS
-------------+------+-----------+----------NAME|ID|TYPE|ELEMENTS
-------------+------+-----------+----------metadata|0|Physical|11
index|1|Physical|0
default|2|Physical|779
csv|3|Physical|1000
binary|4|Physical|1001
person|5|Physical|7
animal|6|Physical|5
animalrace|-2|Logical|0
animaltype|-3|Logical|1
orderitem|-4|Logical|0
order|-5|Logical|0
city|-6|Logical|3
-------------+------+-----------+----------TOTAL2807
--------------------------------------------
Forinformationoncreatingnewclustersinthecurrentdatabase,seethe CREATECLUSTERcommand.Formoreinformationon
othercommands,seeConsoleCommands.
105
ListServers
Console- LISTSERVERS
Displaysallactiveserversconnectedwithinacluster.
ThiscommandwasintroducedinOrientDBversion2.2.
S yntax:
LISTSERVERS
Example:
Listtheserverscurrentlyconnectedtothecluster:
orientdb>LISTSERVERS
CONFIGUREDSERVERS
-+----+------+-----------+-------------+-----------+-----------+-----------+---------+--------#|Name|Status|Connections|StartedOn|Binary|HTTP|UsedMemory
|FreeMemory|MaxMemory
-+----+------+-----------+-------------+-----------+-----------+-----------+---------+--------0|no2|ONLINE|0|2015-1030...|192.168.0.6|192.168.0.6|80MB(8.80%)|215MB(23%)|910MB
1|no1|ONLINE|0|2015-10-30...|192.168.0.6|192.168.0.6|90MB(2.49%)|195MB(5%)
|3.5GB
-+----+------+-----------+-------------+-----------+-----------+-----------+---------+---------
Usethe DISPLAYcommandtoshowinformationonaspecificserver:
orientdb>DISPLAY0
-------------+-----------------------------Name|Value
-------------+-----------------------------Name|node2
Status|ONLINE
Connections|0
StartedOn|FriOct3021:41:07CDT2015
Binary|192.168.0.6:2425
HTTP|192.168.0.6:2481
UsedMemory|80,16MB(8,80%)
FreeMemory|215,34MB(23,65%)
MaxMemory|910,50MB
-------------+------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
106
ListServerUsers
Console-LISTSERVERUSERS
ThisfeaturewasintroducedinOrientDBversion2.2.
Displaysallconfiguredusersontheserver.Inordertodisplaytheusers,thecurrentsystemuserthatisrunningtheconsolemusthave
permissionstoreadthe $ORINETDB_HOME/config/orientdb-server-config.xmlconfigurationfile.Formoreinformation,seeOrientDB
ServerSecurity.
S yntax:
LISTSERVERUSERS
Example:
Listconfiguredusersonaserver:
orientdb>LISTSERVERUSERS
SERVERUSERS
-'root',permissions:*
-'guest',permissions:connect,server.listDatabases,server.dblist
Formoreinformation,see
SETSERVERUSER
DROPSERVERUSER
Formoreinformationonotherconsolecommands,seeConsoleCommands.
107
Commit
Console-COMMIT
Closesatransaction,committingthechangesyouhavemadetothedatabase.Usethe BEGINcommandtoopenatransaction.Ifyou
don'twanttosavethechangesyou'vemade,usethe ROLLBACKcommandtorevertthedatabasestatebacktothepointwhereyou
openedthetransaction.
Formoreinformation,seeTransactions.
S yntax
COMMIT
Example
Initiateatransaction,usingthe BEGINcommand:
orientdb>BEGIN
Transaction2isrunning
Forthesakeofexample,attempttoopenanothertransaction:
orientdb>BEGIN
Error:anactivetransactioniscurrentlyopen(id=2).Commitorrollback
beforestartinganewone.
Insertdataintotheclass Account,usingan INSERTstatement:
orientdb>INSERTINTOAccount(name)VALUES('txtest')
Insertedrecord'Account#9:-2{name:txtest}v0'in0,000000sec(s).
Committhetransactiontothedatabase:
orientdb>COMMIT
Transaction2hasbeencommittedin4ms
Displaythenewcontent,usinga SELECTquery:
orientdb>SELECTFROMAccountWHEREnameLIKE'tx%'
---+---------+---------#|RID|name
---+---------+---------0|#9:1107|txtest
---+---------+---------1item(s)found.Queryexecutedin0.041sec(s).
Whenatransactionisopen,allnewrecordsuseatemporaryRecordIDthatfeaturesnegativenumbers.Afterthecommit,theyhavea
permanentRecordIDthatuseswithpositivenumbers.
108
Commit
Formoreinformation,see
Transactions
BEGIN
ROLLBACK
ConsoleCommands
109
Config
Console- CONFIG
Displaystheconfigurationinformationonthecurrentdatabase,aswellaswhetheritislocalorremote.
S yntax
CONFIG
Examples
Displaytheconfigurationofthecurrentdatabase:
orientdb>CONFIG
REMOTESERVERCONFIGURATION:
+------------------------------------+--------------------------------+
|NAME|VALUE|
+------------------------------------+--------------------------------+
|treemap.lazyUpdates|300|
|db.cache.enabled|false|
|file.mmap.forceRetry|5|
|treemap.optimizeEntryPointsFactor|1.0|
|storage.keepOpen|true|
|treemap.loadFactor|0.7|
|file.mmap.maxMemory|110000000|
|network.http.maxLength|10000|
|storage.cache.size|5000|
|treemap.nodePageSize|1024|
|...|...|
|treemap.entryPoints|30|
+------------------------------------+--------------------------------+
Youcanchangeconfigurationvariablesdisplayedhereusingthe CONFIGSETcommand.Todisplaythevaluesettoone
configurationvariable,usethe CONFIGGETcommand.
Formoreinformationonothercommands,seeConsoleCommands.
110
ConfigGet
Console- CONFIGGET
Displaysthevalueoftherequestedconfigurationvariable.
S yntax
CONFIGGET<config-variable>
<config-variable>Definestheconfigurationvariableyouwanttoquery.
Examples
Displaythevaluetothe tx.log.fileTypeconfigurationvariable:
orientdb>CONFIGGETtx.log.fileType
Remoteconfiguration:tx.log.fileType=classic
Youcandisplayallconfigurationvariablesusingthe CONFIGcommand.Tochangethevalues,usethe CONFIGSETcommand.
Formoreinformationonothercommands,seeConfigCommands.
111
ConfigSet
Console- CONFIGSET
Updatesaconfigurationvariabletothegivenvalue.
S yntax
CONFIGSET<config-variable><config-value>
<config-variable>Definestheconfigurationvariableyouwanttochange.
<config-value>Definesthevalueyouwanttoset.
Example
Displaythecurrentvaluefor tx.autoRetry:
orientdb>CONFIGGETtx.autoRetry
Remoteconfiguration:tx.autoRetry=1
Changethe tx.autoRetryvalueto 5:
orientdb>CONFIGSETtx.autoRetry5
Remoteconfigurationvaluechangedcorrectly.
Displaynewvalue:
orientdb>CONFIGGETtx.autoRetry
Remoteconfiguration:tx.autoRetry=5
Youcandisplayallconfigurationvariableswiththe CONFIGcommand.Youcanviewthecurrentvalueonaconfigurationvariable
usingthe CONFIGGETcommand.
Formoreinformationonothercommands,seeConsoleCommands
112
Connect
Console- CONNECT
Opensadatabase.
S yntax
CONNECT<database-url><user><password>
<database-url>DefinestheURLofthedatabaseyouwanttoconnectto.Itusestheformat <mode>:<path>
<mode>Definesthemodeyouwanttouseinconnectingtothedatabase.Itcanbe PLOCALor REMOTE.
<path>Definesthepathtothedatabase.
<user>Definestheuseryouwanttoconnecttothedatabasewith.
<password>Definesthepasswordneededtoconnecttothedatabase,withthedefineduser.
Examples:
Connecttoalocaldatabaseastheuser admin,loadingitdirectlyintotheconsole:
orientdb>CONNECTPLOCAL:../databases/GratefulDeadConcertsadminmy_admin_password
Connectingtodatabase[plocal:../databases/GratefulDeadConcerts]...OK
Connecttoaremotedatabase:
orientdb>CONNECTREMOTE:192.168.1.1/GratefulDeadConcertsadminmy_admin_password
Connectingtodatabase[remote:192.168.1.1/GratefulDeadConcerts]...OK
Formoreinformationonothercommands,seeConsoleCommands.
113
CreateCluster
Console- CREATECLUSTER
Createsanewclusterinthecurrentdatabase.Theclusteryoucreatecaneitherbephysicalorinmemory.OrientDBsavesphysical
clusterstodisk.M emoryclustersarevolatile,soanyrecordsyousavetothemarelost,shouldtheserverbestopped.
S yntax
CREATECLUSTER<cluster-name><cluster-type><data-segment><location>[<position>]
<cluster-name>Definesthenameofthecluster.
<cluster-type>Defineswhethertheclusteris PHYSICALor LOGICAL.
<data-segment>Definesthedatasegmentyouwanttouse.
DEFAULTSetstheclustertothedefaultdatasegment.
<location>Definesthelocationfornewclusterfiles,ifapplicable.Use DEFAULTtosavethesetothedatabasedirectory.
<position>Defineswheretoaddnewcluster.Use APPENDtocreateitasthelastcluster.Leaveemptytoreplace.
Example
Createanewcluster documents:
orientdb>CREATECLUSTERdocumentsPHYSICALDEFAULTDEFAULTAPPEND
Creatingcluster[documents]oftype'PHYSICAL'indatabasedemoaslastone...
PHYSICALclustercreatedcorrectlywithid#68
Youcandisplayallconfiguredclustersinthecurrentdatabaseusingthe CLUSTERScommand.Todeleteanexistingcluster,use
the DROPCLUSTERcommand.
Formoreinformationonothercommands,seeConsoleCommands
114
CreateDatabase
Console- CREATEDATABASE
Createsandconnectstoanewdatabase.
S yntax
CREATEDATABASE<database-url>[<user><password><storage-type>[<db-type>]]
<database-url>DefinestheURLofthedatabaseyouwanttoconnectto.Itusestheformat <mode>:<path>
<mode>Definesthemodeyouwanttouseinconnectingtothedatabase.Itcanbe PLOCALor REMOTE.
<path>Definesthepathtothedatabase.
<user>Definestheuseryouwanttoconnecttothedatabasewith.
<password>Definesthepasswordneededtoconnecttothedatabase,withthedefineduser.
<storage-type>Definesthestoragetypethatyouwanttouse.Youcanchoosebetween PLOCALand MEMORY.
<db-type>Definesthedatabasetype.Youcanchoosebetween GRAPHand DOCUMENT.Thedefaultis GRAPH.
Examples
Createalocaldatabase demo:
orientdb>CREATEDATABASEPLOCAL:/usr/local/orientdb/databases/demo
Creatingdatabase[plocal:/usr/local/orientdb/databases/demo]...
Connectingtodatabase[plocal:/usr/local/orientdb/databases/demo]...OK
Databasecreatedsuccessfully.
Currentdatabaseis:plocal:/usr/local/orientdb/databases/demo
orientdb{db=demo}>
Createaremotedatabase trick:
orientdb>CREATEDATABASEREMOTE:192.168.1.1/trickroot
E30DD873203AAA245952278B4306D94E423CF91D569881B7CAD7D0B6D1A20CE9PLOCAL
Creatingdatabase[remote:192.168.1.1/trick]...
Connectingtodatabase[remote:192.168.1.1/trick]...OK
Databasecreatedsuccessfully.
Currentdatabaseis:remote:192.168.1.1/trick
orientdb{db=trick}>
Tocreateastaticdatabasetousefromtheserver,see Serverpre-configuredstoragetypes.
Toremoveadatabase,see DROPDATABASE.Tochangedatabaseconfigurationsaftercreation,see ALTERDATABASE.
Formoreinformationonothercommands,seeConsoleCommands.
115
CreateIndex
Console- CREATEINDEX
Createanindexonagivenproperty.OrientDBsupportsthreeindexalgorithmsandseveralindextypesthatusethesealgorithms.
S B-TreeAlgorithm
UNIQUEDoesnotallowduplicatekeys,failswhenitencountersduplicates.
NOTUNIQUEDoesallowduplicatekeys.
FULLTEXTIndexestoanysinglewordoftext.
DICTIONARYDoesnotallowduplicatekeys,overwriteswhenitencountersduplicates.
HashIndexAlgorithm
UNIQUE_HASH_INDEXDoesnotallowduplicatekeys,itfailswhenitencountersduplicates.
NOTUNIQUE_HASH_INDEXDoesallowduplicatekeys.
FULLTEXT_HASH_INDEXIndexestoanysingleword.
DICTIONARYDoesnotallowduplicatekeys,itoverwriteswhenitencountersduplicates.
LuceneEngine
LUCENEFulltextindextypeusingtheLuceneEngine.
SPATIALSpatialindexusingtheLuceneEngine.
Formoreinformationonindexing,seeIndexes.
S yntax
CREATEINDEX<index-name>[ON<class-name>(<property-names>)]<index-type>[<key-type>]
<index-name>Definesalogicalnamefortheindex.Optionally,youcanusetheformat <class-name>.<property-name>,tocreate
anautomaticindexboundtotheschemaproperty.
NOTEBecauseofthisfeature,indexnamescannotcontainperiods.
<class-name>Definestheclasstoindex.Theclassmustalreadyexistinthedatabaseschema.
<property-names>Definesacomma-separatedlistofpropertiesthatyouwanttoindex.Thesepropertiesmustalreadyexistinthe
databaseschema.
<index-type>Definestheindextypethatyouwanttouse.
<key-type>Definesthekeythatyouwanttouse.Onautomaticindexes,thisisauto-determinedbyreadingthetargetschema
propertywhereyoucreatetheindex.Whennotspecifiedformanualindexes,OrientDBdeterminesthetypeatrun-timeduringthe
firstinsertionbyreadingthetypeoftheclass.
Examples
CreateanindexthatusesuniquevaluesandtheSB-Treeindexalgorithm:
orientdb>CREATEINDEXjobs.job_idUNIQUE
TheSQL CREATEINDEXpageprovidesmoreinformationoncreatingindexes.M oreinformationonindexingcanbefoundunder
Indexes.FurtherSQLinformationcanbefoundunder SQLCommands.
Formoreinformationonothercommands,seeConsoleCommands
116
CreateLink
Console- CREATELINK
CreatesalinkbetweentwoormorerecordsoftheDocumenttype.
S yntax
CREATELINK<link-name>FROM<source-class>.<source-property>TO<target-class>.<target-property>
<link-name>Definesthelogicalnameofthepropertyforthelink.Whennotexpressed,itoverwritesthe <target-property>
field.
<source-class>Definesthesourceclassforthelink.
<source-property>Definesthesourcepropertyforthelink.
<target-class>Definesthetargetclassforthelink.
<target-property>Definesthetargetpropertyforthelink.
Examples
Createa1-nlinkconnectingcommentstoposts:
orientdb>CREATELINKcommentsFROMComments.!PostIdTOPosts.IdINVERSE
UnderstandingLinks
LinksareusefulwhenimportingdatafromaRelationaldatabase.IntheRelationalworld,thedatabaseresolvesrelationshipsasforeign
keys.Forinstance,considertheaboveexamplewhereyouneedtoshowinstancesintheclass Postashavinga1-nrelationshipto
instancesinclass Comment.Thatis, Post1--->*Comment.
InaRelationaldatabase,whereclassesaretables,youmighthavesomethinglikethis:
reldb>SELECT*FROMPost;
+----+----------------+
|Id|Title|
+----+----------------+
|10|NoSQLmovement|
|20|NewOrientDB|
+----+----------------+
2rowsin(0.01sec)
reldb>SELECT*FROMComment;
+----+--------+--------------+
|Id|PostId|Text|
+----+--------+--------------+
|0|10|First|
|1|10|Second|
|21|10|Another|
|41|20|Firstagain|
|82|20|SecondAgain|
+----+--------+--------------+
5rowsinsec(0.03sec)
InOrientDB,youhaveadirectrelationshipinyourobjectmodel.Navigationrunsfrom Postto Commentandnotviceversa,(asin
theRelationaldatabasemodel).Forthisreason,youneedtocreatealinkas INVERSE.
117
CreateLink
FormoreinformationonSQLcommands,seeSQLCommands.
Formoreinformationonothercommands,seeConsoleCommands.
118
CreateProperty
Console- CREATEPROPERTY
Createsanewpropertyonthegivenclass.Theclassmustalreadyexist.
S yntax
CREATEPROPERTY<class-name>.<property-name><property-type>[<linked-type>][<linked-class>]
<class-name>Definestheclassyouwanttocreatethepropertyin.
<property-name>Definesthelogicalnameoftheproperty.
<property-type>Definesthetypeofpropertyyouwanttocreate.Severaloptionsareavailable:
<linked-type>Definesthecontainertype,usedincontainerpropertytypes.
<linked-class>Definesthecontainerclass,usedincontainerpropertytypes.
NOTE:Thereareseveralpropertyandlinktypesavailable.
Examples
Createtheproperty nameontheclass User,ofthestringtype:
orientdb>CREATEPROPERTYUser.nameSTRING
Createalistofstringsastheproperty tagsintheclass Profile,usinganembeddedlistofthestringtype.
orientdb>CREATEPROPERTYProfile.tagsEMBEDDEDLISTSTRING
Createtheembeddedmapproperty friendsintheclass Profile,linkittotheclass Profile.
orientdb>CREATEPROPERTYProfile.friendsEMBEDDEDMAPProfile
Thisformsacircularreference.
Toremoveaproperty,usethe DROPPROPERTYcommand.
PropertyTypes
Whencreatingproperties,youneedtodefinethepropertytype,sothatOrientDBknowsthekindofdatatoexpectinthefield.There
areseveralstandardpropertytypesavailable:
BOOLEAN
INTEGER
SHORT
LONG
FLOAT
DATE
STRING
EMBEDDED
LINK
BYTE
BINARY
DOUBLE
Inadditiontothese,thereareseveralmorepropertytypesthatfunctionascontainers.Theseformlists,setsandmaps.Usingcontainer
propertytypesrequiresthatyoualsodefinealinktypeorclass.
EMBEDDEDLIST
EMBEDDEDSET
EMBEDDEDMAP
LINKLIST
LINKSET
LINKMAP
LinkTypes
Thelinktypesavailablearethesameasthoseavailableasthestandardpropertytypes:
119
CreateProperty
BOOLEAN
INTEGER
SHORT
LONG
FLOAT
DOUBLE
DATE
STRING
BINARY
EMBEDDED
LINK
BYTE
Formoreinformation,seeSQLCommandsandConsoleCommands.
120
DeclareIntent
Console- DECLAREINTENT
Declaresanintentforthecurrentdatabase.Intentsallowyoutotellthedatabasewhatyouwanttodo.
S yntax
DECLAREINTENT<intent-name>
<intent-name>Definesthenameoftheintent.OrientDBsupportsthreeintents:
NULLRemovesthecurrentintent.
MASSIVEINSERT
MASSIVEREAD
Examples
Declareanintentforamassiveinsert:
orientdb>DECLAREINTENTMASSIVEINSERT
Aftertheinsert,cleartheintent:
orientdb>DECLAREINTENTNULL
Formoreinformationonothercommands,seeConsoleCommands.
121
Delete
Console-DELETE
Removeoneormorerecordsfromthedatabase.Youcandeterminewhichrecordsgetdeletedusingthe WHEREclause.
S yntax
DELETEFROM<target-name>[LOCK<lock-type>][RETURN<return-type>]
[WHERE<condition>*][LIMIT<MaxRecords>][TIMEOUT<timeout-value>]
<target-name>Definesthetargetfromwhichyouwanttodeleterecords.Useoneofthefollowingtargetnames:
<class-name>Determineswhatclassyouwanttodeletefrom.
CLUSTER:<cluster-name>Determineswhatclusteryouwanttodeletefrom.
INDEX:<index-name>Determineswhatindexyouwanttodeletefrom.
LOCK<lock-type>Defineshowtherecordlocksbetweentheloadanddeletion.Ittakesoneoftwotypes:
DEFAULTOperationusesnolocks.Intheeventofconcurrentdeletions,theM VCCthrowsanexception.
RECORDLockstherecordduringthedeletion.
RETURN<return-type>DefineswhattheConsolereturns.Therearetwosupportedreturntypes:
COUNTReturnsthenumberofdeletedrecords.Thisisthedefaultreturntype.
BEFOREReturnstherecordsbeforethedeletion.
WHERE<condition>Definestheconditionusedinselectingrecordsfordeletion.
LIMITDefinesthemaximumnumberofrecordstodelete.
TIMEOUTDefinesthetime-limittoallowtheoperationtorunbeforeittimesout.
NOTE:Whendealingwithverticesandedges,donotusethestandardSQL DELETEcommand.Doingsocandisruptgraph
integrity.Instead,usethe DELETEVERTEXorthe DELETEEDGEcommands.
Examples
Removeallrecordsfromtheclass Profile,wherethesurnameisunknown,ignoringcase:
orientdb>DELETEFROMProfileWHEREsurname.toLowerCase()='unknown'
Formoreinformationonothercommands,seeSQLCommandsandConsoleCommands.
122
DictionaryGet
Console- DICTIONARYGET
Displaysthevalueoftherequestedkey,loadedfromthedatabasedictionary.
S yntax
DICTIONARYGET<key>
<key>Definesthekeyyouwanttoaccess.
Example
InadictionaryofU.S.presidents,displaytheentryforBarackObama:
orientdb>DICTIONARYGETobama
------------------------------------------------------------------------Class:Personid:5:4v.1
------------------------------------------------------------------------parent:null
children:[Person@5:5{parent:Person@5:4,children:null,name:MaliaAnn,
surname:Obama,city:null},Person@5:6{parent:Person@5:4,
children:null,name:Natasha,surname:Obama,city:null}]
name:Barack
surname:Obama
city:City@-6:2{name:Honolulu}
-------------------------------------------------------------------------
Youcandisplayallkeysstoredinadatabaseusingthe DICTIONARYKEYScommand.Formoreinformationonindexes,see
Indexes.
Formoreinformationonothercommands,seeConsoleCommands.
123
DictionaryKeys
Console- DICTIONARYKEYS
Displaysallthekeysstoredinthedatabasedictionary.
S yntax
DICTIONARYKEYS
Example
Displayallthekeysstoredinthedatabasedictionary:
orientdb>DICTIONARYKEYS
Found4keys:
#0:key-148
#1:key-147
#2:key-146
#3:key-145
Toloadtherecordsassociatedwiththesekeys,usethe DICTIONARYGETcommand.Formoreinformationonindexes,see
Indexes.
Formoreinformationonothercommands,seeConsoleCommands.
124
DictionaryPut
Console- DICTIONARYPUT
Bindsarecordtoakeyinthedictionarydatabase,makingitaccessibletothe DICTIONARYGETcommand.
S yntax
DICTIONARYPUT<key><record-id>
<key>Definesthekeyyouwanttobind.
<record-id>DefinestheIDfortherecordyouwanttobindtothekey.
Example
InthedatabasedictionaryofU.S.presidents,bindtherecordforBarackObamatothekey obama:
orientdb>DICTIONARYPUTobama5:4
-----------------------------------------------------------------------Class:Personid:5:4v.1
-----------------------------------------------------------------------parent:null
children:[Person@5:5{parent:Person@5:4,children:null,name:MaliaAnn,
surname:Obama,city:null},Person@5:6{parent:Person@5:4,
children:null,name:Natasha,surname:Obama,city:null}]
name:Barack
surname:Obama
city:City@-6:2{name:Honolulu}
-----------------------------------------------------------------------Theentryobama=5:4hasbeeninsertedinthedatabasedictionary
Toseeallthekeysstoredinthedatabasedictionary,usethe DICTIONARYKEYScommand.Formoreinformationondictionaries
andindexes,seeIndexes.
Formoreinformationonothercommands,seeConsoleCommands.
125
DictionaryRemove
Console- DICTIONARYREMOVE
Removestheassociationfromthedatabasedictionary.
S yntax
DICTIONARYREMOVE<key>
<key>Definesthekeythatyouwanttoremove.
Example
InadatabasedictionaryofU.S.presidents,removethekeyforBarackObama:
orientdb>DICTIONARYREMOVEobama
Entryremovedfromthedictionary.Lastvalueofentrywas:
-----------------------------------------------------------------------Class:Personid:5:4v.1
-----------------------------------------------------------------------parent:null
children:[Person@5:5{parent:Person@5:4,children:null,name:MaliaAnn,
surname:Obama,city:null},Person@5:6{parent:Person@5:4,
children:null,name:Natasha,surname:Obama,city:null}]
name:Barack
surname:Obama
city:City@-6:2{name:Honolulu}
------------------------------------------------------------------------
Youcandisplayinformationforallkeysstoredinthedatabasedictionaryusingthe DICTIONARYKEYcommand.Formore
informationondictionariesandindexes,seeIndexes.
Formoreinformationonothercommands,seeConsoleCommands.
126
Disconnect
Console-DISCONNECT
Closesthecurrentlyopeneddatabase.
S yntax
DISCONNECT
Example
Disconnectfromthecurrentdatabase:
orientdb>DISCONNECT
Disconnectingfromthedatabase[../databases/petshop/petshop]...OK
Toconnecttoadatabase,see CONNECT.Formoreinformationonothercommands,seeConsoleCommands.
127
DisplayRecord
Console-DISPLAYSRECORD
Displaysdetailsonthegivenrecordfromthelastreturnedresult-set.
S yntax
DISPLAYRECORD<record-number>
<record-number>Definestherelativepositionoftherecordinthelastresult-set.
Example
Querythedatabaseontheclass Persontogeneratearesult-set:
orientdb>SELECTFROMPerson
---+-----+--------+----------+-----------+-----------+-----#|RID|PARENT|CHILDREN|NAME|SURNAME|City
---+-----+--------+----------+-----------+-----------+-----0|5:0|null|null|Giuseppe|Garibaldi|-6:0
1|5:1|5:0|null|Napoleon|Bonaparte|-6:0
2|5:2|5:3|null|Nicholas|Churchill|-6:1
3|5:3|5:2|null|Winston|Churchill|-6:1
4|5:4|null|[2]|Barack|Obama|-6:2
5|5:5|5:4|null|MaliaAnn|Obama|null
6|5:6|5:4|null|Natasha|Obama|null
---+-----+--------+----------+-----------+-----------+-----7item(s)found.Queryexecutedin0.038sec(s).
Withtheresult-setready,displayrecordnumberfourintheresult-set,(forM aliaAnnObama):
orientdb>DISPLAYRECORD5
-----------------------------------------------------------------------Class:Personid:5:5v.0
-----------------------------------------------------------------------parent:Person@5:4{parent:null,children:[Person@5:5,Person@5:6],
name:Barack,surname:Obama,city:City@-6:2}
children:null
name:MaliaAnn
surname:Obama
city:null
------------------------------------------------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
128
DisplayRawRecord
Console- DISPLAYSRAWRECORD
Displaysdetailsonthegivenrecordfromthelastreturnedresult-setinabinaryformat.
S yntax
DISPLAYRAWRECORD<record-number>
<record-number>Definestherelativepositionoftherecordinthelastresult-set.
Example
Querythedatabaseontheclass Vtogeneratearesult-set:
orientdb{db=GratefulDeadConcerts}>SELECTsong_type,name,performancesFROMVLIMIT6
-----+-------+--------+----------+-------------------------+-------------#|@RID|@CLASS|song_type|name|performances
-----+-------+--------+----------+-------------------------+-------------0|#9:1|V|cover|HEYBODIDDLEY|5
1|#9:2|V|cover|IMAMAN|1
2|#9:3|V|cover|NOTFADEAWAY|531
3|#9:4|V|original|BERTHA|394
4|#9:5|V|cover|GOINGDOWNTHEROAD...|293
5|#9:6|V|cover|MONA|1
6|#9:7|V|null|Bo_Diddley|null
-----+-------+--------+-----------+------------------------+------------LIMITEXCEEDED:resultsetcontainsmoreitemsnotdisplayed(limit=6)
6item(s)found.Queryexecutedin0.136sec(s).
Displayrawrecordonthesong"HeyBoDiddley"fromtheresult-set:
orientdb{db=GratefulDeadConcerts}>DISPLAYRAWRECORD0
Rawrecordcontent.Thesizeis292bytes,whilesettingsforcetoprintfirst150
bytes:
Vsong_typenametypeperformancesout_followed_byout_written_byout_sung_byin_followed_byco
verHEYBOD
Formoreinformationonothercommandsavailable,seeConsoleCommands.
129
DropCluster
Console- DROPCLUSTER
Removesaclusterfromthedatabasecompletely,deletingitwithallrecordsandcachesinthecluster.
S yntax
DROPCLUSTER<cluster-name>
<cluster-name>Definesthenameoftheclusteryouwanttodrop.
NOTE:Whenyoudropacluster,theclusterandallrecordsandcachesintheclusteraregone.Unlessyouhavemadebackups,
thereisnowaytorestoretheclusterafteryoudropit.
Examples
Dropacluster personfromthecurrent,localdatabase:
orientdb>DROPCLUSTERperson
Thisremovesboththecluster Personandallrecordsofthe Personclassinthatcluster.
Youcancreateanewclusterusingthe CREATECLUSTERcommand.
Forinformationonothercommands,seeSQLandConsolecommands.
130
DropDatabase
Console- DROPDATABASE
Removesadatabasecompletely.Ifthedatabaseisopenandadatabasenamenotgiven,itremovesthecurrentdatabase.
S yntax
DROPDATABASE[<database-name><server-username><server-user-password>]
<database-nameDefinesthedatabaseyouwanttodrop.Bydefaultitusesthecurrentdatabase,ifit'sopen.
<server-username>Definestheserveruser.Thisusermusthavetheprivilegestodropthedatabase.
<server-user-password>Definesthepasswordfortheserveruser.
NOTE:Whenyoudropadatabase,itdeletesthedatabaseandallrecords,cachesandschemainformationitcontains.Unlessyou
havemadebackups,thereisnowaytorestorethedatabaseafteryoudropit.
Examples
Removethecurrentlocaldatabase:
orientdb>DROPDATABASE
Removethedatabase demoatlocalhost:
orientdb>DROPDATABASEREMOTE:localhost/demorootroot_password
Youcancreateanewdatabaseusingthe CREATEDATABASEcommand.Tomakechangestoanexistingdatabase,usethe ALTER
DATABASEcommand.
Formoreinformationonothercommands,seeSQLandConsolecommands.
131
DropServerUser
Console- DROPSERVERUSER
Removesauserfromtheserver.Inordertodoso,thecurrentsystemuserrunningtheConsole,musthavepermissionstowritetothe
$ORIENTDB_HOME/config/orientdb-server-config.xmLconfigurationfile.
S yntax
DROPSERVERUSER<user-name>
<user-name>Definestheuseryouwanttodrop.
NOTE:Formoreinformationonserverusers,seeOrientDBServerSecurity.
Thisfeaturewasintroducedinversion2.2.
Example
Removetheuser editorfromtheServer:
orientdb>DROPSERVERUSEReditor
Serveruser'editor'droppedcorrectly
Toviewthecurrentserverusers,seethe LISTSERVERUSERScommand.Tocreateorupdateaserveruser,seethe SETSERVER
USERcommand.
Formoreinformationonothercommands,seeConsoleCommands.
132
ExportDatabase
Console- EXPORT
Exportsthecurrentdatabasetoafile.OrientDBusesaJSON-basedExportFormat.Bydefault,itcompressesthefileusingtheGZIP
algorithm.
Withthe IMPORTcommand,thisallowsyoutomigratethedatabasebetweendifferentversionsofOrientDBwithoutlosingdata.
Ifyoureceiveanerroraboutthedatabaseversion,exportthedatabaseusingthesameversionofOrientDBthathasgeneratedthe
database.
Bearinmind,exportingadatabasebrowsesit,ratherthanlockingit.Whilethisdoesmeanthatconcurrentoperationscanexecuteduring
theexport,italsomeansthatyoucannotcreateanexactreplicaofthedatabaseatthepointwhenthecommandisissued.Intheevent
thatyouneedtocreateasnapshot,usethe BACKUPcommand.
Youcanrestoreadatabasefromanexportusingthe IMPORT.
NOTE:WhiletheexportformatisJSON,therearesomeconstraintsinthefieldorder.Editingthisfileoradjustingitsindentation
maycauseimportstofail.
S yntax
Bydefault,thiscommandexportsthefulldatabase.Useitsoptionstodisablethepartsyoudon'tneedtoexport.
EXPORTDATABASE<output-file>
[-excludeAll]
[-includeClass=<class-name>*]
[-excludeClass=<class-name>*]
[-includeCluster=<cluster-name>*]
[-excludeCluster=<cluster-name>*]
[-includeInfo=<true|false>]
[-includeClusterDefinitions=<true|false>]
[-includeSchemsa=<true|false>]
[-includeSecurity=<true|false>]
[-includeRecords=<true|false>]
[-includeIndexDefinitions=<true|false>]
[-includeManualIndexes=<true|false>]
[-compressionLevel=<0-9>]
[-compressionBuffer=<bufferSize>]
<output-file>Definesthepathtotheoutputfile.
-excludeAllSetstheexporttoexcludeeverythingnototherwiseincludedthroughcommandoptions
-includeClassExportincludescertainclasses,specificallythosedefinedbyaspace-separatedlist.Incaseyouspecifymultiple
classnames,youhavetowrapthelistbetweenquotes,eg. -includeClass="FooBarBaz"
-excludeClassExportexcludescertainclasses,specificallythosedefinedbyaspace-separatedlist.
-includeClusterExportincludescertainclusters,specificallythosedefinedbyaspace-separatedlist.
-excludeClusterExportexcludescertainclusters,specificallythosedefinedbyaspace-separatedlist.
-includeInfoDefineswhethertheexportincludesdatabaseinformation.
-includeClusterDefinitionsDefineswhethertheexportincludesclusterdefinitions.
-includeSchemaDefineswhethertheexportincludesthedatabaseschema.
-includeSecurityDefineswhethertheexportincludesdatabasesecurityparameters.
-includeRecordsDefineswhethertheexportincludesrecordcontents.
-includeIndexDefinitionsDefineswhethertheexportincludesthedatabaseindexdefinitions.
-includeManualIndexesDefineswhethertheexportincludesmanualindexcontents.
-compressionLevelDefinesthecompressionleveltouseontheexport,inarangebetween 0(nocompression)and 9
(maximumcompression).Thedefaultis 1.(Featureintroducedinversion1.7.6.)
-compressionBufferDefinesthecompressionbuffersizeinbytestouseincompression.Thedefaultis16kb.(Featureintroduced
inversion1.7.6.)
Examples
Exportthecurrentdatabase,includingeverything:
133
ExportDatabase
orientdb>EXPORTDATABASEC:\temp\petshop.export
Exportingcurrentdatabaseto:C:\temp\petshop.export...
Exportingdatabaseinfo...OK
Exportingdictionary...OK
Exportingschema...OK
Exportingclusters...
-Exportingcluster'metadata'(records=11)->...........OK
-Exportingcluster'index'(records=0)->OK
-Exportingcluster'default'(records=779)->OK
-Exportingcluster'csv'(records=1000)->OK
-Exportingcluster'binary'(records=1001)->OK
-Exportingcluster'person'(records=7)->OK
-Exportingcluster'animal'(records=5)->OK
-Exportingcluster'animalrace'(records=0)->OK
-Exportingcluster'animaltype'(records=1)->OK
-Exportingcluster'orderitem'(records=0)->OK
-Exportingcluster'order'(records=0)->OK
-Exportingcluster'city'(records=3)->OK
Exportofdatabasecompleted.
Exportthecurrentdatabase,includingonlyitsfunctions:
orientdb>EXPORTDATABASEfunctions.gz-includeClass=OFunction-includeInfo=FALSE
-includeClusterDefinitions=FALSE-includeSchema=FALSE
-includeIndexDefinitions=FALSE-includeManualIndexes=FALSE
Alternatively,youcansimplifytheabovebyexcludingall,thenincludingonlythosefeaturesthatyouneed.Forinstance,export
thecurrentdatabase,includingonlytheschema:
orientdb>EXPORTDATABASEschema.gz-excludeALL-includeSchema=TRUE
ExportAPI
InadditiontotheConsole,youcanalsotriggerexportsthroughJavaandanyotherlanguagethatrunsontheJVM ,byusingthe
ODatabaseExportclass.
Forexample:
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/temp/mydb");
db.open("admin","admin");
try{
OCommandOutputListenerlistener=newOCommandOutputListener(){
@Override
publicvoidonMessage(StringiText){
System.out.print(iText);
}
};
ODatabaseExportexport=newODatabaseExport(db,"/temp/export",listener);
export.exportDatabase();
export.close();
}finally{
db.close();
}
134
ExportDatabase
Formoreinformationonbackupsandrestores,importsandexports,seethefollowingcommands:
IM PORTDATABASE
BACKUPDATABASE
RESTOREDATABASE
aswellasthefollowingpages:
ExportFileFormat
ODatabaseExportJavaClass
Formoreinformationonothercommands,seeConsoleCommands.
135
ExportRecord
Console- EXPORTRECORD
Exportsthecurrentrecord,usingtherequestedformat.IntheeventthatyougiveaformatthatOrientDBdoesnotsupport,itprovides
alistofsupportedformats.
S yntax
EXPORTRECORD<format>
<format>Definestheexportformatyouwanttouse.
Examples
Use SELECTtocreatearecordforexport:
orientdb>SELECTname,surname,parent,children,cityFROMPersonWHERE
name='Barack'ANDsurname='Obama'
---+-----+--------+---------+--------+------------+-----#|RID|name|surname|parent|children|city
---+-----+--------+---------+--------+------------+-----0|5:4|Barack|Obama|null|[5:5,5:6]|-6:2
---+-----+--------+---------+--------+------------+------
ExportJSONdatafromthisrecord:
orientdb>EXPORTRECORDJSON
{
'name':'Barack',
'surname':'Obama',
'parent':null,
'children':[5:5,5:6],
'city':-6:2
}
Useabadformatvaluetodeterminewhatexportformatsareavailableonyourdatabase:
orientdb>EXPORTRECORDGIBBERISH
ERROR:Format'GIBBERISH'wasnotfound.
Supportedformatsare:
-json
-ORecordDocument2csv
Formoreinformationonothercommands,seeConsoleCommands.
136
FreezeDB
Console- FREEZEDATABASE
Flushesallcachedcontenttodiskandrestrictspermittedoperationstoreadcommands.Withtheexceptionofreads,noneofthe
commandsmadeonafrozendatabaseexecute.Itremainsinthisstateuntilyourunthe RELEASEcommand.
Executingthiscommandrequiresserveradministrationrights.Youcanonlyexecuteitonremotedatabases.Ifyouwouldliketofreezeor
releasealocaldatabase,usethe ODatabase.freeze()and ODatabase.release()methodsdirectlythroughtheOrientDBAPI.
Youmayfindthiscommandusefulintheeventthatyouwouldliketoperformbackupsonalivedatabase.Todoso,freezethe
database,performafilesystemsnapshot,thenreleasethedatabase.Youcannowcopythesnapshotanywhereyouwant.
Thisworksbestwhenthebackupdoesn'ttakeverylongtorun.
S yntax
FREEZEDATABASE
Example
Freezesthecurrentdatabase:
orientdb>FREEZEDATABASE
Tounfreezeadatabase,usethe RELEASEDATABASEcommand.
Formoreinformationonothercommands,seeSQLandConsolecommands.
137
Get
Console- GET
Returnsthevalueoftherequestedproperty.
S yntax
GET<property-name>
<property-name>Definesthenameoftheproperty.
Example
Findthedefaultlimitonyourdatabase:
orientdb>GETLIMIT
limit=20
Todisplayallavailablepropertiesconfiguredonyourdatabase,usethe PROPERTIEScommand.
Formoreinformationonothercommands,seeConsoleCommands.
138
GREM LIN
Console- GREMLIN
ExecutescommandsintheGremlinlanguagefromtheConsole.
Gremlinisagraphtraversallanguage.OrientDBsupportsitfromtheConsole,APIandthroughaGremlinshelllaunchedfrom
$ORIENTDB_HOME/bin/gremlin.sh.
S yntax
GREMLIN<command>
<command>Definesthecommandsyouwanttoknow.
NOTE:OrientDBparsesGremlincommandsasmulti-lineinput.Itdoesnotexecutethecommanduntilyoutype end.Bearin
mind,the endhereiscase-sensitive.
Examples
CreateavertexusingGremlin:
orientdb>GREMLINv1=g.addVertex();
[Startedmulti-linecommand.Typejust'end'tofinishandexecute.]
orientdb>end
v[#9:0]
Scriptexecutedin0,100000sec(s).
FormoreinformationontheGremlinlanguage,seeGremlin.Formoreinformationonothercommands,seeConsoleCommands.
139
ImportDatabase
Console- IMPORT
Importsanexporteddatabaseintothecurrentoneopen.
TheinputfilemustusetheJSONExportFormat,asgeneratedbythe EXPORTcommand.Bydefault,thisfileiscompressedusingthe
GZIPalgorithm.
With EXPORT,thiscommandallowsyoutomigratebetweenreleaseswithoutlosingdata,byexportingdatafromtheoldversionand
importingitintothenewversion.
S yntax
IMPORTDATABASE<input-file>[-preserveClusterIDs=<true|false>]
[-merge=<true|false>]
[-migrateLinks=<true|false>]
[-rebuildIndexes=<true|false>]
<inputy-file>Definesthepathtothefileyouwanttoimport.
-preserveClusterIDsDefineswhetheryouwanttopreserveclusterID'sduringtheimport.Whenturnedoff,theimportcreates
temporaryclusterID's,whichcansometimesfail.ThisoptionisonlyvalidwithPLocalstorage.
-mergeDefineswhetheryouwanttomergetheimportwiththedataalreadyinthecurrentdatabase.Whenturnedoff,thedefault,
theimportoverwritescurrentdata,withtheexceptionofsecurityclasses,( ORole, OUser, OIdentity),whichitalways
preserves.Thisfeaturewasintroducedinversion1.6.1.
-migrateLinksDefineswhetheryouwanttomigratelinksaftertheimport.Whenenabled,thisupdatesallreferencesfromtheold
linkstothenewRecordID's.Bydefault,itisenabled.Advisablethatyouonlyturnitoffwhenmergingandyou'recertainnoother
existentrecordslinktothoseyou'reimporting.Thisfeaturewasintroducedinversion1.6.1.
-rebuildIndexesDefineswhetheryouwanttorebuildindexesaftertheimport.Bydefault,itdoes.Youcansetittofalseto
speeduptheimport,butdosoonlywhenyou'recertaintheimportdoesn'taffectindexes.Thisfeaturewasintroducedinversion
1.6.1.
Example
Importthedatabase petshop.export:
orientdb>IMPORTDATABASEC:/temp/petshop.export-preserveClusterIDs=true
Importingrecords...
-Importedrecordsintothecluster'internal':5records
-Importedrecordsintothecluster'index':4records
-Importedrecordsintothecluster'default':1022records
-Importedrecordsintothecluster'orole':3records
-Importedrecordsintothecluster'ouser':3records
-Importedrecordsintothecluster'csv':100records
-Importedrecordsintothecluster'binary':101records
-Importedrecordsintothecluster'account':1005records
-Importedrecordsintothecluster'company':9records
-Importedrecordsintothecluster'profile':9records
-Importedrecordsintothecluster'whiz':1000records
-Importedrecordsintothecluster'address':164records
-Importedrecordsintothecluster'city':55records
-Importedrecordsintothecluster'country':55records
-Importedrecordsintothecluster'animalrace':3records
-Importedrecordsintothecluster'ographvertex':102records
-Importedrecordsintothecluster'ographedge':101records
-Importedrecordsintothecluster'graphcar':1records
140
ImportDatabase
Formoreinformationonbackups,restores,andexports,see: BACKUP, RESTOREand EXPORTcommands,andthe
ODatabaseImportJavaclass.FortheJSONformat,seeExportFileFormat.
Formoreinformationonothercommands,seeConsoleCommands.
ImportAPI
InadditiontotheConsole,youcanalsomanageimportsthroughtheJavaAPI,andwithanylanguagethatrunsontopoftheJVM ,
usingthe ODatabaseImportclass.
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/temp/mydb");
db.open("admin","admin");
try{
OCommandOutputListenerlistener=newOCommandOutputListener(){
@Override
publicvoidonMessage(StringiText){
System.out.print(iText);
}
};
ODatabaseImportimport=newODatabaseImport(db,"/temp/export/export.json.gz",listener);
import.importDatabase();
import.close();
}finally{
db.close();
}
Troubleshooting
ValidationErrors
Occasionally,youmayencountervalidationerrorsduringimports,usuallyshownasan OValidationExceptionexception.Beginning
withversion2.2,youcandisablevalidationatthedatabase-levelusingthe ALTERDATABASEcommand,toallowtheimporttogo
through.
1. Disablevalidationforthecurrentdatabase:
orientdb>ALTERDATABASEvalidationfalse
2. Importtheexporteddatabase:
orientdb>IMPORTDATABASE/path/to/my_data.export-preserveClusterIDs=TRUE
3. Re-enablevalidation:
orientdb>ALTERDATABASEvalidationtrue
ClusterID's
Duringimportsyoumayoccasionallyencounteranerrorthatreads: Importedcluster'XXX'hasid=6differentfromtheoriginal:5.
TypicallyoccursindatabasesthatwerecreatedinmucholderversionsofOrientDB.Youcancorrectitusingthe DROPCLASSonthe
class ORIDs,thenattemptingtheimportagain.
1. Importthedatabase:
141
ImportDatabase
orientdb>IMPORTDATABASE/path/to/old_data.export
Importingrecords...
-Creatingcluster'company'...Errorondatabaseimporthappenedjustbeforeline
16,column52com.orientechnologies.orient.core.exception.OConfigurationException:
Importedcluster'companyhasid=6differentfromtheoriginal:5at
com.orientechnologies.orient.core.db.tool.ODatabaseImport.importClusters(
ODatabaseImport.java:500)at
com.orientechnologies.orient.core.db.tool.ODatabaseIMport.importDatabase(
ODatabaseImport.java:121)
2. Dropthe ORIDsclass:
orientdb>DROPCLASSORIDs
3. Importthedatabase:
orientdb>IMPORTDATABASE/path/to/old_data.export
Thedatabasenowimportswithouterror.
142
Indexes
Console- INDEXES
Displaysallindexesinthecurrentdatabase.
S yntax
INDEXES
Example
Displayindexesinthecurrentdatabase:
orientdb{db=GratefulDeadConcerts}>INDEXES
INDEXES
--------------+------------+-------+--------+--------NAME|TYPE|CLASS|FIELDS|RECORDS
--------------+------------+-------+--------+--------dictionary|DICTIONARY|||0
Group.Grp_Id|UNIQUE|Group|Grp_Id|1
ORole.name|UNIQUE|ORole|name|3
OUser.name|UNIQUE|OUser|name|4
--------------+------------+----------------+--------TOTAL=48
------------------------------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
143
Info
Console- INFO
Displaysallinformationonthecurrentdatabase.
S yntax
INFO
Example
Displayinformationondatabase petshop:
orientdb{db=petshop}>INFO
Currentdatabase:../databases/petshop/petshop
CLUSTERS:
------------+------+----------+---------NAME|ID|TYPE|ELEMENTS
------------+------+----------+---------metadata|0|Physical|11
index|1|Physical|0
default|2|Physical|779
csv|3|Physical|1000
binary|4|Physical|1001
person|5|Physical|7
animal|6|Physical|5
animalrace|-2|Logical|0
animaltype|-3|Logical|1
orderitem|-4|Logical|0
order|-5|Logical|0
city|-6|Logical|3
------------+------+----------+---------TOTAL2807
----------------------------------------CLASSES:
------------+----+------------+---------NAME|ID|CLUSTERS|ELEMENTS
------------+----+------------+---------Person|0|person|7
Animal|1|animal|5
AnimalRace|2|AnimalRace|0
AnimalType|3|AnimalType|1
OrderItem|4|OrderItem|0
Order|5|Order|0
City|6|City|3
------------+----+------------+---------TOTAL16
-----------------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
144
InfoClass
Console- INFOCLASS
Displaysallinformationongivneclass.
S yntax
INFOCLASS<class-name>
<class-name>Defineswhatclassyouwantinformationon.
Example
Displayinformationonclass Profile
orientdb>INFOCLASSProfile
Defaultcluster......:profile(id=10)
Supportedclusterids:[10]
Properties:
--------+----+----------+-----------+---------+-----------+----------+-----+---NAME|ID|TYPE|LINKTYPE|INDEX|MANDATORY|NOTNULL|MIN|MAX
--------+----+----------+-----------+---------+-----------+----------+-----+---nick|3|STRING|null||false|false|3|30
name|2|STRING|null|NOTUNIQUE|false|false|3|30
surname|1|STRING|null||false|false|3|30
...||...|...|...|...|...|...|...
photo|0|TRANSIENT|null||false|false||
--------+----+----------+-----------+---------+-----------+----------+-----+----
Formoreinformationonothercommands,seeConsoleCommands.
145
InfoProperty
Console- INFOPROPERTY
Displaysallinformationonthegivenproperty.
S yntax
INFOPROPERTY<class-name>.<property-name>
<class-name>Definestheclasstowhichthepropertybelongs.
<property-name>Definesthepropertyyouwantinformationon.
Example
Displayinformationontheproperty nameintheclass OUser:
orientdb>INFOPROPERTYOUser.name
PROPERTY'OUser.name'
Type.................:STRING
Mandatory............:true
Notnull.............:true
Readonly............:false
Defaultvalue........:null
Minimumvalue........:null
Maximumvalue........:null
REGEXP...............:null
Collate..............:{OCaseInsensitiveCollate:name=ci}
Linkedclass.........:null
Linkedtype..........:null
INDEXES(1altogether)
--------------------+-----------NAME|PROPERTIES
--------------------+-----------OUser.name|name
--------------------+------------
Formoreinformationonothercommands,seeConsoleCommands.
146
Insert
Console- INSERT
Insertsanewrecordintothecurrentdatabase.Remember,OrientDBcanworkinschema-lessmode,meaningthatyoucancreateany
fieldonthefly.
S yntax
INSERTINTO<<class-name>|CLUSTER:<cluster-name>>(<field-names>)VALUES(<field-values>)
<class-name>Definestheclassyouwanttocreatetherecordin.
CLUSTER:<cluster-name>Definestheclusteryouwanttocreatetherecordin.
<field-names>Definesthefieldsyouwanttoaddtherecordsto,inacomma-separatedlist.
<field-values>Definesthevaluesyouwanttoinsert,inacomma-separatedlist.
Examples
Insertanewrecordintotheclass Profile,usingthename Jayandsurname Miner:
orientdb>INSERTINTOProfile(name,surname)VALUES('Jay',Miner')
Insertedrecordin0,060000sec(s).
Insertanewrecordintotheclass Employee,whiledefiningarelationship:
orientdb>INSERTINTOEmployee(name,boss)VALUES('Jack',11:99)
Insertanewrecord,addingacollectionofrelationships:
orientdb>INSERTINTOProfile(name,friends)VALUES('Luca',[10:3,10:4])
Formoreinformationonothercommands,seeSQLandConsolecommands.
147
ListDatabases
Console- LISTDATABASES
Displaysalldatabaseshostedonthecurrentserver.NotethatthiscommandrequiresyouconnecttotheOrientDBServer.
S yntax
LISTDATABASES
Example
Connecttotheserver:
orientdb>CONNECTREMOTE:localhostadminadmin_password
Listthedatabaseshostedontheserver:
orientdb{server=remote:localhost/}>LISTDATABASES
Found4databases:
*ESA(plocal)
*Napster(plocal)
*Homeland(plocal)
*GratefulDeadConcerts(plocal)
Formoreinformationonothercommands,seeConsoleCommands.
148
ListConnections
Console- LISTCONNECTIONS
DisplaysallactiveconnectionstotheOrientDBServer.Commandintroducedinversion2.2.
S yntax
LISTCONNECTIONS
Example
ListthecurrentconnectionstotheOrientDBServer:
orientdb{server=remote:localhost/}>LISTCONNECTIONS
---+----+--------------+------+-------------------+--------+-----+--------+-------#|ID|REMOTE_ADDRESS|PROTOC|LAST_OPERATION_ON|DATABASE|USER|COMMAND|TOT_REQS
---+----+--------------+------+-------------------+--------+-----+--------+-------0|17|/127.0.0.1|binary|2015-10-1219:22:34|-|-|info|1
1|16|/127.0.0.1|binary|1970-01-0101:00:00|-|-|-|0
5|1|/127.0.0.1|http|1970-01-0100:59:59|pokec|admin|Listen|32
---+----+--------------+------+-------------------+--------+-----+--------+--------
Formoreinformationonothercommands,seeConsoleCommands.
149
LoadRecord
Console- LOADRECORD
LoadsarecordthegivenRecordIDfromthecurrentdatabase.
S yntax
LOADRECORD<record-id>
<record-idDefinestheRecordIDoftherecordyouwanttoload.
Intheeventthatyoudon'thaveaRecordID,executeaquerytofindtheonethatyouwant.
Example
Loadtherecordfor #5:5:
orientdb>LOADRECORD#5:5
-------------------------------------------------------------------------------Class:Personid:#5:5v.0
-------------------------------------------------------------------------------parent:Person@5:4{parent:null,children:[Person@5:5,Person@5:6],name:Barack,
surname:Obama,city:City@-6:2}
children:null
name:MaliaAnn
surname:Obama
city:null
--------------------------------------------------------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
150
Profiler
Console- PROFILER
ControlstheProfiler.
S yntax
PROFILERON|OFF|DUMP|RESET
ONTurnontheProfilerandbeginrecording.
OFFTurnofftheProfilerandstoprecording.
DUMPDumptheProfilerdata.
RESETResettheProfilerdata.
Example
TurntheProfileron:
orientdb>PROFILERON
ProfilerisONnow,use'profileroff'toturnoff.
DumpProfilerdata:
orientdb>PROFILERDUMP
Formoreinformationonothercommands,seeConsoleCommands.
151
Properties
Console- PROPERTIES
Displaysallconfiguredproperties.
S yntax
PROPERTIES
Example
Listconfiguredproperties:
orientdb>PROPERTIES
PROPERTIES:
------------------------+----------NAME|VALUE
------------------------+----------limit|20
backupBufferSize|1048576
backupCompressionLevel|9
collectionMaxItems|10
verbose|2
width|150
maxBinaryDisplay|150
debug|false
ignoreErrors|false
------------------------+-----------
Tochangeapropertyvalue,usethe SETcommand.
Formoreinformationonothercommands,seeConsoleCommands.
152
ReleaseDB
Console- RELEASEDATABASE
Releasesdatabasefromafrozenstate,fromwhereitonlyallowsreadoperationsbacktonormalmode.Executionrequiresserver
administrationrights.
Youmayfindthiscommandusefulintheeventthatyouwanttoperformlivedatabasebackups.Runthe FREEZEDATABASEcommandto
takeasnapshot,youcanthencopythesnapshotanywhereyouwant.Usesuchapproachwhenyouwanttotakeshort-termbackups.
S yntax
RELEASEDATABASE
Example
Releasethecurrentdatabasefromafreeze:
orientdb>RELEASEDATABASE
Tofreezeadatabase,seethe FREEZEDATABASEcommand.
Formoreinformationonothercommands,seeConsoleandSQLcommands.
153
ReloadRecord
Console- RELOADRECORD
ReloadsarecordfromthecurrentdatabasebyitsRecordID,ignoringthecache.
Youmayfindthiscommandusefulincaseswhereexternalapplicationschangetherecordandyouneedtoseethelatestupdate.
S yntax
RELOADRECORD<record-id>
<record-id>DefinestheuniqueRecordIDfortherecordyouwanttoreload.Ifyoudon'thavetheRecordID,executeaquery
first.
Examples
ReloadrecordwiththeIDof 5:5:
orientdb>RELOADRECORD5:5
-----------------------------------------------------------------------Class:Personid:5:5v.0
-----------------------------------------------------------------------parent:Person@5:4{parent:null,children:[Person@5:5,Person@5:6],
name:Barack,surname:Obama,city:City@-6:2}
children:null
name:MaliaAnn
surname:Obama
city:null
------------------------------------------------------------------------
Formoreinformationonothercommands,seeConsoleCommands.
154
Restore
Console- RESTOREDATABASE
Restoresadatabasefromabackup.Itmustbedoneagainstanewdatabase.Itdoesnotsupportrestoresthatmergewithanexisting
database.Ifyouneedtobackupandrestoretoanexistingdatabase,usethe EXPORTDATABASEand IMPORTDATABASEcommands.
OrientDBEnterpriseEditionversion2.2andmajor,supportincrementalbackup.
Tocreateabackupfiletorestorefrom,usethe BACKUPDATABASEcommand.
S yntax
RESTOREDATABASE<backup-file>|<incremental-backup-directory>
<backup-file>Definesthedatabasefileyouwanttorestore.
<incremental-backup-directory>Definesthedatabasedirectoryyouwanttorestorefromanincrementalbackup.Availableonly
inOrientDBEnterpriseEditionversion2.2andmajor.
Exampleoffullrestore
Createanewdatabasetoreceivetherestore:
orientdb>CREATEDATABASEPLOCAL:/tmp/mydb
Restorethedatabasefromthe mydb.zipbackupfile:
orientdb{db=/tmp/mydb}>RESTOREDATABASE/backups/mydb.zip
Exampleofincrementalrestore
ThisisavailableonlyinOrientDBEnterpriseEditionversion2.2andmajor.
Openadatabasetoreceivetherestore:
orientdb>CONNECTPLOCAL:/tmp/mydb
Restorethedatabasefromthe /backupbackupdirectory:
orientdb{db=/tmp/mydb}>RESTOREDATABASE/backup
Formoreinformation,seethe BACKUPDATABASE, EXPORTDATABASE, IMPORTDATABASEcommands.Formoreinformationon
othercommands,seeConsoleCommands.
RestoreAPI
Inadditiontotheconsolecommands,youcanalsoexecuterestoresthroughtheJavaAPIorwithanylanguagethatcanrunontopofthe
JVM usingthe restore()methodagainstthedatabaseinstance.
db.restore(in,options,callable,listener);
inDefinesthe InputStreamusedtoreadthebackupcontent.Usesa FileInputStreamtoreadthebackupcontentfromdisk.
optionsDefinesbackupoptions,suchas Map<String,Object>object.
callableDefinesthecallbacktoexecutewhenthedatabaseislocked.
listenerListenercalledforbackupmessages.
compressionLevelDefinestheZipCompressionlevel,between 0fornocompressionand 9formaximumcompression.The
greaterthecompressionlevel,thesmallerthefinalbackupcontentandthegreatertheCPUandtimeittakestoexecute.
155
Restore
bufferSizeBuffersizeinbytes,thegreaterthebufferthemoreefficientthecompression.
Example
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/temp/mydb");
db.open("admin","admin");
try{
OCommandOutputListenerlistener=newOCommandOutputListener(){
@Override
publicvoidonMessage(StringiText){
System.out.print(iText);
}
};
InputStreamout=newFileInputStream("/temp/mydb.zip");
db.restore(in,null,null,listener);
}finally{
db.close();
}
156
Rollback
Console- ROLLBACK
Abortsatransaction,rollingthedatabasebacktoitssavepoint.
S yntax
BEGIN
Formoreinformationontransactions,seeTransactions.Toinitiateatransaction,usethe BEGINcommand.Tosavechanges,see
COMMITcommand.
Example
Initiateanewtransaction:
orientdb>BEGIN
Transaction1isrunning
Attempttostartanewtransaction,whileanotherisopen:
orientdb>BEGIN
Error:anactivetransactioniscurrentlyopen(id=1).Commitorrollbackbefore
startinganewone.
M akechangestothedatabase:
orientdb>INSERTINTOAccount(name)VALUES('txtest')
Insertedrecord'Account#9:-2{name:txtest}v0'in0,004000sec(s).
Viewchangesindatabase:
orientdb>SELECTFROMAccountWHEREnameLIKE'tx%'
---+-------+-------------------#|RID|name
---+-------+-------------------0|#9:-2|txtest
---+-------+-------------------1item(s)found.Queryexecutedin0.076sec(s).
Abortthetransaction:
orientdb>ROLLBACK
Transaction1hasbeenrollbackedin4ms
Viewrolledbackdatabase:
157
Rollback
orientdb>SELECTFROMAccountWHEREnameLIKE'tx%'
0item(s)found.Queryexecutedin0.037sec(s).
Formoreinformationonothercommands,seeConsoleCommands.
158
Set
Console- SET
Changesthevalueofaproperty.
S yntax
SET<property-name><property-value>
<property-name>Definesthenameoftheproperty
<property-value>Definesthevalueyouwanttochangethepropertyto.
Example
Changethe LIMITpropertytoonehundred:
orientdb>SETLIMIT100
Previousvaluewas:20
limit=100
Todisplayallpropertiesusethe PROPERTIEScommand.Todisplaythevalueofaparticularproperty,usethe GETcommand.
Formoreinformationonothercommands,seeConsoleCommands.
159
SetServerUser
Console- SETSERVERUSER
Createsaserveruser.Iftheserveruseralreadyexists,itupdatesthepasswordandpermissions.
Inordertocreateormodifytheuser,thecurrentsystemusermusthavewritepermissionsonthe $ORIENTDB_HOME/config/orientdbserver-config.xmlconfigurationfile.
S yntax
SETSERVERUSER<user-name><user-password><user-permissions>
<user-name>Definestheserverusername.
<user-password>Definesthepasswordfortheserveruser.
<user-permissions>Definesthepermissionsfortheserveruser.
Formoreinformationonsecurity,seeOrientDBServerSecurity.Featureintroducedinversion2.2.
Example
Createtheserveruser editor,giveitallpermissions:
orientdb>SETSERVERUSEReditormy_password*
Serveruser'editor'setcorrectly
Todisplayallserverusers,seethe LISTSERVERUSERScommand.Toremoveaserveruser,see DROPSERVERUSERcommand.
Formoreinformationonothercommands,seeConsoleCommands.
160
Sleep
Console- SLEEP
Pausestheconsoleforthegivenamountatime.Youmayfindthiscommandusefulinworkingwithbatchesortosimulatelatency.
S yntax
SLEEP<time>
<time>DefinesthetimetheConsoleshouldpauseinmilliseconds.
Example
Pausetheconsoleforthreeseconds:
orientdb{server=remote:localhost/}>SLEEP3000
Formoreinformationonothercommands,seeConsoleCommands.
161
Upgrading
Upgrading
OrientDBusestheSemanticVersioningSystem(http://semver.org),wheretheversionnumbersfollowthisformat
M AJOR.M INOR.PATCH,Herearethemeaningsoftheincrements:
M AJORversionentailsincompatibleAPIchanges,
M INORversionentailsfunctionalityinabackward-compatiblemanner
PATCHversionentailsbackward-compatiblebugfixes.
SobetweenPATCHversions,thecompatibilityisassured(example1.7.0->1.7.8).BetweenM INORandM AJORversions,youmay
needtoexportandre-importthedatabase.Tofindoutifyourupgrademustbedoneoverexportingandimportingthedatabase,see
belowinthecolumn"Database":
CompatibilityMatrix
Blueprints
Database
Binary
Protocol
HTTP
Protocol
Release2.1.x
Final
v2.6.0
Automatic
30
10
2.0.x
M igrationfrom-1.7.xto-2.0.x
Final
v2.6.0
Automatic
25
10
1.6.x
1.7.x
M igrationfrom-1.6.xto-1.7.x
Final
v2.5.0
Automatic
20,21
10
1.5.x
1.6.x
M igrationfrom-1.5.xto-1.6.x
Changed
v2.5.x
Automatic
18,19
10
1.4.x
1.5.x
M igrationfrom-1.4.xto-1.5.x
Changed
v2.4.x
Automatic
16,17
10
1.3.x
1.4.x
M igrationfrom-1.3.xto-1.4.x
Changed
v2.3.x
Automatic
14,15
n.a.
n.a.
Changed
v2.2.x
FROM
TO
Guide
2.0.x
2.1.x
1.7.x
1.2.x
1.3.x
OK
OK
OK
Need
export
&Reimport
12,
13
n.a.
References:
BinaryNetworkProtocol:NetworkBinaryProtocol
HTTPNetworkProtocol:OrientDBREST
MigratefromLOCALstorageenginetoPLOCAL
Startingfromversion1.5.xOrientDBcomeswithabrandnewstorageengine:PLOCAL(PaginatedLOCAL).It'spersistentlikethe
LOCAL,butstoresinformationinadifferentway.BelowarethemaindifferenceswithLOCAL:
recordsarestoredinclusterfiles,whilewithLOCALwassplitbetweenclusteranddata-segments
moredurablethanLOCALbecausetheappend-on-writemode
minorcontentionlocksonwrites:thismeansmoreconcurrency
itdoesn'tuseM emoryM appingtechniques(M M ap)sothebehaviorismore"predictable"
162
Upgrading
TomigrateyourLOCALstoragetothenewPLOCAL,youneedtoexportandreimportthedatabaseusingPLOCALasstorageengine.
Followthestepsbelow:
1)openanewshell(Linux/M ac)oraCommandPrompt(Windows)
2)exportthedatabaseusingtheconsole.Examplebyexportingthedatabaseunder/temp/db:
$bin/console.sh(orbin/console.batunderWindows)
orientdb>CONNECTDATABASElocal:/temp/dbadminadmin
orientdb>EXPORTDATABASE/temp/db.json.gzip
orientdb>DISCONNECT
3)nowalwaysintheconsolecreateanewdatabaseusingthe"plocal"engine:
a)onalocalfilesystem:
orientdb>CREATEDATABASEplocal:/temp/newdbadminadminplocalgraph
b)onaremoteserver(usetheserver'scredentialstoaccess):
orientdb>CREATEDATABASEremote:localhost/newdbrootpasswordplocalgraph
4)nowalwaysintheconsoleimporttheolddatabaseinthenewone:
orientdb>IMPORTDATABASE/temp/db.json.gzip-preserveClusterIDs=true
orientdb>QUIT
5)IfyouaccesstothedatabaseinthesameJVM remembertochangetheURLfrom"local:"to"plocal:"
MigrategraphtoRidBag
AsofOrientDB1.7theRidBagisdefaultcollectionthatmanagesadjacencyrelationsingraphs.Whiletheolderdatabasemanagedbyan
M VRB-Treearefullycompatible,youcanupdateyourdatabasetothemorerecentformat.
YoucanupgradeyourgraphviaconsoleorusingtheORidBagM igrationclass
Usingconsole
Connecttodatabase CONNECTplocal:databases/GratefulDeadConcerts
Run upgradegraphcommand
UsingtheAPI
CreateOGraphM igrationinstance.Passdatabaseconnectiontoconstructor.
Invokemethodexecute()
163
Backwardcompatibility
BackwardCompatibility
OrientDBsupportsbinarycompatibilitybetweenpreviousreleasesandlatestrelease.Binarycompatibilityissupportedatleast
betweenlast2minorversions.
Forexample,letssupposethatwehavefollowingreleases1.5,1.5.1,1.6.1,1.6.2,1.7,1.7.1thenbinarycompatibilityatleastbetween
1.6.1,1.6.2,1.7,1.7.1releaseswillbesupported.
Ifwehavereleases1.5,1.5.1,1.6.1,1.6.2,1.7,1.7.1,2.0thenbinarycompatibilitywillbesupportedatleastbetweenreleases1.7,1.7.1,
2.0.
Binarycompatibilityfeatureisimplementedusingfollowingalgorithm:
1. Whenstorageisopened,versionofbinaryformatwhichisusedwhenstorageiscreatedisreadfromstorageconfiguration.
2. Factoryofobjectsareusedtopresentdiskbaseddatastructuresforcurrentbinaryformatiscreated.
Onlyfeaturesanddatabasecomponentswhichwereexistatthemomentwhencurrentbinaryformatwaslatestonewillbeused.It
meansthatyoucannotusealldatabasefeaturesavailableinlatestreleaseifyouusestoragewhichwascreatedusingoldbinaryformat
version.Italsomeansthatbugswhicharefixedinnewversionsmaybe(butmaybenot)reproducibleonstoragecreatedusingold
binaryformat.
ToupdatebinaryformatstoragetolatestoneyoushouldexportdatabaseinJSONformatandimportitback.Usingeitherconsole
commandsexportdatabaseandimportdatabaseorJavaAPIlookat com.orientechnologies.orient.core.db.tool.ODatabaseImport,
com.orientechnologies.orient.core.db.tool.ODatabaseExportclassesand
com.orientechnologies.orient.test.database.auto.DbImportExportTesttest.
Currentbinaryformatversioncanbereadfrom
com.orientechnologies.orient.core.db.record.OCurrentStorageComponentsFactory#binaryFormatVersionproporty.
Instanceof OCurrentStorageComponentsFactoryclasscanberetrievedbycallof
com.orientechnologies.orient.core.storage.OStorage#getComponentsFactorymethod.
Latestbinaryformatversioncanbereadfromhere
com.orientechnologies.orient.core.config.OStorageConfiguration#CURRENT_BINARY_FORMAT_VERSION.
Pleasenotethatbinarycompatibilityissupportedsince1.7-rc2versionforplocalstorage(asexceptionyoucanreaddatabasecreatedin
1.5.1versionby1.7-rc2version).
ReturntoUpgrade.
164
From2.1.xto2.2.x
Release2.2.x
What'snew?
DirectMemory
Startingfromv2.2,OrientDBusesdirectmemory.Thenewserver.sh(and.bat)alreadysetthemaximumsizevalueto512GBof
memorybysettingtheJVM configuration
-XX:MaxDirectMemorySize=512g
IfyourunOrientDBembeddedorwithadifferentscript,pleaseset MaxDirectMemorySizetoahighvalue,like 512g.
CommandCache
OrientDB2.2hasanewcomponentcalledCommandCache,disabledbydefault,butthatcanmakeahugedifferenceinperformanceon
someusecases.LookatCommandCachetoknowmore.
Sequences
-Inprogress-
Parallelqueries
Startingfromv2.2,theOrientDBSQLexecutorwilldecideifexecuteornotaqueryinparallel.Beforev2.2executingparallelqueries
couldbedoneonlymanuallybyappendingthe PARALLELkeywordattheendofSQLSELECT.Issue4578.
AutomaticusageofMultipleclusters
Startingfromv2.2,whenaclassiscreated,thenumberofunderlyingclusterswillbethenumberofcores.Issue4518.
Encryptionatrest
OrientDBv2.2canencryptdatabaseatfilesystemlevel89.
NewODocument.eval()
ToexecutequickexpressionstartingfromaODocumentandVertex/Edgeobjects,usethenew .eval()method.Theoldsyntax
ODocument.field("city[0].country.name")isnotsupportedanymore.Issue4505.
Migrationfrom2.1.xto2.2.x
Databasescreatedwithrelease2.1.xarecompatiblewith2.2.x,soyoudon'thavetoexport/importthedatabase.
Securityandspeed
OrientDBv2.2increasesecuritybyusingSALT.ThismeansthathashingofpasswordismuchslowerthanOrientDBv2.1.Youcan
configurethenumberofcycleforSALT:moreishardertodecodebutisslower.Changesetting security.userPasswordSaltIterations
tothenumberofcycles.Defaultis65kcycles.Thedefaultpasswordhashingalgorithmisnow PBKDF2WithHmacSHA256thisisnot
presentinanyenvironmentsoyoucanchangeitsetting security.userPasswordDefaultAlgorithmpossiblealternativesvaluesare
PBKDF2WithHmacSHA1or SHA-256
Toimproveperformanceconsideralsoavoidingopeningandclosingconnection,butratherusingaconnectionpool.
165
From2.1.xto2.2.x
APIchanges
ODocument.field()
ToexecutequickexpressionstartingfromaODocumentandVertex/Edgeobjects,usethenew .eval()method.Theoldsyntax
ODocument.field("city[0].country.name")isnotsupportedanymore.Thisisbecausewesimplifiedthe .field()methodtodon't
acceptexpressoionanymore.Thisallowstoboostupperformanceonsuchusedmethod.Issue4505.
Schema.dropClass()
Ondropclassaredroppedalltheclusterownedbytheclass,andnotjustthedefaultcluster.
ConfigurationChanges
Since2.2youcanforcetonotaskforarootpasswordsetting <isAfterFirstTime>true</isAfterFirstTime>insidethe <orient-server>
elementintheorientdb-server-config.xmlfile.
SQLandConsolecommandsChanges
StrictSQLparsingisnowappliedalsotostatementsforS chemaManipulation(CREATECLASS,ALTERCLASS,CREATE
PROPERTY,ALTERPROPERTYetc.)
ALTERDATABAS E:Astatementlike
ALTERDATABASEdateformatyyyy-MM-dd
iscorrectlyexecuted,butisinterpretedintheWRONGway:the yyyy-MM-ddisinterpretedasanexpression(twosubtractions)andnot
asasingledateformat.Pleasere-writeitas(seequotes)
ALTERDATABASEdateformat'yyyy-MM-dd'
CREATEFUNCTION
Insomecasesavariantthesyntaxwithcurlybraceswasaccepted(notdocumented),eg.
CREATEFUNCTIONtestCreateFunction{return'hello'+name;}PARAMETERS[name]IDEMPOTENTtrueLANGUAGEJavascript
Nowit'snotsupportedanymore,therightsyntaxis
CREATEFUNCTIONtestCreateFunction"return'hello'+name;"PARAMETERS[name]IDEMPOTENTtrueLANGUAGEJavascript
ALTERPROPERTY
TheALTERPROPERTYcommand,inpreviousversions,acceptedanyunformattedvalueaslastargument,eg.
ALTERPROPERTYFoo.namemin2015-01-0100:00:00
Inv.2.2thevaluemustbeavalidexpression(eg.astring):
ALTERPROPERTYFoo.namemin"2015-01-0100:00:00"
166
From2.0.xto2.1.x
Release2.1.x
What'snew?
LiveQuery
OrientDB2.1includesthefirstexperimentalversionofLiveQuery.Seedetailshere.
Migrationfrom2.0.xto2.1.x
Databasescreatedwithrelease2.0.xarecompatiblewith2.1,soyoudon'thavetoexport/importthedatabase.
Differencefunction
In2.0.xdifference()functionhadinconsistentbehavior:itactuallyworkedasasymmetricdifference(see4366,3969)In2.1itwas
refactoredtoperformnormaldifference(https://proofwiki.org/wiki/Definition:Set_Difference)andanotherfunctionwascreatedfor
symmetricdifference(called"symmetricDifference()").
Ifforsomereasonyouapplicationreliedonthe(wrong)behaviorofdifference()function,pleasechangeyourqueriestoinvoke
symmetricDifference()instead.
StrictSQLparser
V2.1introducesanewimplementationofthenewSQLparser.Thisimplementationismorestrict,sosomequeriesthatwereallowedin
2.0.xcouldnotworknow.
Forbackwardcompatibility,youcandisablethenewparserfromStudio->DB->Configuration->removetheflagfromstrictSql
(bottomrightofthepage).
Orviaconsolebyexecutingthiscommand,justonce:
ALTERDATABASEcustomstrictSql=false
Importantimprovementsofthenewparserare:
fullsupportfornamed(:param)andunnamed(?)inputparameters:nowyoucanuseinputparametersalmosteverywhereina
query:insubqueries,functionparameters,betweensquarebrackets,asaquerytarget
bettermanagementofblankspacesandnewlinecharacters:theoldparserwasverysensitivetopresenceorabsenceofblankspaces
(especiallyinparticularpoints,eg.beforeandaftersquarebrackets),nowtheproblemiscompletelyfixed
strictvalidation:theoldparserinsomecasesfailedtodetectinvalidqueries(eg.amacroscopicexamplewasaquerywithtwo
WHEREconditions,likeSELECTFORM FooWHEREa=2WHEREa=3),nowalltheseproblemsarecompletelyfixed
Writingthenewparserwasagoodopportunitytovalidateourquerylanguage.Wediscoveredsomeambiguitiesandwehadtoremove
them.Hereisashortlistoftheseproblemsandhowtomanagethemwiththenewparser:
-asavalidcharacterforidentifiers(propertyandclassnames):intheoldimplementationyoucoulddefineapropertynamelike
"simple-name"anddo SELECTsimple-nameFROMFoo.Thisisnotallowedanymore,because -characterisusedforarithmetic
operations(subtract).Tousenameswith -character,usebackticks.Example: SELECT`simple-name`FROMFoo
reservedkeywordsasidentifiers:wordslike select, from, where...couldbeusedaspropertyorclassname,eg.thisquery
wasvalid SELECTFROMFROMFROM.Inv2.1allthereservedkeywordshavetobequotedwithabackticktobeusedasvalid
167
From2.0.xto2.1.x
identifiers: SELECT`FROM`FROM`FROM`
Objectdatabase
Before2.1entityclasscachewasstatic,soyoucouldnotmanagemultipleOObjectDatabaseconnectionsinthesameVM .In2.1
registerEntityClass()worksatstoragelevel,soyoucanopenmultipleOObjectDatabaseconnectionsinthesameVM .
IM PORTANT:in2.1ifyoucloseandre-openthestorage,youhavetore-registeryourPOJOclasses.
Distributedarchitecture
Startingfromrelease2.1.6it'snotpossibletohotupgradeadistributedarchitecturenodebynode,becausetheusageofthelastrecent
versionofHazelcastthatbreakssuchnetworkcompatibility.Ifyou'reupgradingadistributedarchitectureyoushouldpoweroffthe
entireclusterandrestartitwiththenewrelease.
APIchanges
ODatabaseDocumentTx.activateOnCurrentThread()
Ifbyupgadingtov2.1youseeerrorsofkind"Databaseinstanceisnotsetincurrentthread...",thismeansthatyouusedthesame
ODatabaseinstanceacrossmultiplethreads.Thiswasalwaysforbidden,butsomeusersdiditwithunpredictableresultsandrandom
errors.Forthisreasoninv2.1OrientDBalwayschecksthattheODatabaseinstancewasboundtothecurrentthread.
WeintroducedanewAPItoallowmovingaODatabaseinstanceacrossthreads.BeforetouseaODatabaseinstancecallthemethod
ODatabaseDocumentTx.activateOnCurrentThread()andtheODatabaseinstancewillbeboundtothecurrentthread.Example:
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal/temp/mydb").open("admin","admin");
newThread(){
publicvoidrun(){
db.activateOnCurrentThread();//<----BINDSTHEDATABASEONCURRENTTHREAD
db.command(newOCommandSQL("selectfromMyProjectwherethisSummerIsVeryHot=true")).execute();
}
}.start();
168
From1.7.xto2.0.x
Migrationfrom1.7.xto2.0.x
Databasescreatedwithrelease1.7.xarecompatiblewith2.0,soyoudon'thavetoexport/importthedatabaselikeintheprevious
releases.Checkyourdatabasedirectory:ifyouhaveafile*.wal,deleteitbeforemigration.
Usethenewbinaryserialization
Tousethenewbinaryprotocolyouhavetoexportandreimportthedatabaseintoanewone.Thiswillboostupyourdatabase
performanceofabout+20%againstolddatabase.
Toexportandreimportyourdatabasefollowthesesteps:
1)StopanyOrientDBserverrunning
2)Openanewshell(Linux/M ac)oraCommandPrompt(Windows)
2)Exportthedatabaseusingtheconsole.M oveintothedirectorywhereyou'veinstalledOrientDB2.0andexecutethefollowing
commands:
>cdbin
>./console.sh(orbin/console.batunderWindows)
orientdb>CONNECTplocal:/temp/mydbadminadmin
orientdb>EXPORTDATABASE/temp/mydb.json.gz
orientdb>DISCONNECT
orientdb>CREATEDATABASEplocal:/temp/newdb
orientdb>IMPORTDATABASE/temp/mydb.json.gz
Nowyournewdatabaseis:/temp/newdb.
APIchanges
ODocumentpin()andunpin()methods
Weremovedpin()andunpin()methodstoforcethecachebehavior.
ODocumentprotectingofinternalmethods
Wehavehiddensomemethodsconsideredinternaltoavoiduserscallthem.However,ifyourusageofOrientDBisquiteadvancedand
youstillneedthem,youcanaccessfromInternalhelperclasses.Pleasestillconsiderthemasinternalsandcouldchangeinthefuture.
Belowthemainones:
ORecordAbstract.addListener(),usesORecordListenerM anager.addListener()instead
ODatabaseRecord.getStorage()
WemovedgetStorage()methodtoODatabaseRecordInternal.
ODatabaseDocumentPool
WereplacedODatabaseDocumentPoolJavaclass(nowdeprecated)withthenew,moreefficient
com.orientechnologies.orient.core.db.OPartitionedDatabasePool.
Caches
WecompletelyremovedLevel2cache.NowonlyLevel1andStorageDiskCacheareused.Thischangeshouldbetransparentwithcode
thatrunonpreviousversions,unlessyouenable/disableLevel2cacheinyourcode.
169
From1.7.xto2.0.x
Furthermoreit'snotpossibleanymoretodisableCache,somethod setEnable()hasbeenremoved.
Changes
Context
1.7.x
2.0.x
API
ODatabaseRecord.getLevel1Cache()
ODatabaseRecord.getLocalCache()
API
ODatabaseRecord.getLevel2Cache()
Notavailable
Configuration
OGlobalConfiguration.CACHE_LEVEL1_ENABLED
OGlobalConfiguration.CACHE_LOCAL_ENABLED
Configuration
OGlobalConfiguration.CACHE_LEVEL2_ENABLED
Notavailable
NomoreLOCALengine
WecompletelydroppedthelongdeprecatedLOCALStorage.Ifyourdatabasewerecreatedusing"LOCAL:"thenyouhavetoexportit
withtheversionyouwereusing,thenimportitinafreshnewdatabasecreatedwithOrientDB2.0.
Server
Firstrunaskforrootpassword
Atfirstrun,OrientDBasksfortheroot'spassword.Leaveitblanktoautogenerateit(likewith1.7.x).Thisisthemessage:
+----------------------------------------------------+
|WARNING:FIRSTRUNCONFIGURATION|
+----------------------------------------------------+
|Thisisthefirsttimetheserverisrunning.|
|Pleasetypeapasswordofyourchoiceforthe|
|'root'userorleaveitblanktoauto-generateit.|
+----------------------------------------------------+
Rootpassword[BLANK=autogenerateit]:_
Ifyousetthesystemsettingorenvironmentvariable ORIENTDB_ROOT_PASSWORD,thenitsvaluewillbetakenasrootpassword.Ifit's
defined,butempty,apasswordwillbeautomaticallygenerated.
Distributed
Firstrunaskfornodename
Atfirstrunasdistributed,OrientDBasksforthenodename.Leaveitblanktoautogenerateit(likewith1.7.x).Thisisthemessage:
+----------------------------------------------------+
|WARNING:FIRSTDISTRIBUTEDRUNCONFIGURATION|
+----------------------------------------------------+
|Thisisthefirsttimethattheserverisrunning|
|asdistributed.Pleasetypethenameyouwant|
|toassigntothecurrentservernode.|
+----------------------------------------------------+
Nodename[BLANK=autogenerateit]:_
Ifyousetthesystemsettingorenvironmentvariable ORIENTDB_NODE_NAME,thenitsvaluewillbetakenasnodename.Ifit'sdefined,but
empty,anamewillbeautomaticallygenerated.
Multi-Masterreplication
170
From1.7.xto2.0.x
WithOrientDB2.0eachrecordclusterselectsassignsthefirstservernodeinthe serverslistnodeasmasterforinsertiononly.In99%
ofthecasesyouinsertperclass,notpercluster.Whenyouworkperclass,OrientDBauto-selecttheclusterwherethelocalnodeisthe
master.Inthiswaywecompletelyavoidconflicts(likein1.7.x).
Exampleofconfigurationwith2nodesreplicated(nosharding):
INSERTINTOCustomer(name,surname)VALUES('Jay','Miner')
Ifyouexecutethiscommandagainstanode1,OrientDBwillassignthecluster-idwherenode1ismaster,i.e.#13:232.Withnode2would
bedifferent:itcouldn'tneverbe#13.
Formoreinformationlookat:http://www.orientechnologies.com/docs/last/orientdb.wiki/Distributed-Sharding.html.
Asynchronousreplication
OrientDB2.0supportsconfigurableexecutionmodethroughthenewvariable executionMode.Itcanbe:
undefined,thedefault,meanssynchronous
synchronous,toworkinsynchronousmode
asynchronous,toworkinasynchronousmode
{
"autoDeploy":true,
"hotAlignment":false,
"executionMode":"undefined",
"readQuorum":1,
"writeQuorum":2,
"failureAvailableNodesLessQuorum":false,
"readYourWrites":true,
"clusters":{
"internal":{
},
"index":{
},
"*":{
"servers":["<NEW_NODE>"]
}
}
}
Setto"asynchronous"tospeedupthedistributedreplication.
GraphAPI
Multi-threading
StartingfromOrientDB2.0,instancesofbothclassesOrientGraphandOrientGraphNoTxcan'tbesharedacrossthreads.Createand
destroyinstancesfromthesamethread.
Edgecollections
OrientDB2.0disabledtheautoscaleofedge.In1.7.x,ifavertexhad1edgeonly,aLINKwasused.Assoonasanewedgeisaddedthe
LINKisautoscaledtoaLINKSETtohost2edges.Ifyouwantthissettingbackyouhavetocallthesetwomethodsongraphinstance
(orOrientGraphFactorybeforetogetaGraphinstance):
graph.setAutoScaleEdgeType(true);
graph.setEdgeContainerEmbedded2TreeThreshold(40);
171
From1.6.xto1.7.x
Migrationfrom1.6.xto1.7.x
Databasescreatedwithrelease1.6.xarecompatiblewith1.7,soyoudon'thavetoexport/importthedatabaselikeintheprevious
releases.
Engine
OrientDB1.7comeswiththePLOCALengineasdefaultone.Forcompatibilitypurposewestillsupport"local"database,butthiswill
beremovedsoon.Sogetthechancetomigrateyourold"local"databasetothenew"plocal"followthestepsin:M igratefromlocal
storageenginetoplocal.
172
From1.5.xto1.6.x
Migrationfrom1.5.xto1.6.x
Databasescreatedwithrelease1.5.xneedtobeexportedandreimportedinOrientDB1.6.x.
FromOrientDB1.5.x:
Opentheconsoleunder"bin/"directorycalling:
./console.sh(or.batonWindows)
Connecttothedatabaseandexportit,example:
orientdb>connectplocal:/temp/dbadminadmin
orientdb>exportdatabase/temp/db.zip
RunOrientDB1.6.xconsole
./console.sh(or.batonWindows)
Createanewdatabaseandimportit,example:
orientdb>createdatabaseplocal:/temp/dbadminadminplocal
orientdb>importdatabase/temp/db.zip
Foranyproblemonimport,lookatImportTroubleshooting.
Engine
OrientDB1.6.xcomeswiththenewPLOCALengine.Tomigrateadatabasecreatewiththeold"local"tosuchenginefollowthesteps
in:M igratefromlocalstorageenginetoplocal.
173
From1.4.xto1.5.x
Migrationfrom1.4.xto1.5.x
OrientDB1.5.xautomaticupgradesanydatabasescreatedwithversion1.4.x,soexportandimportisnotneeded.
Engine
OrientDB1.5.xcomeswiththenewPLOCALengine.Tomigratetosuchenginefollowthestepsin:M igratefromlocalstorageengineto
plocal.
174
From1.3.xto1.4.x
Migrationfrom1.3.xto1.4.x
GraphDB
OrientDB1.4.xusesanewoptimizedstructuretomanagegraphs.YoucanusethenewOrientDB1.4.xAPIagainstgraphdatabases
createdwithOrientDB1.3.xsettingfewpropertiesatdatabaselevel.Inthiswayyoucancontinuetoworkwithyourdatabasebut
rememberthatthisdoesn'tusethenewstructuresoit'sstronglysuggestedtoexportandimportthedatabase.
ThenewEngineusessomenoveltechniquesbasedontheideaofadynamicGraphthatchangeshapeatrun-timebasedonthesettings
andcontent.ThenewEngineismuchfasterthanbeforeandneedslessspaceinmemoryanddisk.Belowthemainimprovements:
avoidcreationofedgesasdocumentifhaven'tproperties.WithGraphswitnopropertiesonedgesthiscansavemorethan50%of
spaceondiskandthereforememorywithmorechancestohaveabigpartofdatabaseincache.Furthermorethisspeeduptraversal
toobecauserequiresonerecordloadless.Assoonasthefirstpropertyissettheedgeisconvertedtransparently
Vertex"in"and"out"fieldsaren'tdefinedintheschemaanymorebecausecanbeofdifferenttypesandchangeatrun-timeadapting
tothecontent:
noconnection=null(nospacetaken)
1connection=storeasLINK(fewbytes)
1connections=usetheSetofLINKS(usingtheM VRBTreeRIDSetclass)
bindingofBlueprints"label"concepttoOrientDBsub-classes.Ifyoucreateanedgewithlabel"friend",thentheedgesub-type
"friend"willbeused(createdbytheenginetransparently).Thismeans:1fieldlessindocument(thefield"label")andthereforeless
spaceandtheabilitytousethetechnique1(seeabove)
edgesarestoredondifferentfilesatfilesystemlevelbecauseareuseddifferentclusters
betterpartitioningagainstmultipledisks(andinthefuturemoreparallelism)
directquerieslike"selectfromfriend"ratherthan"selectfromE"andthenfilteringtheresult-setlookingfortheedgewiththe
wantedlabelproperty
multiplepropertiesforedgesofdifferentlabels.Notanymorea"in"and"out"inVertexbut"out_friend"tostorealltheoutgoing
edgesofclass"friend".ThismeansfastertraversalofedgesgivingoneormultiplelabelsavoidingtoscantheentireSetofedgesto
findtherightone
Blueprintschanges
IfyouwasusingBlueprintslookalsototheBlueprintschanges1.xand2.x.
Workingwithdatabasecreatedwith1.3.x
Executethesecommandsagainsttheopendatabase:
ALTERDATABASEcustomuseLightweightEdges=false
ALTERDATABASEcustomuseClassForEdgeLabel=false
ALTERDATABASEcustomuseClassForVertexLabel=false
ALTERDATABASEcustomuseVertexFieldsForEdgeLabels=false
BaseclasschangedforGraphelements
Before1.4.xthebaseclassesforVerticeswas"OGraphVertex"withalias"V"andforEdgeswas"OGraphEdge"withalias"E".Starting
fromv1.4thebaseclassforVerticesis"V"and"E"forEdges.Soifinyourcodeyoureferred"V"and"E"forinheritancenothingis
changed(because"V"and"E"wasthealiasesofOGraphVertexand"OGraphEdge"),butifyouuseddirectly"OGraphVertex"and
"OGraphEdge"youneedtoreplacetheminto"V"and"E".
Ifyoudon'texportandimportthedatabaseyoucanrenametheclassesbyhandtypingthesecommands:
175
From1.3.xto1.4.x
ALTERCLASSOGraphVertexshortnamenull
ALTERCLASSOGraphVertexnameV
ALTERCLASSOGraphEdgeshortname=null
ALTERCLASSOGraphEdgenameE
Exportandre-importthedatabase
UseGREM LINandGraphM Lformat.
Ifyou'reexportingthedatabaseusingtheversion1.4.xyou'vetosetfewconfigurationsatdatabaselevel.SeeaboveWorkingwith
databasecreatedwith1.3.x.
Exportthedatabase
$cd$ORIENTDB_HOME/bin
$./gremlin.sh
\,,,/
(oo)
-----oOOo-(_)-oOOo----gremlin>g=newOrientGraph("local:/temp/db");
==>orientgraph[local:/temp/db]
gremlin>g.saveGraphML("/temp/export.xml")
==>null
Importtheexporteddatabase
gremlin>g=newOrientGraph("local:/temp/newdb");
==>orientgraph[local:/temp/newdb]
gremlin>g.loadGraphML("/temp/export.xml");
==>null
gremlin>
Yournewdatabasewillbecreatedunder"/temp/newdb"directory.
GeneralMigration
Ifyouwanttomigratefromrelease1.3.xto1.4.xyou'vetoexportthedatabaseusingthe1.3.xandre-importitusing1.4.x.Example:
Exportthedatabaseusing1.3.x
176
From1.3.xto1.4.x
$cd$ORIENTDB_HOME/bin
$./console.sh
OrientDBconsolev.1.3.0-www.orientechnologies.com
Type'help'todisplayallthecommandssupported.
orientdb>CONNECTlocal:../databases/mydbadminadmin
Connectingtodatabase[local:../databases/mydb]withuser'admin'...
OK
orientdb>EXPORTDATABASE/temp/export.json.gz
Exportingcurrentdatabaseto:database/temp/export.json.gz...
Startedexportofdatabase'mydb'to/temp/export.json.gz...
Exportingdatabaseinfo...OK
Exportingclusters...OK(24clusters)
Exportingschema...OK(23classes)
Exportingrecords...
-Cluster'internal'(id=0)...OK(records=3/3)
-Cluster'index'(id=1)...OK(records=0/0)
-Cluster'manindex'(id=2)...OK(records=1/1)
-Cluster'default'(id=3)...OK(records=0/0)
-Cluster'orole'(id=4)...OK(records=3/3)
-Cluster'ouser'(id=5)...OK(records=3/3)
-Cluster'ofunction'(id=6)...OK(records=1/1)
-Cluster'oschedule'(id=7)...OK(records=0/0)
-Cluster'orids'(id=8).............OK(records=428/428)
-Cluster'v'(id=9).............OK(records=809/809)
-Cluster'e'(id=10)...OK(records=0/0)
-Cluster'followed_by'(id=11).............OK(records=7047/7047)
-Cluster'sung_by'(id=12)...OK(records=2/2)
-Cluster'written_by'(id=13)...OK(records=1/1)
-Cluster'testmodel'(id=14)...OK(records=2/2)
-Cluster'vertexwithmandatoryfields'(id=15)...OK(records=1/1)
-Cluster'artist'(id=16)...OK(records=0/0)
-Cluster'album'(id=17)...OK(records=0/0)
-Cluster'track'(id=18)...OK(records=0/0)
-Cluster'sing'(id=19)...OK(records=0/0)
-Cluster'has'(id=20)...OK(records=0/0)
-Cluster'person'(id=21)...OK(records=2/2)
-Cluster'restaurant'(id=22)...OK(records=1/1)
-Cluster'eat'(id=23)...OK(records=0/0)
Done.Exported8304oftotal8304records
Exportingindexinfo...
-Indexdictionary...OK
OK(1indexes)
Exportingmanualindexescontent...
-Exportingindexdictionary...OK(entries=0)
OK(1manualindexes)
Databaseexportcompletedin1913ms
Re-importtheexporteddatabaseusingOrientDB1.4.x:
177
From1.3.xto1.4.x
$cd$ORIENTDB_HOME/bin
$./console.sh
OrientDBconsolev.1.3.0-www.orientechnologies.com
Type'help'todisplayallthecommandssupported.
orientdb>CREATEDATABASElocal:../databases/newmydbadminadminlocal
Creatingdatabase[local:../databases/newmydb]usingthestoragetype[local]...
Databasecreatedsuccessfully.
Currentdatabaseis:local:../databases/newmydb
orientdb>IMPORTDATABASE/temp/export.json.gz
Importingdatabasedatabase/temp/export.json.gz...
Startedimportofdatabase'local:../databases/newmydb'from/temp/export.json.gz...
Importingdatabaseinfo...OK
Importingclusters...
-Creatingcluster'internal'...OK,assignedid=0
-Creatingcluster'default'...OK,assignedid=3
-Creatingcluster'orole'...OK,assignedid=4
-Creatingcluster'ouser'...OK,assignedid=5
-Creatingcluster'ofunction'...OK,assignedid=6
-Creatingcluster'oschedule'...OK,assignedid=7
-Creatingcluster'orids'...OK,assignedid=8
-Creatingcluster'v'...OK,assignedid=9
-Creatingcluster'e'...OK,assignedid=10
-Creatingcluster'followed_by'...OK,assignedid=11
-Creatingcluster'sung_by'...OK,assignedid=12
-Creatingcluster'written_by'...OK,assignedid=13
-Creatingcluster'testmodel'...OK,assignedid=14
-Creatingcluster'vertexwithmandatoryfields'...OK,assignedid=15
-Creatingcluster'artist'...OK,assignedid=16
-Creatingcluster'album'...OK,assignedid=17
-Creatingcluster'track'...OK,assignedid=18
-Creatingcluster'sing'...OK,assignedid=19
-Creatingcluster'has'...OK,assignedid=20
-Creatingcluster'person'...OK,assignedid=21
-Creatingcluster'restaurant'...OK,assignedid=22
-Creatingcluster'eat'...OK,assignedid=23
Done.Imported22clusters
Importingdatabaseschema...OK(23classes)
Importingrecords...
-Importedrecordsintocluster'internal'(id=0):3records
-Importedrecordsintocluster'orole'(id=4):3records
-Importedrecordsintocluster'ouser'(id=5):3records
-Importedrecordsintocluster'internal'(id=0):1records
-Importedrecordsintocluster'v'(id=9):809records
-Importedrecordsintocluster'followed_by'(id=11):7047records
-Importedrecordsintocluster'sung_by'(id=12):2records
-Importedrecordsintocluster'written_by'(id=13):1records
-Importedrecordsintocluster'testmodel'(id=14):2records
-Importedrecordsintocluster'vertexwithmandatoryfields'(id=15):1records
-Importedrecordsintocluster'person'(id=21):2records
Done.Imported7874records
Importingindexes...
-Index'dictionary'...OK
Done.Created1indexes.
Importingmanualindexentries...
-Index'dictionary'...OK(0entries)
Done.Imported1indexes.
Deletetemporaryrecords...OK(0records)
Databaseimportcompletedin2383ms
orientdb>
Yournewdatabasewillbecreatedunder"../databases/newmydb"directory.
178
BackupandRestore
Backup&Restore
OrientDBsupportsbackandandrestoreoperations,likeanydatabasemanagementsystem.
The BACKUPDATABASEcommandexecutesacompletebackuponthecurrentlyopendatabase.Itcompressesthebackupthebackup
usingtheZIPalgorithm.Torestorethedatabasefromthesubsequent .zipfile,youcanusethe RESTOREDATABASEcommand.
Backupsandrestoresaremuchfasterthanthe EXPORTDATABASEand IMPORTDATABASEcommands.Youcanalsoautomatebackups
usingtheAutomaticBackupserverplugin.Additionally,beginningwithversion2.2ofEnterpriseEditionOrientDBintroducesmajor
supportforincrementalbackups.
BackupsversusExports
Duringbackups,the BACKUPDATABASEcommandproducesaconsistentcopyofthedatabase.Duringthisprocess,thedatabaselocksall
writeoperations,waitingforthebackuptofinish.Ifyouneedperformreadsandwritesonthedatabaseduringbackups,setupa
distributedclusterofnodes.
Bycontrast,the EXPORTDATABASEcommanddoesn'tlockthedatabase,allowingconcurrentwritestooccurduringtheexportprocess.
Consequentially,theexportmayincludechangesmadeafteryouinitiatedtheexport,whichmayresultininconsistencies.
UsingtheBackupScript
Beginninginversion1.7.8,OrientDBintroducesa backup.shscriptfoundinthe $ORIENTDB_HOME/bindirectory.Thisscriptallows
youtoinitiatebackupsfromthesystemconsole.
S yntax
./backup.sh<db-url><user><password><destination>[<type>]
<db-url>DefinestheURLforthedatabasetobackup.
<user>Definestheusertorunthebackup.
<password>Definesthepasswordfortheuser.
<destination>Definesthepathtothebackupfilethescriptcreates,(usethe .zipextension).
<type>Definesthebackuptype.Supportedtypes:
defaultLocksthedatabaseduringthebackup.
lvmExecutesanLVM copy-on-writesnapshotinthebackground.
Examples
Backupadatabaseopenedusing plocal:
$$ORIENTDB_HOME/bin/backup.shplocal:../database/testdb\
adminadminpasswd\
/path/to/backup.zip
Performanon-blockingLVM backup,using plocal:
$$ORIENTDB_HOME/bin/backup.shplocal:../database/testdb\
adminadminpasswd\
/path/to/backup.zip\
lvm
Performanon-blockingLVM backup,usingaremotedatabasehostedat localhost:
179
BackupandRestore
$$ORIENTDB_HOME/bin/backup.shremote:localhost/testdb\
rootrootpasswd\
/path/to/backup.zip\
lvm
PerformabackupusingtheOrientDBConsolewiththe BACKUPcommand:
orientdb>CONNECTPLOCAL:../database/testdb/adminadminpasswd
orientdb>BACKUPDATABASE/path/to/backup.zip
Backupexecutedin0.52seconds.
NOTENon-blockingbackupsrequirethattheoperatingsystemsupportLVM .Formoreinformation,see
LVM
FilesystemsnapshotswithLVM
LVM snapshotbackup
RestoringDatabases
Onceyouhavecreatedyour backup.zipfile,youcanrestoreittothedatabaseeitherthroughtheOrientDBConsole,usingthe
RESTOREDATABASEcommand.
orientdb>RESTOREDATABASE/backups/mydb.zip
Restoreexecutedin6.33seconds
BearinmindthatOrientDBdoesnotsupportmergingduringrestores.Ifyouneedtomergetheolddatawithnewwrites,insteaduse
EXPORTDATABASEand IMPORTDATABASEcommands,instead.
Formoreinformation,see
BACKUPDATABASE
RESTOREDATABASE
EXPORTDATABASE
IMPORTDATABASE
ConsoleCommands
180
ExportandImport
ExportandImport
OrientDBsupportsexportandimportoperations,likeanydatabasemanagementsystem.
The EXPORTDATABASEcommandexportsthecurrentopeneddatabaseintoafile.TheexportedfileisintheExportJSONformat.By
default,itcompressesthefileusingtheGZIPalgorithm.
Usingexportswiththe IMPORTDATABASEcommand,youcanmigratethedatabasebetweendifferentreleasesofOrientDBwithout
losingdata.Whendoingthis,ifyoureceiveanerrorrelatingtothedatabaseversion,exportthedatabaseusingthesameversionof
OrientDBonwhichyoucreatedthedatabase.
orientdb>EXPORTDATABASE/temp/petshop.export
Exportingcurrentdatabaseto:/temp/petshop.export...
Exportingdatabaseinfo...OK
Exportingdictionary...OK
Exportingschema...OK
Exportingclusters...
-Exportingcluster'metadata'(records=11)->...........OK
-Exportingcluster'index'(records=0)->OK
-Exportingcluster'default'(records=779)->OK
-Exportingcluster'csv'(records=1000)->OK
-Exportingcluster'binary'(records=1001)->OK
-Exportingcluster'person'(records=7)->OK
-Exportingcluster'animal'(records=5)->OK
-Exportingcluster'animalrace'(records=0)->OK
-Exportingcluster'animaltype'(records=1)->OK
-Exportingcluster'orderitem'(records=0)->OK
-Exportingcluster'order'(records=0)->OK
-Exportingcluster'city'(records=3)->OK
Exportofdatabasecompleted.
ExportsversusBackups
Exportsdon'tlockthedatabase.Instead,theybrowsethecontents.ThismeansthatOrientDBcanexecuteconcurrentoperationsduring
theexport,buttheexporteddatabasemaynotbeanexactreplicafromthetimewhenyouissuedthecommand.Ifyouneedadatabase
snapshot,usebackups.
The BACKUPDATABASEcommanddoescreateaconsistentcopyofthedatabase,butitlocksthedatabase.Duringthebackup,the
databaseremainsinread-onlymode,allconcurrentwriteoperationsareblockeduntilthebackupfinishes.Intheeventthatyouneeda
databasesnapshotandtheabilitytoperformread/writeoperationsduringthebackup,setupadistributedclusterofnodes.
NOTE:Eventhoughtheexportfileis100%JSON,therearesomeconstraintsintheJSONformat,wherethefieldordermustbe
kept.M odifyingthefiletoadjusttheindentationmaymakethefileunusableindatabaseimports.
ImportingDatabases
Onceyouhaveexportedyourdatabase,youcanimportitusingthe IMPORTDATABASEcommand.
181
ExportandImport
orientdb>IMPORTDATABASE/temp/petshop.export-preserveClusterIDs=true
Importingrecords...
-Importedrecordsintothecluster'internal':5records
-Importedrecordsintothecluster'index':4records
-Importedrecordsintothecluster'default':1022records
-Importedrecordsintothecluster'orole':3records
-Importedrecordsintothecluster'ouser':3records
-Importedrecordsintothecluster'csv':100records
-Importedrecordsintothecluster'binary':101records
-Importedrecordsintothecluster'account':1005records
-Importedrecordsintothecluster'company':9records
-Importedrecordsintothecluster'profile':9records
-Importedrecordsintothecluster'whiz':1000records
-Importedrecordsintothecluster'address':164records
-Importedrecordsintothecluster'city':55records
-Importedrecordsintothecluster'country':55records
-Importedrecordsintothecluster'animalrace':3records
-Importedrecordsintothecluster'ographvertex':102records
-Importedrecordsintothecluster'ographedge':101records
-Importedrecordsintothecluster'graphcar':1records
Formoreinformation,see
JSONExportFormat
RESTOREDATABASE
EXPORTDATABASE
IMPORTDATABASE
ConsoleCommands
182
Exportformat
ExportFormat
Whenyourunthe EXPORTDATABASEcommand,OrientDBexportsthedatabaseintoazippedfileusingaspecialJSONformat.When
yourunthe IMPORTDATABASEcommand,OrientDBunzipsthefileandparsestheJSON,makingtheimport.
Sections
ExportfilesforOrientDBusethefollowingsections.Notethatwhiletheexportformatis100%JSON,therearesomeconstraintsinthe
format,wherethefieldordermustbekept.Additionally,modifyingthefiletoadjusttheindentation(ashasbeendoneintheexamples
below),maymakeitunusableindatabaseimports.
InfoSection
Thefirstsectioncontainstheresumingdatabaseinformationaswellasallversionsusedduringtheexport.OrientDBusesthis
informationtocheckforcompatibilityduringtheimport.
"info":{
"name":"demo",
"default-cluster-id":2,
"exporter-format":2,
"engine-version":"1.7-SNAPSHOT",
"storage-config-version":2,
"schema-version":4,
"mvrbtree-version":0
}
Parameter
Description
JS ONType
"name"
Definesthenameofthedatabase.
String
"default-cluster-id"
DefinestheClusterIDtousebydefault.Range:0-32,762.
Integer
"exporter-format"
Definestheversionofthedatabaseexporter.
Integer
"engine-version"
DefinestheversionofOrientDB.
String
"storage-version"
DefinestheversionoftheStoragelayer.
Integer
"schema-version"
Definestheversionoftheschemaexporter.
Integer
"mvrbtree-version"
DefinestheversionoftheM VRB-Tree.
Integer
ClustersSection
Thissectiondefinesthedatabasestructureinclusters.Itisformedfromalistwithanentryforeachclusterinthedatabase.
"clusters":[
{"name":"internal","id":0,"type":"PHYSICAL"},
{"name":"index","id":1,"type":"PHYSICAL"},
{"name":"default","id":2,"type":"PHYSICAL"}
]
Parameter
Description
JS ONType
"name"
Definesthelogicalnameofthecluster.
String
"id"
DefinestheClusterID.Range:0-32,767.
Integer
"type"
Definestheclustertype: PHYSICAL, LOGICALand MEMORY.
String
SchemaSection
183
Exportformat
Thissectiondefinesthedatabaseschemaasclassesandproperties.
"schema":{
"version":210,
"classes":[
{"name":"Account","default-cluster-id":9,"cluster-ids":[9],
"properties":[
{"name":"binary","type":"BINARY","mandatory":false,"not-null":false},
{"name":"birthDate","type":"DATE","mandatory":false,"not-null":false},
{"name":"id","type":"INTEGER","mandatory":false,"not-null":false}
]
}
]
}
Parameter
Description
JS ONType
"version"
Definestheversionoftherecordstoringtheschema.Range:0-2,147,483,647.
Integer
"classes"
Definesalistofentriesforeachclassintheschema.
Array
ParametersfortheClassesS ubsection:
Parameter
Description
JS ONType
"name"
Definesthelogicalnameoftheclass.
String
"defaultcluster-id"
DefinesthedefaultClusterIDfortheclass.Itrepresentstheclusterthatstoresthe
classrecords.
Integer
"cluster-ids"
DefinesanarrayofClusterID'sthatstoretheclassrecords.ThefirstIDisalwaysthe
defaultClusterID.
Arrayof
Integers
"properties"
Definesalistofentriesforeachpropertyfortheclassintheschema.
Array
ParametersforthePropertiesS ub-subsection:
Parameter
Description
JS ONType
"name"
Definesthelogicalnameoftheproperty.
String
"type"
Definesthepropertytype.
String
"mandatory"
Defineswhetherthepropertyismandatory.
Boolean
"not-null"
Defineswhetherthepropertyacceptsa NULLvalue.
Boolean
RecordsSection
Thissectiondefinestheexportedrecordwithmetadataandfields.Entriesformetadataaredistinguishedfromfieldsbythe @symbol.
"records":[
{"@type":"d","@rid":"#12:476","@version":0,"@class":"Account",
"account_id":476,
"date":"2011-12-0900:00:00:0000",
"@fieldTypes":["account_id=i","date=t"]
},
{"@type":"d","@rid":"#12:477","@version":0,"@class":"Whiz",
"id":477,
"date":"2011-12-0900:00:00:000",
"text":"HeinofficereturnHeinsideelectronicsfor$500,000Jay",
"@fieldTypes":"date=t"
}
]
ParametersforMetadata
184
Exportformat
Parameter
Description
JS ONType
"@type"
Definestherecord-type: dforDocument, bforBinary.
String
"@rid"
DefinestheRecordID,usingtheformat: <cluster-id>:<cluster-position>.
String
"@version"
Definestherecordversion.Range:0-2,147,483,647.
Integer
"@class"
Definesthelogicalclassnamefortherecord.
String
"@fieldTypes"
Definesanarrayofthetypesforeachfieldinthisrecord.
Any
S upportedFieldTypes
Value
Type
l
Long
f
Float
d
Double
s
Short
t
Datetime
d
Date
c
Decimal
b
Byte
FullExample
{
"info":{
"name":"demo",
"default-cluster-id":2,
"exporter-version":2,
"engine-version":"1.0rc8-SNAPSHOT",
"storage-config-version":2,
"schema-version":4,
"mvrbtree-version":0
},
"clusters":[
{"name":"internal","id":0,"type":"PHYSICAL"},
{"name":"index","id":1,"type":"PHYSICAL"},
{"name":"default","id":2,"type":"PHYSICAL"},
{"name":"orole","id":3,"type":"PHYSICAL"},
{"name":"ouser","id":4,"type":"PHYSICAL"},
{"name":"orids","id":5,"type":"PHYSICAL"},
{"name":"csv","id":6,"type":"PHYSICAL"},
{"name":"binary","id":8,"type":"PHYSICAL"},
{"name":"account","id":9,"type":"PHYSICAL"},
{"name":"company","id":10,"type":"PHYSICAL"},
{"name":"profile","id":11,"type":"PHYSICAL"},
{"name":"whiz","id":12,"type":"PHYSICAL"},
{"name":"address","id":13,"type":"PHYSICAL"},
{"name":"city","id":14,"type":"PHYSICAL"},
{"name":"country","id":15,"type":"PHYSICAL"},
{"name":"dummy","id":16,"type":"PHYSICAL"},
{"name":"ographvertex","id":26,"type":"PHYSICAL"},
{"name":"ographedge","id":27,"type":"PHYSICAL"},
{"name":"graphvehicle","id":28,"type":"PHYSICAL"},
{"name":"graphcar","id":29,"type":"PHYSICAL"},
{"name":"graphmotocycle","id":30,"type":"PHYSICAL"},
{"name":"newv","id":31,"type":"PHYSICAL"},
{"name":"mappoint","id":33,"type":"PHYSICAL"},
{"name":"person","id":35,"type":"PHYSICAL"},
{"name":"order","id":36,"type":"PHYSICAL"},
{"name":"post","id":37,"type":"PHYSICAL"},
{"name":"comment","id":38,"type":"PHYSICAL"}
185
Exportformat
],
"schema":{
"version":210,
"classes":[
{"name":"Account","default-cluster-id":9,"cluster-ids":[9],
"properties":[
{"name":"binary","type":"BINARY","mandatory":false,"not-null":false},
{"name":"birthDate","type":"DATE","mandatory":false,"not-null":false},
{"name":"id","type":"INTEGER","mandatory":false,"not-null":false}
]
},
{"name":"Address","default-cluster-id":13,"cluster-ids":[13]
},
{"name":"Animal","default-cluster-id":17,"cluster-ids":[17]
},
{"name":"AnimalRace","default-cluster-id":18,"cluster-ids":[18]
},
{"name":"COMMENT","default-cluster-id":38,"cluster-ids":[38]
},
{"name":"City","default-cluster-id":14,"cluster-ids":[14]
},
{"name":"Company","default-cluster-id":10,"cluster-ids":[10],"super-class":"Account",
"properties":[
]
},
{"name":"Country","default-cluster-id":15,"cluster-ids":[15]
},
{"name":"Dummy","default-cluster-id":16,"cluster-ids":[16]
},
{"name":"GraphCar","default-cluster-id":29,"cluster-ids":[29],"super-class":"GraphVehicle",
"properties":[
]
},
{"name":"GraphMotocycle","default-cluster-id":30,"cluster-ids":[30],"super-class":"GraphVehicle",
"properties":[
]
},
{"name":"GraphVehicle","default-cluster-id":28,"cluster-ids":[28],"super-class":"OGraphVertex",
"properties":[
]
},
{"name":"MapPoint","default-cluster-id":33,"cluster-ids":[33],
"properties":[
{"name":"x","type":"DOUBLE","mandatory":false,"not-null":false},
{"name":"y","type":"DOUBLE","mandatory":false,"not-null":false}
]
},
{"name":"OGraphEdge","default-cluster-id":27,"cluster-ids":[27],"short-name":"E",
"properties":[
{"name":"in","type":"LINK","mandatory":false,"not-null":false,"linked-class":"OGraphVertex"},
{"name":"out","type":"LINK","mandatory":false,"not-null":false,"linked-class":"OGraphVertex"}
]
},
{"name":"OGraphVertex","default-cluster-id":26,"cluster-ids":[26],"short-name":"V",
"properties":[
{"name":"in","type":"LINKSET","mandatory":false,"not-null":false,"linked-class":"OGraphEdge"},
{"name":"out","type":"LINKSET","mandatory":false,"not-null":false,"linked-class":"OGraphEdge"}
]
},
{"name":"ORIDs","default-cluster-id":5,"cluster-ids":[5]
},
{"name":"ORole","default-cluster-id":3,"cluster-ids":[3],
"properties":[
{"name":"mode","type":"BYTE","mandatory":false,"not-null":false},
{"name":"name","type":"STRING","mandatory":true,"not-null":true},
{"name":"rules","type":"EMBEDDEDMAP","mandatory":false,"not-null":false,"linked-type":"BYTE"}
]
},
{"name":"OUser","default-cluster-id":4,"cluster-ids":[4],
"properties":[
{"name":"name","type":"STRING","mandatory":true,"not-null":true},
{"name":"password","type":"STRING","mandatory":true,"not-null":true},
{"name":"roles","type":"LINKSET","mandatory":false,"not-null":false,"linked-class":"ORole"}
]
},
{"name":"Order","default-cluster-id":36,"cluster-ids":[36]
186
Exportformat
},
{"name":"POST","default-cluster-id":37,"cluster-ids":[37],
"properties":[
{"name":"comments","type":"LINKSET","mandatory":false,"not-null":false,"linked-class":"COMMENT"}
]
},
{"name":"Person","default-cluster-id":35,"cluster-ids":[35]
},
{"name":"Person2","default-cluster-id":22,"cluster-ids":[22],
"properties":[
{"name":"age","type":"INTEGER","mandatory":false,"not-null":false},
{"name":"firstName","type":"STRING","mandatory":false,"not-null":false},
{"name":"lastName","type":"STRING","mandatory":false,"not-null":false}
]
},
{"name":"Profile","default-cluster-id":11,"cluster-ids":[11],
"properties":[
{"name":"hash","type":"LONG","mandatory":false,"not-null":false},
{"name":"lastAccessOn","type":"DATETIME","mandatory":false,"not-null":false,"min":"2010-01-0100:00:00"},
{"name":"name","type":"STRING","mandatory":false,"not-null":false,"min":"3","max":"30"},
{"name":"nick","type":"STRING","mandatory":false,"not-null":false,"min":"3","max":"30"},
{"name":"photo","type":"TRANSIENT","mandatory":false,"not-null":false},
{"name":"registeredOn","type":"DATETIME","mandatory":false,"not-null":false,"min":"2010-01-0100:00:00"},
{"name":"surname","type":"STRING","mandatory":false,"not-null":false,"min":"3","max":"30"}
]
},
{"name":"PropertyIndexTestClass","default-cluster-id":21,"cluster-ids":[21],
"properties":[
{"name":"prop1","type":"STRING","mandatory":false,"not-null":false},
{"name":"prop2","type":"INTEGER","mandatory":false,"not-null":false},
{"name":"prop3","type":"BOOLEAN","mandatory":false,"not-null":false},
{"name":"prop4","type":"INTEGER","mandatory":false,"not-null":false},
{"name":"prop5","type":"STRING","mandatory":false,"not-null":false}
]
},
{"name":"SQLDropIndexTestClass","default-cluster-id":23,"cluster-ids":[23],
"properties":[
{"name":"prop1","type":"DOUBLE","mandatory":false,"not-null":false},
{"name":"prop2","type":"INTEGER","mandatory":false,"not-null":false}
]
},
{"name":"SQLSelectCompositeIndexDirectSearchTestClass","default-cluster-id":24,"cluster-ids":[24],
"properties":[
{"name":"prop1","type":"INTEGER","mandatory":false,"not-null":false},
{"name":"prop2","type":"INTEGER","mandatory":false,"not-null":false}
]
},
{"name":"TestClass","default-cluster-id":19,"cluster-ids":[19],
"properties":[
{"name":"name","type":"STRING","mandatory":false,"not-null":false},
{"name":"testLink","type":"LINK","mandatory":false,"not-null":false,"linked-class":"TestLinkClass"}
]
},
{"name":"TestLinkClass","default-cluster-id":20,"cluster-ids":[20],
"properties":[
{"name":"testBoolean","type":"BOOLEAN","mandatory":false,"not-null":false},
{"name":"testString","type":"STRING","mandatory":false,"not-null":false}
]
},
{"name":"Whiz","default-cluster-id":12,"cluster-ids":[12],
"properties":[
{"name":"account","type":"LINK","mandatory":false,"not-null":false,"linked-class":"Account"},
{"name":"date","type":"DATE","mandatory":false,"not-null":false,"min":"2010-01-01"},
{"name":"id","type":"INTEGER","mandatory":false,"not-null":false},
{"name":"replyTo","type":"LINK","mandatory":false,"not-null":false,"linked-class":"Account"},
{"name":"text","type":"STRING","mandatory":true,"not-null":false,"min":"1","max":"140"}
]
},
{"name":"classclassIndexManagerTestClassTwo","default-cluster-id":25,"cluster-ids":[25]
},
{"name":"newV","default-cluster-id":31,"cluster-ids":[31],"super-class":"OGraphVertex",
"properties":[
{"name":"f_int","type":"INTEGER","mandatory":false,"not-null":false}
]
},
{"name":"vertexA","default-cluster-id":32,"cluster-ids":[32],"super-class":"OGraphVertex",
187
Exportformat
"properties":[
{"name":"name","type":"STRING","mandatory":false,"not-null":false}
]
},
{"name":"vertexB","default-cluster-id":34,"cluster-ids":[34],"super-class":"OGraphVertex",
"properties":[
{"name":"map","type":"EMBEDDEDMAP","mandatory":false,"not-null":false},
{"name":"name","type":"STRING","mandatory":false,"not-null":false}
]
}
]
},
"records":[{
"@type":"d","@rid":"#12:476","@version":0,"@class":"Whiz",
"id":476,
"date":"2011-12-0900:00:00:000",
"text":"Losawentchip,ofwasreturningcover,Inthe",
"@fieldTypes":"date=t"
},{
"@type":"d","@rid":"#12:477","@version":0,"@class":"Whiz",
"id":477,
"date":"2011-12-0900:00:00:000",
"text":"HeinofficereturnHeinsideelectronicsfor$500,000Jay",
"@fieldTypes":"date=t"
}
]
}
188
ImportFromRDBM S
ImportfromRDBMS
NOTE:AsofOrientDB2.0,youcanusetheOrientDB-ETLmoduletoimportdatafromanRDBMS.YoucanuseETLalsowith1.7.xby
installingitasaseparatemodule.
OrientDBsupportsasubsetofSQL,soimportingadatabasecreatedas"Relational"isstraightforward.Forthesakeofsimplicity,
consideryourRelationaldatabasehavingjustthesetwotables:
POST
COM M ENT
WheretherelationshipisbetweenPostandcommentasOne-2-M any.
TABLEPOST:
+----+----------------+
|id|title|
+----+----------------+
|10|NoSQLmovement|
|20|NewOrientDB|
+----+----------------+
TABLECOMMENT:
+----+--------+--------------+
|id|postId|text|
+----+--------+--------------+
|0|10|First|
|1|10|Second|
|21|10|Another|
|41|20|Firstagain|
|82|20|SecondAgain|
+----+--------+--------------+
ImportusingtheDocumentM odel(relationshipsaslinks)
ImportusingtheGraphM odel(relationshipsasedges)
189
ImportFromRDBM S
ImportfromaRelationalDatabase
RelationaldatabasestypicallyqueryandmanipulatedatawithSQL.GiventhatOrientDBsupportsasubsetofSQL,itisrelatively
straightfowardtoimportdatafromaRelationaldatabasestoOrientDB.YoucanmanageimportsusingtheJavaAPI,OrientDBStudio
ortheOrientDBConsole.TheexamplesbelowusetheConsole.
ThisguidecoversimportingintotheDocumentM odel.Beginningwithversion2.0,youcanimportintotheGraphM odelusing
theETLM odule.Fromversion1.7.xyoucanstilluseETLbyinstallingitasaseparatemodule
Fortheseexamples,assumethatyourRelationaldatabase,(referredtoas reldbinthecode),containstwotables: Postand
Comment.Therelationshipbetweenthesetablesisone-to-many.
reldb>SELECT*FROMpost;
+----+----------------+
|id|title|
+----+----------------+
|10|NoSQLmovement|
|20|NewOrientDB|
+----+----------------+
reldb>SELECT*FROMcomment;
+----+--------+--------------+
|id|postId|text|
+----+--------+--------------+
|0|10|First|
|1|10|Second|
|21|10|Another|
|41|20|Firstagain|
|82|20|SecondAgain|
+----+--------+--------------+
GiventhattheRelationalM odeldoesn'tuseconceptsfromObjectOrientedProgramming,therearesomethingstoconsiderinthe
transitionfromaRelationaldatabasetoOrientDB.
InRelationaldatabasesthereisnoconceptofclass,sointheimporttoOrientDByouneedtocreateonclasspertable.
InRelationaldatabases,one-to-manyreferencesinvertfromthetargettabletothesourcetable.
TablePOST<-(foreignkey)TableCOMMENT
InOrientDB,itfollowstheObjectOrientedM odel,soyouhaveacollectionoflinksconnectinginstancesof Postand Comment.
ClassPOST->*(collectionoflinks)ClassCOMMENT
ExportingRelationalDatabases
M ostRelationaldatabasemanagementsystemsprovideawaytoexportthedatabaseintoSQLformat.Whatyouspecificallyneedfrom
thisisatextfilethatcontainstheSQL INSERTcommandstorecreatethedatabasefromscratch.Forexample,
M ySQL:the mysqldumputility.
OracleDatabase:theDatapumputilities.
M icrosoftSQLServer:theImportandExportWizard.
190
ImportFromRDBM S
Whenyourunthisutilityontheexampledatabase,itproducesan .sqlfilethatcontainstheexportedSQLoftheRelationaldatabase.
DROPTABLEIFEXISTSpost;
CREATETABLEpost(
idINT(11)NOTNULLAUTO_INCREMENT,
titleVARCHAR(128),
PRIMARYKEY(id)
);
DROPTABLEIFEXISTScomment;
CREATETABLEcomment(
idINT(11)NOTNULLAUTO_INCREMENT,
postIdINT(11),
textTEXT,
PRIMARYKEY(id),
CONSTRAINT`fk_comments`
FOREIGNKEY(`postId`)
REFERENCES`post`(`id`)
);
INSERTINTOPOST(id,title)VALUES(10,'NoSQLmovement');
INSERTINTOPOST(id,title)VALUES(20,'NewOrientDB');
INSERTINTOCOMMENT(id,postId,text)VALUES(0,10,'First');
INSERTINTOCOMMENT(id,postId,text)VALUES(1,10,'Second');
INSERTINTOCOMMENT(id,postId,text)VALUES(21,10,'Another');
INSERTINTOCOMMENT(id,postId,text)VALUES(41,20,'Firstagain');
INSERTINTOCOMMENT(id,postId,text)VALUES(82,20,'SecondAgain');
ModifyingtheExportFile
ImportingfromtheRelationaldatabaserequiresthatyoumodifytheSQLfiletomakeitusablebyOrientDB.Inordertodothis,you
needtoopentheSQLfile,(called export.sqlbelow),inatexteditorandmodifythecommandsthere.Oncethisisdone,youcan
executethefileontheConsoleusingbatchmode.
Database
InordertoimportadataintoOrientDB,youneedtohaveadatabasereadytoreceivetheimport.Notethattheexample export.sql
filedoesn'tincludestatementstocreatethedatabase.Youcaneithercreateanewdatabaseoruseanexistingone.
UsingNewDatabases
Increatingadatabasefortheimport,youcaneithercreateavolatilein-memorydatabase,(onethatisonlyavailablewhileOrientDBis
running),oryoucancreateapersistentdisk-baseddatabase.Forapersistentdatabase,youcancreateitonaremoteserverorlocally
throughthePLocalmode.
TherecommendedmethodisPLocal,giventhatitoffersbetterperformanceonmassiveinserts.
UsingtheembeddedPlocalmode:
$vimexport.sql
CREATEDATABASEPLOCAL:/tmp/db/blogadmin_useradmin_passwdPLOCALDOCUMENT
Here,the CREATEDATABASEcommandcreatesanewdatabaseat /tmp/db/blog.
UsingtheRemotemode:
$vimexport.sql
CREATEDATABASEREMOTE:localhost/blogroot_userdkdf383dhdsjPLOCALDOCUMENT
ThiscreatesadatabaseattheURL http://localhost/blog.
191
ImportFromRDBM S
NOTE:Whenyoucreateremotedatabases,youneedtheservercredentialstoaccessit.Theuser rootanditspasswordare
storedinthe $ORIENTDB_HOME/config/orientdb-server-config.xmlconfigurationfile.
UsingExistingDatabases
Intheeventthatyoualreadyhaveadatabasesetupandreadyfortheimport,insteadofcreatingadatabaseaddalinethatconnectsto
thatdatabases,usingthe CONNECTcommand.
UsingtheembeddedPLocalmode:
$vimexport.sh
CONNECTPLOCAL:/tmp/db/blogadmin_useradmin_passwd
Thisconnectstothedatabaseat /tmp/db/blog.
UsingtheRemotemode:
$vimexport.sql
CONNECTREMOTE:localhost/blogadmin_useradmin_passwd
ThisconnectstothedatabaseattheURL http://localhost/blog.
DeclaringIntent
IntheSQLfile,afteryoucreateorconnecttothedatabase,youneedtodeclareyourintentiontoperformamassiveinsert.Intentsallow
youtoutilizeautomatictuningOrientDBformaximumperformanceonparticularoperations,suchaslargeinsertsorreads.
$vimexport.sh
...
DECLAREINTENTMASSIVEINSERT
CreatingClasses
RelationaldatabaseshavenoparalleltoconceptsinObjectOrientedprogramming,suchasclasses.Conversely,OrientDBdoesn'thavea
conceptoftablesintheRelationalsense.
M odifytheSQLfile,changing CREATETABLEstatementsto CREATECLASScommands:
$vimexport.sql
...
CREATECLASSPost
CREATECLASSComment
NOTE:IncaseswhereyourRelationaldatabasewascreatedusingObjectRelationalM apping,orORM ,tools,suchasHibernate
orDataNucleus,youhavetorebuildtheoriginalObjectOrientedStructuredirectlyinOrientDB.
CreateLinks
IntheRelationaldatabase,therelationshipbetweenthe postand commentwashandledthroughforeignkeysonthe idfields.
OrientDBhandlesrelationshipsdifferently,usinglinksbetweentwoormorerecordsoftheDocumenttype.
Bydefault,the CREATELINKcommandcreatesadirectrelationshipinyourobjectmodel.Navigationgoesfrom Postto Commentand
notviceversa,whichisthecasefortheRelationaldatabase.You'llneedtousethe INVERSEkeywordtomakethelinksworkinboth
directions.
Addthefollowinglineafterthe INSERTstatements.
192
ImportFromRDBM S
$vimexport.sql
...
CREATELINKcommentsTYPELINKSETFROMcomment.postIdTOpost.idINVERSE
RemoveConstraints
UnlikehowRelationaldatabaseshandletables,OrientDBdoesnotrequireyoutocreateastrictschemaonyourclasses.Theproperties
oneachclassaredefinedthroughthe INSERTstatements.Thatis, idand titleon Postand id, postIdand texton
Comment.
Giventhatyoucreatedalinkintheabovesection,theproperty postIdisnolongernecessary.Insteadofmodifyingeach INSERT
statement,youcanusethe UPDATEcommandtoremovethemattheend:
$vimexport.sql
...
UPDATEcommentREMOVEpostId
Bearinmind,thisisanoptionalstep.Thedatabasewillstillfunctionifyouleavethisfieldinplace.
ExpectedOutput
Whenyou'vefinished,removeanystatementsthatOrientDBdoesnotsupport.Withthechangesabovethisleavesyouwithafile
similartotheonebelow:
$catexport.sql
CONNECTplocal:/tmp/db/blogadminadmin
DECLAREINTENTMASSIVEINSERT
CREATECLASSPost
CREATECLASSComment
INSERTINTOPost(id,title)VALUES(10,'NoSQLmovement')
INSERTINTOPost(id,title)VALUES(20,'NewOrientDB')
INSERTINTOComment(id,postId,text)VALUES(0,10,'First')
INSERTINTOComment(id,postId,text)VALUES(1,10,'Second')
INSERTINTOComment(id,postId,text)VALUES(21,10,'Another')
INSERTINTOComment(id,postId,text)VALUES(41,20,'Firstagain')
INSERTINTOComment(id,postId,text)VALUES(82,20,'SecondAgain')
CREATELINKcommentsTYPELINKSETFROMComment.postIdTOPost.idINVERSE
UPDATECommentREMOVEpostId
ImportingDatabases
WhenyoufinishmodifyingtheSQLfile,youcanexecuteitthroughtheConsoleinbatchmode.ThisisdonebystartingtheConsole
withtheSQLfilegivenasthefirstargument.
$$ORIENTDB_HOME/bin/console.shexport.sql
WhentheOrientDBstarts,itexecuteseachofthecommandsgivenintheSQLfiles,creatingorconnectingtothedatabase,creatingthe
classesandinsertingthedatafromtheRelationaldatabase.YounowhaveaworkinginstanceofOrientDBtouse.
193
ImportFromRDBM S
UsingtheDatabase
YounowhaveanOrientDBDocumentdatabasewhererelationshipsaredirectandhandledwithouttheuseofjoins.
Queryforallpostswithcomments:
orientdb>SELECTFROMPostWHEREcomments.size()>0
Queryforallpostswherethecommentscontaintheword"flame"inthe textproperty:
orientdb>SELECTFROMPostWHEREcommentsCONTAINS(text
LIKE'%flame%')
Queryforallpostswithcommentsmadetoday,assumingthatyouhaveaddeda datepropertytothe Commentclass:
orientdb>SELECTFROMPostWHEREcommentsCONTAINS(date>
'2011-04-1400:00:00')
Formoreinformation,see
SQLcommands
Console-Commands
194
ImportFromRDBM S
ImportfromRDBMStoGraphModel
ToimportfromRDBM StoOrientDBusingtheGraphM odeltheETLtoolisthesuggestedwaytodoit.Takealookat:Importfrom
CSVtoaGraph.
195
ImportFromNeo4j
ImportfromNeo4j
Neo4jisanopen-sourcegraphdatabasethatqueriesandmanipulatesdatausingitsownCypherQueryLanguageandcanexportin
GraphM L,anXM L-basedfileformatforgraphs.GiventhatOrientDBcanreadGraphM L,itisrelativelystraightforwardtoimport
datafromNeo4jintoOrientDB.YoucanmanagetheimportsusingtheConsoleortheJavaAPI.
Neo4jisaregisteredtrademarkofNeoTechnology,Inc.FormoreinformationonthedifferencesbetweenNeo4jandOrientDB,
seeOrientDBvs.Neo4j.
ExportingGraphML
InordertoexportdatafromNeo4jintoGraphM L,youneedtoinstalltheNeo4jShellToolsplugin.Onceyouhavethispackage
installed,youcanusethe export-graphmlutilitytoexportthedatabase.
1. ChangeintotheNeo4jhomedirectory:
$cd/path/to/neo4j-community-2.3.2
2. DownloadtheNeo4jShellTools:
$curlhttp://dist.neo4j.org/jexp/shell/neo4j-shell-tools_2.3.2.zip\
-oneo4j-shell-tools.zip
3. Unzipthe neo4j-shell-tools.zipfileintothe libdirectory:
$unzipneo4j-shell-tools.zip-dlib
4. RestarttheNeo4jServer.Intheeventthatit'snotrunning, startit:
$./bin/neo4jrestart
5. OnceyouhaveNeo4jrestartedwiththeNeo4jShellTools,launchtheNeo4jShelltool,locatedinthe bin/directory:
$./bin/neo4j-shell
WelcometotheNeo4jShell!Enter'help'foralistofcommands
NOTE:RemoteNeo4jgraphdatabaseservice'shell'atport1337
neo4j-sh(0)$
6. ExportthedatabaseintoGraphM L:
neo4j-sh(0)$export-graphml-t-o/tmp/out.graphml
WrotetoGraphML-file/tmp/out.graphml0.100%:nodes=302rels=834
properties=4221time59sectotal59sec
Thisexportsthedatabasetothepath /tmp/out.graphml.
ImportingGraphML
TherearethreemethodsavailableinimportingtheGraphM LfileintoOrientDB:throughtheConsole,throughGremlinorthroughthe
JavaAPI.
196
ImportFromNeo4j
ImportingthroughtheOrientDBConsole
FormorerecentversionsofOrientDB,youcanimportdatafromGraphM LthroughtheOrientDBConsole.Ifyouhaveversion2.0or
greater,thisistherecommendedmethodgiventhatitcanautomaticallytranslatetheNeo4jlabelsintoclasses.
1. LogintotheOrientDBConsole.
$$ORIENTDB_HOME/bin/console.sh
2. InOrientDB,createadatabasetoreceivetheimport:
orientdb>CREATEDATABASEPLOCAL:/tmp/db/test
Creatingdatabase[plocal:/tmp/db/test]usingthestoragetype[plocal]...
Databasecreatedsuccessfully.
Currentdatabaseis:plocal:/tmp/db/test
3. ImportthedatafromtheGraphM Lfile:
orientdb{db=test}>IMPORTDATABASE/tmp/out.graphml
ImportingGRAPHMLdatabasedatabasefrom/tmp/out.graphml...
Transaction8hasbeencommittedin12ms
ThisimportstheNeo4jdatabaseintoOrientDBonthe testdatabase.
ImportingthroughtheGremlinConsole
ForolderversionsofOrientDB,youcanimportdatafromGraphM LthroughtheGremlinConsole.Ifyouhaveaversion1.7orearlier,
thisisthemethodtouse.Itisnotrecommendedonmorerecentversions,giventhatitdoesn'tconsiderlabelsdeclaredinNeo4j.Inthis
case,everythingimportsasthebasevertexandedgeclasses,(thatis, Vand E).Thismeansthat,afterimportingthroughGremlin
youneedtorefactoryougraphelementstofitamorestructuredschema.
ToimporttheGraphM LfileintoOrientDB,completethefollowingsteps:
1. LaunchtheGremlinConsole:
$$ORIENTDB_HOME/bin/gremlin.sh
\,,,/
(oo)
-----oOOo-(_)-oOOo-----
2. FromtheGremlinConsole,createanewgraph,specifyingthepathtoyourGraphdatabase,(here /tmp/db/test):
gremlin>g=newOrientGraph("plocal:/tmp/db/test");
==>orientgraph[plocal:/db/test]
3. LoadtheGraphM Lfileintothegraphobject(thatis, g):
gremlin>g.loadGraphML("/tmp/out.graphml");
==>null
4. ExittheGremlinConsole:
197
ImportFromNeo4j
gremlin>quit
ThisimportstheGraphM LfileintoyourOrientDBdatabase.
ImportingthroughtheJavaAPI
OrientDBConsolecallstheJavaAPI.UsingtheJavaAPIdirectlyallowsyougreatercontrolovertheimportprocess.Forinstance,
newOGraphMLReader(newOrientGraph("plocal:/temp/bettergraph")).inputGraph("/temp/neo4j.graphml");
ThislineimportstheGraphM LfileintoOrientDB.
DefiningCustomStrategies
Beginninginversion2.1,OrientDBallowsyoutomodifytheimportprocessthroughcustomstrategiesforvertexandedgeattributes.It
supportsthefollowingstrategies:
com.orientechnologies.orient.graph.graphml.OIgnoreGraphMLImportStrategyDefinesattributestoignore.
com.orientechnologies.orient.graph.graphml.ORenameGraphMLImportStrategyDefinesattributestorename.
Exammples
Ignorethevertexattribute type:
newOGraphMLReader(newOrientGraph("plocal:/temp/bettergraph")).defineVertexAttributeStrategy("__type__",newOIgnoreGrap
hMLImportStrategy()).inputGraph("/temp/neo4j.graphml");
Ignoretheedgeattribute weight:
newOGraphMLReader(newOrientGraph("plocal:/temp/bettergraph")).defineEdgeAttributeStrategy("weight",newOIgnoreGraphMLI
mportStrategy()).inputGraph("/temp/neo4j.graphml");
Renamethevertexattribute typeinjust type:
newOGraphMLReader(newOrientGraph("plocal:/temp/bettergraph")).defineVertexAttributeStrategy("__type__",newORenameGrap
hMLImportStrategy("type")).inputGraph("/temp/neo4j.graphml");
ImportTipsandTricks
DealingwithMemoryIssues
IntheeventthatyouexperiencememoryissueswhileattemptingtoimportfromNeo4j,youmightconsiderreducingthebatchsize.By
default,thebatchsizeissetto 1000.SmallervaluecausesOrientDBtoprocesstheimportinsmallerunits.
ImportwithadjustedbatchsizethroughtheConsole:
orientdb{db=test}>IMPORTDATABASE/tmp/out.graphmlbatchSize=100
ImportwithadjustedbatchsizethroughtheJavaAPI:
newOGraphMLReader(newOrientGraph("plocal:/temp/bettergraph")).setBatchSize(100).inputGraph("/temp/neo4j.graphml");
StoringtheVertexID's
Bydefault,OrientDBupdatestheimporttouseitsownID'sforvertices.IfyouwanttopreservetheoriginalvertexID'sfromNeo4j,
usethe storeVertexIdsoption.
198
ImportFromNeo4j
ImportwiththeoriginalvertexID'sthroughtheConsole:
orientdb{db=test}>IMPORTDATABASE/tmp/out.graphmlstoreVertexIds=true
ImportwiththeoriginalvertexID'sthroughtheJavaAPI:
newOGraphMLReader(newOrientGraph("plocal:/temp/bettergraph")).setStoreVertexIds(true).inputGraph("/temp/neo4j.graphml")
;
199
ETL
ETL
TheExtractorTransformerandLoader,orETL,moduleforOrientDBprovidessupportformovingdatatoandfromOrientDB
databasesusingETLprocesses.
Configuration:TheETLmoduleusesaconfigurationfile,writteninJSON.
ExtractorPullsdatafromthesourcedatabase.
TransformersConvertthedatainthepipelinefromitssourceformattooneaccessibletothetargetdatabase.
Loaderloadsthedataintothetargetdatabase.
HowETLWorks
TheETLmodulereceivesabackupfilefromanotherdatabase,itthenconvertsthefieldsintoanaccessibleformatandloadsitinto
OrientDB.
EXTRACTOR=>TRANSFORMERS[]=>LOADER
Forexample,considertheprocessforaCSVfile.UsingtheETLmodule,OrientDBloadsthefile,applieswhateverchangesitneeds,
thenstoresthereocrdasadocumentintothecurrentOrientDBdatabase.
+-----------+-----------------------+-----------+
||PIPELINE|
+EXTRACTOR+-----------------------+-----------+
||TRANSFORMERS|LOADER|
+-----------+-----------------------+-----------+
|FILE==>CSV->FIELD->MERGE==>OrientDB|
+-----------+-----------------------+-----------+
Youcanmodifythispipeline,allowingthetransformationandloadingphasestoruninparallelbysettingtheconfigurationvariable
"parallel"to true.
{"parallel":true}
Installation
Beginningwithversion2.0,OrientDBbundlestheETLmodulewiththeofficialrelease.Followthesestepstousethemodule:
Clonetherepositoryonyourcomputer,byexecuting:
gitclonehttps://github.com/orientechnologies/orientdb-etl.git
Compilethemodule,byexecuting:
mvncleaninstall
Copy script/oetl.sh(or.batunderWindows)to$ORIENTDB_HOM E/bin
Copy target/orientdb-etl-2.0-SNAPSHOT.jarto$ORIENTDB_HOM E/lib
Usage
TousetheETLmodule,runthe oetl.shscriptwiththeconfigurationfilegivenasanargument.
$$ORIENTDB_HOME/bin/oetl.shconfig-dbpedia.json
200
ETL
NOTE:Ifyouareimportingdataforuseinadistributeddatabase,thenyoumustset
ridBag.embeddedToSbtreeBonsaiThreshold=Integer.MAX\_VALUEfortheETLprocesstoavoidreplicationerrors,
whenthedatabaseisupdatedonline.
Run-timeConfiguration
WhenyouruntheETLmodule,youcandefineitsconfigurationvariablesbypassingitaJSONfile,whichtheETLmoduleresolvesat
run-timebypassingthemasitstartsup.
Youcouldalsodefinethevaluesforthesevariablesthroughcommand-lineoptions.Forexample,youcouldassignthedatabaseURLas
${databaseURL},thenpasstherelevantargumentthroughthecommand-line:
$$ORIENTDB_HOME/bin/oetl.shconfig-dbpedia.json\
-databaseURL=plocal:/tmp/mydb
WhentheETLmoduleinitializes,itpulls /tmp/mydbfromthecommand-linetodefinethisvariableintheconfigurationfile.
AvailableComponents
Blocks
Sources
Extractors
Transformers
Loaders
Examples:
ImportthedatabaseofBeers
ImportfromCSVtoaGraph
ImportfromJSON
ImportDBPedia
ImportfromaDBM S
ImportfromParse(Facebook)
201
Configuration
ETL-Configuration
OrientDBmanagesconfigurationfortheETLmodulethroughasingleJSONconfigurationfile,calledatexecution.
S yntax
{
"config":{
<name>:<value>
},
"begin":[
{<block-name>:{<configuration>}}
],
"source":{
{<source-name>:{<configuration>}}
},
"extractor":{
{<extractor-name>:{<configuration>}}
},
"transformers":[
{<transformer-name>:{<configuration>}}
],
"loader":{<loader-name>:{<configuration>}},
"end":[
{<block-name>:{<configuration>}}
]
}
"config"M anagesallsettingsandcontextvariablesusedbyanycomponentoftheprocess.
"source"M anagesthesourcedatatoprocess.
"begin"Definesalistofblockstoexecuteinorderwhentheprocessbegins.
"extractor"M anagestheextractorsettings.
"transformers"Definesalistoftransformerstoexecuteinthepipeline.
"loader"M anagestheloadersettings.
"end"Definesalistofblockstoexecuteinorderwhentheprocessfinishes.
Example
202
Configuration
{
"config":{
"log":"debug",
"fileDirectory":"/temp/databases/dbpedia_csv/",
"fileName":"Person.csv.gz"
},
"begin":[
{"let":{"name":"$filePath","value":"$fileDirectory.append($fileName)"}},
{"let":{"name":"$className","value":"$fileName.substring(0,$fileName.indexOf("."))"}}
],
"source":{
"file":{"path":"$filePath","lock":true}
},
"extractor":{
"row":{}
},
"transformers":[
{"csv":{"separator":",","nullValue":"NULL","skipFrom":1,"skipTo":3}},
{"merge":{"joinFieldName":"URI","lookup":"V.URI"}},
{"vertex":{"class":"$className"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/dbpedia",
"dbUser":"admin",
"dbPassword":"admin",
"dbAutoCreate":true,
"tx":false,
"batchCommit":1000,
"dbType":"graph",
"indexes":[{"class":"V","fields":["URI:string"],"type":"UNIQUE"}]
}
}
}
GeneralRules
IndevelopingaconfigurationfileforETLmoduleprocesses,considerthefollowing:
Youcanusecontextvariablesbyprefixingthemwiththe $sign.
Itassignsthe $inputcontextvariablebeforeeachtransformation.
YoucanexecuteanexpressioninOrientDBSQLwiththe ={<expression>}syntax.Forinstance,
"field":={EVAL('3*5)}
ConditionalExecution
Inconditionalexecution,OrientDBonlyrunsexecutableblocks,suchastransformersandblocks,whenaconditionisfoundtrue,suchas
witha WHEREclause.
Forexample,
{"let":{
"name":"path",
"value":"C:/Temp",
"if":"${os.name}='Windows'"
}
},
{"let":{
"name":"path",
"value":"/tmp",
"if":"${os.name}.indexOf('nux')"
}
}
Logsetting
203
Configuration
M ostblocks,suchtransformersandblocks,supportthe "log"setting.Logstakeoneofthefollowinglogginglevels,(whicharecaseinsensitive),: NONE, ERROR, INFO, DEBUG.Bydefault,itusesthe INFOlevel.
Settingthelog-levelto DEBUGdisplaysmoreinformationonexecution.Italsoslowsdownexecution,souseitonlyfordevelopment
anddebuggingpurposes.
{"http":{
"url":"http://ip.jsontest.com/",
"method":"GET",
"headers":{
"User-Agent":"Mozilla/5.0(Macintosh;IntelMacOSX10_9_4)AppleWebKit/537.36(KHTML,likeGecko)Chrome/36.0.1985.12
5Safari/537.36"
},
"log":"DEBUG"
}
}
ConfigurationVariables
TheETLmodulebindsallvaluesdeclaredinthe "config"blocktotheexecutioncontextandareaccessibletoETLprocessing.There
arealsosomespecialvariablesusedbytheETLprocess.
Variable
Description
Type
Default
value
"log"
Definesthegloballogginglevel.Theacceptedlevelsare: NONE, ERROR, INFO,
and DEBUG.ThisparameterisusefultodebugaETLprocessorsingle
component.
string
INFO
"maxRetries"
Definesthemaximumnumberofretriesallowed,intheeventthattheloader
raisesan ONeedRetryException,forconcurrentmodificationofthesamerecord.
integer
10
"parallel"
DefineswhethertheETLmoduleexecutespipelinesinparallel,usingallavailable
cores.
boolean
false
"haltOnError"
DefineswhethertheETLmodulehaltstheprocesswhenitencounters
unmanageableerrors.Whensetto false,theprocesscontinuesintheeventof
errors.Itreportsthenumberoferrorsitencountersattheendoftheimport.This
featurewasintroducedinversion2.0.9.
boolean
true
SplitConfigurationonMultipleFiles
Youcansplittheconfigurationintoseveralfilesallowingforthecompositionofcommonpartssuchaspaths,URL'sanddatabase
references.
Forexample,youmightsplittheaboveconfigurationintotwofiles:onewiththeinputpathsfor Person.csvspecifically,whilethe
otherwouldcontaincommonconfigurationsfortheETLmodule.
204
Configuration
$catpersonConfig.json
{
"config":{
"log":"debug",
"fileDirectory":"/temp/databases/dbpedia_csv/",
"fileName":"Person.csv.gz"
}
}
$catcommonConfig.json
{
"begin":[
{"let":{"name":"$filePath","value":"$fileDirectory.append($fileName)"}},
{"let":{"name":"$className","value":"$fileName.substring(0,$fileName.indexOf("."))"}}
],
"source":{
"file":{"path":"$filePath","lock":true}
},
"extractor":{
"row":{}
},
"transformers":[
{"csv":{"separator":",","nullValue":"NULL","skipFrom":1,"skipTo":3}},
{"merge":{"joinFieldName":"URI","lookup":"V.URI"}},
{"vertex":{"class":"$className"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/dbpedia",
"dbUser":"admin",
"dbPassword":"admin",
"dbAutoCreate":true,
"tx":false,
"batchCommit":1000,
"dbType":"graph",
"indexes":[{"class":"V","fields":["URI:string"],"type":"UNIQUE"}]
}
}
}
Then,whenyoucancallbothconfigurationfileswhenyouruntheETLmodule:
$$ORIENTDB_HOME/bin/oetl.shcommonConfig.jsonpersonConfig.json
Run-timeconfiguration
IntheconfigurationfilefortheETLmodule,youcandefinevariablesthatthemoduleresolvesatrun-timebypassingthemascommandlineoptions.Valuespassedinthismanneroverridethevaluesdefinedinthe "config"section,evenwhenyouusemultiple
configurationfiles.
Forinstance,youmightsettheconfigurationvariableinthefileto ${databaseURL},thendefineitthroughthecommand-lineusing:
$$ORIENTDB_HOME/bin/oetl.shconfig-dbpedia.json\
-databaseURL=plocal:/tmp/mydb
Inthiscase,the databaseURLparameterissetinthe "config"sectionto /tmp/mydb,overridinganyvaluegiventhefile.
205
Configuration
{
"config":{
"log":"debug",
"fileDirectory":"/temp/databases/dbpedia_csv/",
"fileName":"Person.csv.gz"
"databaseUrl":"plocal:/temp/currentDb"
},
...
206
Blocks
ETL-Blocks
WhenOrientDBexecutestheETLmodule,blocksintheETLconfigurationdefinecomponentstoexecuteintheprocess.TheETL
moduleinOrientDBsupportsthefollowingtypesofblocks:
"let"
"code"
"console"
LetBlocks
Ina "let"block,youcandefinevariablestotheETLprocesscontext.
Componentname: let
S yntax
Parameter
Description
Type
Mandatory
yes
"name"
Definesthevariablename.TheETLprocessignoresanyvalues
withthe $prefix.
string
"value"
Definesthefixedvaluetoassign.
an
"expression"
DefinesanexpressionintheOrientDBSQLlanguagetoevaluate
andassign.
string
Default
value
Examples
Assignavaluetothefilepathvariable
{
"let":{
"name":"$filePath",
"value":"/temp/myfile"
}
}
Concatthe $fileNamevariabletothe $fileDirectorytocreateanewvariablefor $filePath:
{
"let":{
"name":"$filePath",
"expression":"$fileDirectory.append($fileName)"
}
}
CodeBlock
Inthe "code"block,youcanconfigurecodesnippetstoexecuteinanyJVM -supportedlanguages.ThedefaultlanguageisJavaScript.
Componentname: code
S yntax
Parameter
Description
Type
"language"
Definestheprogramminglanguagetouse.
string
"code"
Definesthecodetoexecute.
string
Mandatory
Defaultvalue
Javascript
yes
207
Blocks
Examples
Executea Hello,World!programinJavaScript,throughtheETLmodule:
{
"code":{
"language":"Javascript",
"code":"print('HelloWorld!');"
}
}
ConsoleBlock
Ina "console"block,youcandefinecommandsOrientDBexecutesthroughtheConsole.
Componentname: console
S yntax
Parameter
Description
Type
"file"
Definesthepathtoafilecontainingthecommandsyouwant
toexecute.
string
"commands"
Definesanarrayofcommands,asstrings,toexecutein
sequence.
string
array
Mandatory
Default
value
Example
Invoketheconsolewithafilecontainingthecommands:
{
"console":{
"file":"/temp/commands.sql"
}
}
Invoketheconsolewithanarrayofcommands:
{
"console":{
"commands":[
"CONNECTplocal:/temp/db/mydbadminadmin",
"INSERTINTOAccountsetname='Luca'"
]
}
}
208
Sources
ETL-Sources
WhenOrientDBexecutestheETLmodule,sourcecomponentsdefinethesourceofthedatayouwanttoextract.Inthecaseofsome
extractorslikeJDBCExtractorworkwithoutsource,makingthiscomponentoptional.TheETLmoduleinOrientDBsupportsthe
followingtypesofsources:
"file"
"input"
"http"
FileSources
Inthefilesourcecomponent,thevariablesrepresentasourcefilecontainingthedatayouwanttheETLmoduletoread.Youcanusetext
filesorfilescomprssedto tar.gz.
Componentname: file
S yntax
Parameter
Description
Type
Mandatory
Defaultvalue
"path"
Definesthepathtothefile
string
yes
"lock"
Defineswhethertolockthefileduringtheextractionphase.
boolean
false
"encoding"
Definestheencodingforthefile.
string
UTF-8
Examples
Extractdatafromthefileat /tmp/actor.tar.gz:
{
"file":{
"path":"/tmp/actor.tar.gz",
"lock":true,
"encoding":"UTF-8"
}
}
InputSources
Intheinputsourcecomponent,theETLmoduleextractsdatafromconsoleinput.YoumayfindthisusefulincaseswheretheETL
moduleoperatesinapipewithothertools.
Componentname: input
S yntax
oetl.sh"<input>"
Example
Catafile,pipingitsoutputintotheETLmodule:
$cat/etc/csv|$ORIENTDB_HOME/bin/oetl.sh\
"{transformers:[{csv:{}}]}"
HTTPSources
209
Sources
IntheHTTPsourcecomponent,theETLmoduleextractsdatafromanHTTPaddressassource.
Componentname: http
S yntax
Parameter
Description
Type
"url"
DefinestheURLtolooktoforsourcedata.
string
"method"
DefinestheHTTPmethodtouseinextractingdata.Supported
methodsare: GET, POST, PUT, DELETE, HEAD, OPTIONS,
and TRACE.
string
"headers"
Definestherequestheadersasaninnerdocumentkey/value.
document
Mandatory
Default
value
yes
GET
Examples
ExecuteanHTTPrequestina GET,settingtheuseragentintheheader:
{
"http":{
"url":"http://ip.jsontest.com/",
"method":"GET",
"headers":{
"User-Agent":"Mozilla/5.0(Macintosh;IntelMacOSX10_9_4)AppleWebKit/537.36(KHTML,likeGecko)Chrome/36.0
.1985.125Safari/537.36"
}
}
}
210
Extractors
ETL-Extractors
WhenOrientDBexecutestheETLmodule,extractorcomponentshandledataextractionfromsource.TheyarethefirstpartoftheETL
process.TheETLmoduleinOrientDBsupportsthefollowingextractors:
Row
CSV
JDBC
JSON
XM L
RowExtractor
WhentheETLmodulerunswithaRowExtractor,itextractscontentrowbyrow.Itoutputsastringarrayclass.
Compnentname: row
OutputClass: [string]
S yntax
Parameter
Description
Type
Mandatory
Default
value
"multiLine"
Defineswhethertheprocesssupportsmultiline.Usefulwith
CSV'ssupportinglinefeedinsideofstring.
boolean
true
"linefeed"
Definesthelinefeedtouseintheeventofmultilineprocessing.
string
\r\n
The "multiLine"and "linefeed"parameterswereintroducedinversion2.0.9.
Examples
Usetherowextractorwithitsdefaultconfiguration:
{
"row":{}
}
CSVExtractor
WhentheETLmodulerunstheCSVExtractor,itparsesafileformatedtoApacheCommonsCSVandextractsthedataintoOrientDB.
Thiscomponentwasintroducedinversion2.1.4andisunavailableinolderreleasesofOrientDB.
Componentname: csv
Outputclass: [ODocument]
S yntax
211
Extractors
Parameter
Description
Type
Mandatory
Default
value
"separator"
Definesthecolumnseparator.
char
,
"columnsOnFirstLine"
Defineswhetherthefirstlinecontainscolumn
descriptors.
boolean
true
"columns"
Definesarrayfornamesand(optionally)typesto
write.
string
array
"nullValue"
Definesthenullvalueinthefile.
string
NULL
"dateFormat"
Definestheformattouseinparsingdatesfromfile.
string
yyyy-mmdd
"quote"
Definesstringcharacterdelimiter.
char
"
"skipFrom"
Definesthelinenumberyouwanttoskipfrom.
integer
"skipTo"
Definesthelinenumberyouwanttoskipto.
integer
"ignoreEmptyLines"
Defineswhetheritshouldignoreemptylines.
boolean
"predefinedFormat"
DefinestheCSVformatyouwanttouse.
string
false
Forthe "columns"parameter,specifythetypebypostfixingittothevalue.Specifyingtypesguaranteesbetterperformance.
Forthe "predefinedFormat"parameter,theavailableformatsare: Default, Excel, MySQL, RFC4180, TDF.
Examples
ExtractlinesfromCSVtothe ODocumentclass,usingcommasastheseparator,considering NULLasthenullvalueandskipping
rowstwothroughfour:
{"csv":
{"separator":",",
"nullValue":"NULL",
"skipFrom":1,
"skipTo":3
}
}
ExtractlinesfromaCSVexportedfromM ySQL:
{"csv":
{"predefinedFormat":"MySQL"}
}
ExtractlinesfromaCSVwiththedefaultformatting,using N/Aasthenullvalueandacustomdateformat:
{"csv":
{"predefinedFormat":"Default",
"nullValue":"N/A",
"dateFormat":"dd-mm-yyyyHH:MM"
}
}
JDBCExtractor
WhentheETLmodulerunstheJDBCExtractor,itcanaccessanydatabasemanagementsystemthatsupportstheJDBCdriver.
InorderfortheETLcomponenttoconnecttothesourcedatabase,putthesourcedatabase'sJDBCdriverintheclasspath,orinthe
$ORIENTDB_HOME/libdirectory.
Componentname: jdbc
Outputclass: [ODocument]
212
Extractors
S yntax
Parameter
Description
Type
Mandatory
"driver"
DefinestheJDBCDriverclass.
string
yes
"url"
DefinestheJDBCURLtoconnectto.
string
yes
"userName"
Definestheusernametouseonthesourcedatabase.
string
yes
"userPassword"
Definestheuserpasswordtouseonthesourcedatabase.
string
yes
"query"
Definesthequerytoextracttherecordyouwanttoimport.
string
yes
"queryCount"
Definesquerythatreturnsthecountofthefetchedrecords,
(usedtoprovideacorrectprogressindicator).
string
Default
value
Example
Extractthecontentsofthe clienttableontheM ySQLdatabase testatlocalhost:
{"jdbc":{
"driver":"com.mysql.jdbc.Driver",
"url":"jdbc:mysql://localhost/test",
"userName":"root",
"userPassword":"my_mysql_passwd",
"query":"SELECT*FROMclient"
}
}
JSONExtractor
WhentheETLmodulerunswithaJSONExtractor,itextractsdatabyparsingJSONobjects.IfthedatahasmorethanoneJSONitems,
youmustenclosethein []brackets.
Componentname: json
Outputclass: [ODocument]
Example
ExtractdatafromaJSONfile.
{"json":{}}
XMLExtractor
WhentheETLmodulerunswiththeXM Lextractor,itextractsdatabyparsingXM Lelements.Thisfeaturewasintroducedinversion
2.2.
Componentname: xml
Outputclass: [ODocument]
S yntax
Parameter
Description
Type
"rootNode"
DefinestherootnodetoextractintheXM L.Bydefault,it
buildsfromtherootelementinthefile.
string
"tagsAsAttribute"
Definesanarrayofelements,wherechildelementsare
consideredasattributesofthedocumentandtheattribute
valuesasthetextwithintheelement.
string
array
Mandatory
Default
value
Examples
213
Extractors
ExtractdatafromanXM Lfile,wheretheXM Lfilereadsas:
<?xmlversion="1.0"encoding="UTF-8"?>
<a>
<b>
<cname='Ferrari'color='red'>ignore</c>
<cname='Maserati'color='black'/>
</b>
</a>
WhiletheOrientDB-ETLconfigurationfilereadsas:
{"source":
{"file":
{"path":"src/test/resources/simple.xml"}
},
"extractor":
{"xml":{}},
"loader":
{"test":{}}
}
Thisextractsthedataas:
{
"a":{
"b":{
"c":[
{
"color":"red",
"name":"Ferrari"
},
{
"color":"black",
"name":"Maserati"
}
]
}
}
}
ExtractacollectionfromXM L,wheretheXM Lfilereadsas:
<?xmlversion="1.0"encoding="UTF-8"?>
<CATALOG>
<CD>
<TITLE>EmpireBurlesque</TITLE>
<ARTIST>BobDylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
<CD>
<TITLE>Hideyourheart</TITLE>
<ARTIST>BonnieTyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBSRecords</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
</CD>
<CD>
<TITLE>GreatestHits</TITLE>
<ARTIST>DollyParton</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>RCA</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1982</YEAR>
</CD>
</CATALOG>
214
Extractors
WhiletheOrientDB-ETLconfigurationfilereads:
{"source":
{"file":
{"path":"src/test/resources/music.xml"}
},"extractor":
{"xml":
{"rootNode":"CATALOG.CD",
"tagsAsAttribute":["CATALOG.CD"]
}
},
"loader":{"test":{}}
}
Thisextractsthedataas:
{
"TITLE":"EmpireBurlesque",
"ARTIST":"BobDylan",
"COUNTRY":"USA",
"COMPANY":"Columbia",
"PRICE":"10.90",
"YEAR":"1985"
}
{
"TITLE":"Hideyourheart",
"ARTIST":"BonnieTyler",
"COUNTRY":"UK",
"COMPANY":"CBSRecords",
"PRICE":"9.90",
"YEAR":"1988"
}
{
"TITLE":"GreatestHits",
"ARTIST":"DollyParton",
"COUNTRY":"USA",
"COMPANY":"RCA",
"PRICE":"9.90",
"YEAR":"1982"
}
215
Transformers
ETLTransformers
WhenOrientDBrunstheETLmodule,transformercomponentsexecuteinapipelinetomodifythedatabeforeitgetsloadedintothe
OrientDBdatabase.Theoperateonreceivedinputandreturnoutput.
Beforeexecution,italwaysinitalizesthe $inputvariable,sothatifyouneedtoyoucanaccessitatrun-time.
CSV
FIELD
M ERGE
VERTEX
CODE
LINK
EDGE
FLOW
LOG
BLOCK
COM M AND
CSVTransformer
Beginningwithversion2.1.4,theCSVTransformerhasbeendeprecatedinfavoroftheCSVExtractor.
ConvertsastringinaDocument,parsingitasCSV
Componentdescription.
Componentname:csv
Supportedinputstypes:[S tring]
Output:ODocument
S yntax
Parameter
Description
Type
Mandatory
Default
value
"separator"
Definesthecolumnseparator.
char
,
"columnsOnFirstLine"
Defineswhetherthefirstlinecontainscolumn
descriptions.
boolean
true
"columns"
Definesarraycontainingcolumnnames,youcandefine
typesbypostfixingthenameswith :<type>.
string
array
"nullValue"
Definesthevaluetointerpretasnull.
string
"stringCharacter"
Definesstringcharacterdelimiter.
char
"skipFrom"
Definesthelinenumbertoskipfrom.
integer
yes
"skipTo"
Definesthelinenumbertoskipto.
integer
yes
"
Forthe "columns"parameter,specifyingtypeguaranteesbetterperformance.
Example
TransformarowinCSV(as ODocumentclass),usingcommasastheseparator,considering NULLasanullvalueandskipping
rowstwothroughfour.
{"csv":{"separator":",","nullValue":"NULL",
"skipFrom":1,"skipTo":3}}
216
Transformers
FieldTransformer
WhentheETLmodulecallstheFieldTransformer,itexecutesanSQLtransformeragainstthefield.
Componentdescription.
Componentname:vertex
Supportedinputstypes:[ODocument]
Output:ODocument
S yntax
Parameter
Description
Type
Mandatory
Default
value
"fieldName"
Definesthedocumentfieldnametouse.
string
"expression"
Definestheexpressionyouwanttoevaluate,usingOrientDB
SQL.
string
"value"
Definesthevaluetoset.Ifthevalueistakenorcomputedatruntime,use "expression"instead.
any
"operation"
Definestheoperationtoexecuteagainstthefields: SETor
REMOVE.
string
SET
"save"
Defineswhethertosavethevertex,edgeordocumentrightafter
settingthefields.
boolean
false
yes
The "fieldName"parameterwasintroducedinversion2.1.
Examples
Transformthefield classintothe ODocumentclass,byprefixingitwith _:
{"field":
{"fieldName":"@class",
"expression":"class.prefix('_')"
}
}
Applytheclassname,basedonthevalueofanotherfield:
{"field":
{"fieldName":"@class",
"expression":"if((fileCount>=0),'D','F')"
}
}
Assignthelastpartofapathtothe namefield:
{"field":
{"fieldName":"name",
"expression":"path.substring(eval('$current.path.lastIndexOf(\"/\")+1'))"
}
}
Asignthefieldafixedvalue:
{"field":
{"fieldName":"counter",
"value":0
}
}
Renamethefieldfrom salaryto renumeration:
217
Transformers
{"field":
{"fieldName":"remuneration",
"expression":"salary"
}
},
{"field":
{"fieldName":"salary",
"operation":"remove"
}
}
Renamemultiplefieldsinonecall.
{"field":
{"fieldNames":
["remuneration","salary"],
"operation":"remove"
}
}
Thisfeaturewasintroducedinversion2.1.
MergeTransformer
WhentheETLmodulecallstheM ergeTransformer,ittakesinputfromone ODocumentinstancetooutputintoanother,loadedby
lookup.THelookupcaneitherbealookupagainstanindexora SELECTquery.
Componentdescription.
Componentname:merge
Supportedinputstypes:[ODocument,OrientVertex]
Output:ODocument
S yntax
Parameter
Description
Type
Mandatory
"joinFieldName"
Definesthefieldcontainingthejoinvalue.
string
yes
"lookup"
Definestheindexonwhichtoexecutethelookup,ora
SELECTquery.
string
yes
"unresolvedLinkAction"
Definestheactiontoexecuteintheeventthatthejoin
hasn'tbeenresolved.
string
Default
value
NOTHING
Forthe "unresolvedLinkAction"parameter,thesupportedactionsare:
Action
Description
NOTHING
Tellsthetransformertodonothing.
WARNING
Tellsthetransformertoincrementwarnings.
ERROR
Tellsthetransformertoincrementerrors.
HALT
Tellsthetransformertointerrupttheprocess.
SKIP
Tellsthetransformertoskipthecurrentrow.
Example
M ergethecurrentrecordagainsttherecordreturnedbythelookuponindex V.URI,withthevaluecontainedinthefield URIof
theinputdocument:
218
Transformers
{"merge":
{"joinFieldName":"URI",
"lookup":"V.URI"
}
}
VertexTransformer
WhentheETLmodulerunstheVertexTransformer,ittransforms ODocumentinputtooutput OrientVertex.
Componentdescription.
Componentname:vertex
Supportedinputstypes:[ODocument,OrientVertex]
Output:OrientVertex
S yntax
Parameter
Description
Type
Mandatory
Default
value
"class"
Definesthevertexclasstouse.
string
V
"skipDuplicates"
Defineswhetheritskipsduplicates.Whenclasshasa
UNIQUEconstraint,ETLignoresduplicates.
boolean
false
The "skipDuplicates"parameterwasintroducedinversion2.1.
Example
Transform ODocumentinputintoavertex,settingtheclassvaluetothe $classnamevariable:
{"vertex":
{"class":"$className",
"skipDuplicates":true
}
}
EdgeTransformer
WhentheETLmodulescallstheEdgeTransformer,itconvertsjoinvaluesinoneormoreedgesbetweenthecurrentvertexandall
verticesreturnedbythelookup.Thelookupcaneitherbemadeagainstanindexora SELECT.
Componentdescription.
Componentname:EDGE
Supportedinputstypes:[ODocument,OrientVertex]
Output:OrientVertex
S yntax
219
Transformers
Parameter
Description
Type
Mandatory
Default
value
"joinFieldName"
Definesthefieldcontainingthejoinvalue.
string
yes
"direction"
Definestheedgedirection.
string
out
"class"
Definestheedgeclass.
string
E
"lookup"
Definestheindexonwhichtoexecutethelookupor
a SELECT.
string
"targetVertexFields"
Definesthefieldonwhichtosetthetargetvertex.
object
"edgeFields"
Definesthefieldstosetintheedge.
object
"skipDuplicates"
Defineswhethertoskipduplicateedgeswhenthe
UNIQUEconstraintissetonboththe outand in
properties.
boolean
false
"unresolvedLinkAction"
Definestheactiontoexecuteintheeventthatthe
joinhasn'tbeenresolved.
string
NOTHING
yes
The "targetVertexFields"andx "edgeFields"parameterwereintroducedinversion2.1.
Forthe "unresolvedLinkAction"parameter,thefollowingactionsaresupported:
Action
Description
NOTHING
Tellsthetransformertodonothing.
CREATE
Tellsthetransformertocreateaninstanceof OrientVertex,settingtheprimarykeytothejoinvalue.
WARNING
Tellsthetransformertoincrementwarnings.
ERROR
Tellsthetransformertoincrementerrors.
HALT
Tellsthetransformertointerrupttheprocess.
SKIP
Tellsthetransformertoskupthecurrentrow.
Examples
Createanedgefromthecurrentvertex,withtheclasssetto Parent,toallverticesreturnedbythelookuponthe D.inodeindex
withthevaluecontainedinthefiled inode_parentoftheinput'svertex:
{"edge":
{"class":"Parent",
"joinFieldName":"inode_parent",
"lookup":"D.inode",
"unresolvedLinkAction":"CREATE"
}
}
Transformerasingle-lineCSVthatcontainsbothverticesandedges:
220
Transformers
{"source":
{"content":
{"value":"id,name,surname,friendSince,friendId,friendName,friendSurname\n0,Jay,Miner,1996,1,Luca,Garulli"
}
},
"extractor":
{"row":{}},
"transformers":
[
{"csv":{}},
{"vertex":
{"class":"V1"}
},
{"edge":
{"unresolvedLinkAction":"CREATE",
"class":"Friend",
"joinFieldName":"friendId",
"lookup":"V2.fid",
"targetVertexFields":
{"name":"${input.friendName}",
"surname":"${input.friendSurname}"
},
"edgeFields":
{"since":"${input.friendSince}"}
}
},
{"field":
{"fieldNames":
["friendSince",
"friendId",
"friendName",
"friendSurname"
],
"operation":"remove"
}
}
],
"loader":
{"orientdb":
{"dbURL":"memory:ETLBaseTest",
"dbType":"graph",
"useLightweightEdges":false
}
}
}
FlowTransformer
WhentheETLmodulecallstheFlowTransformer,itmodifiestheflowthroughthepipeline.Supportedoperationsare skipand
halt.Typically,thistransformeroperateswiththe ifattribute.
Componentdescription.
Componentname:flow
Supportedinputstypes:Any
Output:sametypeasinput
S yntax
Parameter
"operation"
Description
Definestheflowoperation: skipor halt.
Type
string
Mandatory
Defaultvalue
yes
Example
Skipthecurrentrecordif nameisnull:
221
Transformers
{"flow":
{"if":"nameisnull",
"operation":"skip"
}
}
CodeTransformer
WhentheETLmodulecallstheCodeTransformer,itexecutesasnippetofcodeinanyJVM supportedlanguage.Thedefaultis
JavaScript.Thelastobjectinthecodeisreturnedasoutput.
Intheexecutioncontext:
inputTheinputobjectreceived.
recordTherecordextractedfromtheinputobject,whenpossible.Intheeventthatinputobjectisavertexoredge,itassignsthe
underlying ODocumenttothevariable.
Componentdescription.
Componentname:code
Supportedinputstypes:[Object]
Output:Object
S yntax
Parameter
Description
Type
"language"
Definestheprogramminglanguagetouse.
string
"code"
Definesthecodetoexecute.
string
Mandatory
Defaultvalue
JavaScript
yes
Example
Displaythecurrentrecordandreturntheparent:
{"code":
{"language":"Javascript",
"code":"print('Currentrecord:'+record);record.field('parent');"
}
}
LinkTransformer
WhentheETLmodulecallstheLinkTransformer,itconvertsjoinvaluesintolinkswithinthecurrentrecord,usingtheresultofthe
lookup.Thelookupcanbemadeagainstanindexora SELECT.
Componentdescription.
Componentname:link
Supportedinputstypes:[ODocument,OrientVertex]
Output:ODocument
S yntax
222
Transformers
Parameter
Description
Type
Mandatory
"joinFieldName"
Definesthefieldcontaininghtejoinvalue.
string
"joinValue"
Definesthevaluetolookup.
string
"linkFieldName"
Definesthefieldcontainingthelinktoset.
string
yes
"linkFieldType"
Definesthelinktype.
string
yes
"lookup"
Definestheindexonwhichtoexecutethelookupora
SELECTquery.
string
yes
"unresolvedLinkAction"
Definestheactiontoexecuteintheeventthatthejoin
doesn'tresolve.
string
Default
value
NOTHING
Forthe "linkFieldType"parameter,supportedlinktypesare: LINK, LINKSETand LINKLIST.
Forthe "unresolvedLinkAction"parameterthefollowingactionsaresupported:
Action
Description
NOTHING
Tellsthetransformertodonothing.
CREATE
Tellsthetransformertocreatean ODocumentinstance,settingtheprimarykeyasthejoinvalue.
WARNING
Tellsthetransformertoincrementwarnings.
ERROR
Tellsthetransformertoincrementerrors.
HALT
Tellsthetransformertointerrupttheprocess.
SKIP
Tellsthetransformertoskipthecurrentrow.
Example
TransformaJSONvalueintoalinkwithinthecurrentrecord,setas parentofthetype LINK,withtheresultofthelookupon
theindex D.nodewiththevaluecontainedinthefield inode_parentontheinputdocument.
{"link":
{"linkFieldName":"parent",
"linkFieldType":"LINK",
"joinFieldName":"inode_parent",
"lookup":"D.inode",
"unresolvedLinkAction":"CREATE"
}
}
LogTransformer
WhentheETLmoduleusestheLogTransformer,itlogstheinputobjectto System.out.
Componentdescription.
Componentname:log
Supportedinputstypes:Any
Output:Any
S yntax
Parameter
Description
Type
"prefix"
Defineswhatitwritesbeforethecontent.
string
"postfix"
Defineswhatitwritesafterthecontent.
string
Mandatory
Defaultvalue
Examples
Logthecurrentvalue:
223
Transformers
{"log":{}}
Logthecurrntvaluewith ->astheprefix:
{"log":
{"prefix":"->"}
}
BlockTransformer
WhentheETLmodulecallstheBlockTransformer,itexecutesanETLBlockcomponentasatransformationstep.
Componentdescription.
Componentname:block
Supportedinputstypes:[Any]
Output:Any
S yntax
Parameter
Description
Definestheblocktoexecute.
"block"
Type
Mandatory
document
Defaultvalue
yes
Example
Logthecurrentvalue:
{"block":
{"let":
{"name":"id",
"value":"={eval('$input.amount*2')}"
}
}
}
CommandTransformer
WhentheETLmodulecallstheCommandTransformer,itexecutesthegivencommand.
Componentdescription.
Componentname:command
Supportedinputstypes:[ODocument]
Output:ODocument
S yntax
Parameter
Description
Type
"language"
Definesthecommandlanguage:SQLorGremlin.
string
"command"
Definesthecommandtoexecute.
string
Mandatory
Defaultvalue
sql
yes
Example
Executea SELECTandoutputanedge:
{"command":
{"command":"SELECTFROMEWHEREid=${edgeid}",
"output":"edge"
}
}
224
Transformers
225
Loaders
ETL-Loaders
WhentheETLmoduleexecutes,Loadershandlethesavingofrecords.Theyrunatthelaststageoftheprocess.TheETLmodulein
OrientDBsupportsthefollowingloaders:
Output
OrientDB
OutputLoader
WhentheETLmodulerunstheOutputLoader,itprintsthetransformerresultstotheconsoleoutput.Thisistheloaderthatrunsby
default.
Componentname:output
Acceptedinputclasses:[Object]
OrientDBLoader
WhentheETLmodulerunstheOrientDBLoader,itloadstherecordsandverticesfromthetransformersintotheOrientDBdatabase.
Componentname: orientdb
Acceptedinputclasses: [ODocument,OrientVertex]
S yntax
226
Loaders
Parameter
Description
Type
Default
value
Mandatory
"dbURL"
DefinesthedatabaseURL.
string
yes
"dbUser"
Definestheusername.
string
admin
"dbPassword"
Definestheuserpassword.
string
admin
"dbAutoCreate"
Defineswhetheritautomaticallycreatesthe
database,intheeventthatitdoesn'texist
already.
boolean
true
"dbAutoCreateProperties"
Defneswhetheritautomaticallycreates
propertiesintheschema.
boolean
false
"dbAutoDropIfExists"
Defineswhetheritautomaticallydropsthe
databaseifitexistsalready.
boolean
false
"tx"
Defineswhetheritusestransactions
boolean
false
"txUseLog"
Defineswhetherituseslogintransactions.
boolean
"wal"
Defineswhetherituseswriteaheadlogging.
Disabletoachievebetterperformance.
boolean
true
"batchCommit"
Whenusingtransactions,definesthebatch
ofentriesitcommits.Helpsavoidhaving
onelargetransactioninmemory.
integer
0
"dbType"
Definesthedatabasetype: graphor
document.
string
document
"class"
Definestheclasstouseinstoringnew
record.
string
"cluster"
Definestheclusterinwhichtostorethe
newrecord.
string
"classes"
Defineswhetheritcreatesclasses,ifnot
definedalreadyinthedatabase.
inner
document
"indexes"
DefinesindexestouseontheETLprocess.
Beforestarting,itcreatesanydeclared
indexesnotpresentinthedatabase.Indexes
musthave "type", "class"and
"fields".
inner
document
"useLightweightEdges"
Defineswhetheritchangesthedefault
settingforLightweightEdges.
boolean
false
"standardELementConstraints"
Defineswhetheritchangesthedefault
settingforTinkerPopBLueprint
constraints.Valuecannotbenullandyou
cannotuse idasapropertyname.
boolean
true
Forthe "txUseLog"parameter,whenWALisdisabledyoucanstillachievereliabletransactionsthroughthisparameter.Youmayfindit
usefultogroupmanyoperationsintoabatch,suchas CREATEEDGE.
Classes
Whenusingthe "classes"parameter,itdefinesaninnerdocumentthatcontainsadditionalconfigurationvariables.
Parameter
Description
Type
"name"
Definestheclassname.
string
"extends"
Definesthesuper-classname.
string
"clusters"
Definesthenumberofclustertocreateundertheclass.
integer
Mandatory
Defaultvalue
yes
1
NOTE:The "clusters"parameterwasintroducedinversion2.1.
227
Loaders
Indexes
Parameter
Description
Type
Mandatory
"name"
Definestheindexname.
string
"class"
Definestheclassnameinwhichtocreatetheindex.
string
yes
"type"
Definestheindextype.
string
yes
"fields"
Definesanarrayoffieldstoindex.Tospecifythefieldtype,usethe
syntax: <field>.<type>.
string
yes
"metadata"
Definesadditionalindexmetadata.
string
Default
value
Examples
Configurationtoloaddataintothedatabase dbpediaonOrientDB,inthedirectory /temp/databasesusingthePLocalprotocolanda
Graphdatabase.Theloadistransactional,performingcommitsinthousandinsertbatches.Itcreatestwolookupverticeswithindexes
againstthepropertystring URIinthebasevertexclass V.Theindexisunique.
"orientdb":{
"dbURL":"plocal:/temp/databases/dbpedia",
"dbUser":"importer",
"dbPassword":"IMP",
"dbAutoCreate":true,
"tx":false,
"batchCommit":1000,
"wal":false,
"dbType":"graph",
"classes":[
{"name":"Person","extends":"V"},
{"name":"Customer","extends":"Person","clusters":8}
],
"indexes":[
{"class":"V","fields":["URI:string"],"type":"UNIQUE"},
{"class":"Person","fields":["town:string"],"type":"NOTUNIQUE",
metadata:{"ignoreNullValues":false}
}
]
}
228
ImportthedatabaseofBeers
ImportDatabaseofBeersinOrientDB
First,createanewfoldersomewhereonyourharddrive.Forthistestwe'llassume /temp/openbeer.
$mkdir/temp/openbeer
DownloadBeersDatabaseinCSVformat
$curlhttp://openbeerdb.com/data_files/openbeerdb_csv.zip>openbeerdb_csv.zip
$unzipopenbeerdb_csv.zip
InstallOrientDB
$curl"http://orientdb.com/download.php?email=unknown@unknown.com&file=orientdb-community-2.0.9.zip&os=multi">orientdb-comm
unity-2.0.9.zip
$unziporientdb-community-2.0.9.zip
ImportBeerCategories
Thesearethefirst2linesof categories.csvfile:
"id","cat_name","last_mod"
"1","BritishAle","2010-10-2413:50:10"
InordertoimportthisfileinOrientDB,wehavetocreatethefollowingfileas 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"}
]
}
}
}
229
ImportthedatabaseofBeers
NowtoimportitintoOrientDB,moveintothe"bin"directoryofOrientDBdistribution.
$cdorientdb-community-2.0.9/bin
AndrunOrientDBETL.
$./oetl.sh/temp/openbeer/categories.json
OrientDBetlv.2.0.9(build@BUILD@)www.orientechnologies.com
BEGINETLPROCESSOR
ENDETLPROCESSOR
+extracted12rows(0rows/sec)-12rows->loaded11vertices(0vertices/sec)Totaltime:77ms[0warnings,0errors]
ImportBeerStyles
Nowlet'simporttheBeerStyles.Thesearethefirst2linesofthe styles.csvfile.
"id","cat_id","style_name","last_mod"
"1","1","ClassicEnglish-StylePaleAle","2010-10-2413:53:31"
Inthiscase,we'llcorrelatetheStylewiththeCategorycreatedearlier.Thisisthe styles.jsontousewithOrientDBETLforthenext
step.
{
"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"}
]
}
}
}
Nowimportthestyles.
$./oetl.sh/temp/openbeer/styles.json
OrientDBetlv.2.0.9(build@BUILD@)www.orientechnologies.com
BEGINETLPROCESSOR
ENDETLPROCESSOR
+extracted142rows(0rows/sec)-142rows->loaded141vertices(0vertices/sec)Totaltime:498ms[0warnings,0errors]
ImportBreweries
Nowit'stimefortheBreweries.Thesearethefirst2linesofthe breweries.csvfile.
"id","name","address1","address2","city","state","code","country","phone","website","filepath","descript","last_mod"
"1","(512)BrewingCompany","407Radam,F200",,"Austin","Texas","78745","UnitedStates","512.707.2337","http://512brewing.com/
",,"(512)BrewingCompanyisamicrobrewerylocatedintheheartofAustinthatbrewsforthecommunityusingasmanylocal,d
omesticandorganicingredientsaspossible.","2010-07-2220:00:20"
230
ImportthedatabaseofBeers
Brewerieshavenooutgoingrelationswithotherentities,sothisisaplainimportsimilartocategories.Thisisthe breweries.jsonto
usewithOrientDBETLforthenextstep.
{
"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"}
]
}
}
}
Runtheimportforbreweries.
$./oetl.sh/temp/openbeer/breweries.json
OrientDBetlv.2.0.9(build@BUILD@)www.orientechnologies.com
BEGINETLPROCESSOR
ENDETLPROCESSOR
+extracted1.395rows(0rows/sec)-1.395rows->loaded1.394vertices(0vertices/sec)Totaltime:830ms[0warnings,0er
rors]
ImportBeers
Nowit'stimeforthelastandmostimportantfile:theBeers!Thesearethefirst2linesofthe beers.csvfile.
"id","brewery_id","name","cat_id","style_id","abv","ibu","srm","upc","filepath","descript","last_mod",,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,
"1","812","HocusPocus","11","116","4.5","0","0","0",,"Ourtakeonaclassicsummerale.Atoasttoweeds,rays,andsummerh
aze.Alight,crispaleformowinglawns,hittinglazyflyballs,andcommuningwithnature,HocusPocusisofferedupasas
ummersacrificetoclodlessdays.
Asyoucanseeeachbeerisconnectedtootherentitiesthroughthefollowingfields:
brewery_id->Brewery
cat_id->Category
style_id->S tyle
Thisisthe breweries.jsontousewithOrientDBETLforthenextstep.
231
ImportthedatabaseofBeers
{
"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"}
]
}
}
}
Runthefinalimportforbeers.
$./oetl.sh/temp/openbeer/beers.json
OrientDBetlv.2.0.9(build@BUILD@)www.orientechnologies.com
BEGINETLPROCESSOR
...
+extracted5.862rows(1.041rows/sec)-5.862rows->loaded4.332vertices(929vertices/sec)Totaltime:10801ms[0warnin
gs,27errors]
ENDETLPROCESSOR
_Note:27errorsareduetothe27wrongcontentlinesthathavenoid.
Thisdatabaseisavailableonline.Installitwith:
Studio:intheloginpagepressthe"Cloud"button,putserver'scredentialandpressondownloadbuttonon"OpenBeer"line
Downloaditmanuallyfromhttp://orientdb.com/public-databases/OpenBeer.zipandunzipitinaOpenBeerfolderinside
OrientDB'sserver"databases"directory
232
ImportfromCSVtoaGraph
ImportfromaCSVfiletoaGraph
ThisexampledescribestheprocessforimportingfromaCSVfileintoOrientDBasaGraph.Forthesakeofsimplicity,consideronly
these2entities:
POST
COM M ENT
AlsoconsidertherelationshipbetweenPostandCommentasOne-2-M any.OnePostcanhavemultipleComments.We'rerepresenting
themastheywouldappearinanRDBM S,butthesourcecouldbeanything.
WithanRDBM SPostandCommentwouldbestoredin2separatetables:
TABLEPOST:
+----+----------------+
|id|title|
+----+----------------+
|10|NoSQLmovement|
|20|NewOrientDB|
+----+----------------+
TABLECOMMENT:
+----+--------+--------------+
|id|postId|text|
+----+--------+--------------+
|0|10|First|
|1|10|Second|
|21|10|Another|
|41|20|Firstagain|
|82|20|SecondAgain|
+----+--------+--------------+
WithanRDBM S,one-2-manyreferencesareinvertedfromthetargettable(Comment)tothesourceone(Post).Thisisduetothe
inabilityofanRDBM Stohandleacollectionofvalues.
Incomparison,usingtheOrientDBGraphmodel,relationshipsaremodeledasyouwouldthink,whenyoudesignanapplication:
POSTshaveedgestoCOM M ENTs.
So,withanRDBM Syouhave:
TablePOST<-(foreignkey)TableCOMMENT
WithOrientDB,theGraphmodelusesEdgestomanagerelationships:
ClassPOST->*(collectionofedges)ClassCOMMENT
(1)ExporttoCSV
Ifyou'reusinganRDBM Soranyothersource,exportyourdatainCSVformat.TheETLmoduleisalsoabletoextractfromJSONand
anRDBM SdirectlythroughJDBCdrivers.However,forthesakeofsimplicity,inthisexamplewe'regoingtouseCSVasthesource
format.
Considerhaving2CSVfiles:
Fileposts.csv
posts.csvfile,containingalltheposts
id,title
10,NoSQLmovement
20,NewOrientDB
233
ImportfromCSVtoaGraph
Filecomments.csv
comments.csvfile,containingallthecomments,withtherelationshiptothecommentedpost
id,postId,text
0,10,First
1,10,Second
21,10,Another
41,20,Firstagain
82,20,SecondAgain
(2)ETLConfiguration
TheOrientDBETLtoolrequiresonlyaJSONfiletodefinetheETLprocessasExtractor,alistofTransformerstobeexecutedinthe
pipeline,andaLoader,toloadgraphelementsintotheOrientDBdatabase.
Beloware2filescontainingtheETLtoimportPostsandCommentsseparately.
post.jsonETLfile
{
"source":{"file":{"path":"/temp/datasets/posts.csv"}},
"extractor":{"csv":{}},
"transformers":[
{"vertex":{"class":"Post"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/blog",
"dbType":"graph",
"classes":[
{"name":"Post","extends":"V"},
{"name":"Comment","extends":"V"},
{"name":"HasComments","extends":"E"}
],"indexes":[
{"class":"Post","fields":["id:integer"],"type":"UNIQUE"}
]
}
}
}
TheLoadercontainsalltheinformationtoconnecttoanOrientDBdatabase.Wehaveusedaplocaldatabase,becauseit'sfaster.
However,ifyouhaveanOrientDBserverup&running,use"remote:"instead.NotetheclassesandindexesdeclaredintheLoader.As
soonastheLoaderisconfigured,theclassesandindexesarecreated,iftheydonotalreadyexist.Wehavecreatedtheindexonthe
Post.idfieldtoassurethattherearenoduplicatesandthatthelookuponthecreatededges(seebelow)willbefastenough.
comments.jsonETLfile
234
ImportfromCSVtoaGraph
{
"source":{"file":{"path":"/temp/datasets/comments.csv"}},
"extractor":{"csv":{}},
"transformers":[
{"vertex":{"class":"Comment"}},
{"edge":{"class":"HasComments",
"joinFieldName":"postId",
"lookup":"Post.id",
"direction":"in"
}
}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/blog",
"dbType":"graph",
"classes":[
{"name":"Post","extends":"V"},
{"name":"Comment","extends":"V"},
{"name":"HasComments","extends":"E"}
],"indexes":[
{"class":"Post","fields":["id:integer"],"type":"UNIQUE"}
]
}
}
}
Thisfileissimilartothepreviousone,buttheEdgetransformerdoesthejob.SincethelinkfoundintheCSVgoesintheopposite
direction(Comment->Post),whilewewanttomodeldirectly(Post->Comment),weusedthedirection"in"(defaultisalways"out").
(3)RuntheETLprocess
NowallowtheETLtorunbyexecutingbothimportsinsequence.OpenashellundertheOrientDBhomedirectory,andexecutethe
followingsteps:
$cdbin
$./oetl.shpost.json
$./oetl.shcomment.json
Oncebothscriptsexecutesuccessfully,you'llhaveyourBlogimportedintoOrientDBasaGraph!
(4)Checkthedatabase
OpenthedatabaseundertheOrientDBconsoleandexecutethefollowingcommandstocheckthattheimportisok:
235
ImportfromCSVtoaGraph
$./console.sh
OrientDBconsolev.2.0-SNAPSHOT(build2565)www.orientechnologies.com
Type'help'todisplayallthesupportedcommands.
InstallingextensionsforGREMLINlanguagev.2.6.0
orientdb>connectplocal:/temp/databases/blogadminadmin
Connectingtodatabase[plocal:/temp/databases/blog]withuser'admin'...OK
orientdb{db=blog}>selectexpand(out())fromPostwhereid=10
----+-----+-------+----+------+-------+-------------#|@RID|@CLASS|id|postId|text|in_HasComments
----+-----+-------+----+------+-------+-------------0|#12:0|Comment|0|10|First|[size=1]
1|#12:1|Comment|1|10|Second|[size=1]
2|#12:2|Comment|21|10|Another|[size=1]
----+-----+-------+----+------+-------+-------------3item(s)found.Queryexecutedin0.002sec(s).
orientdb{db=blog}>selectexpand(out())fromPostwhereid=20
----+-----+-------+----+------+------------+-------------#|@RID|@CLASS|id|postId|text|in_HasComments
----+-----+-------+----+------+------------+-------------0|#12:3|Comment|41|20|Firstagain|[size=1]
1|#12:4|Comment|82|20|SecondAgain|[size=1]
----+-----+-------+----+------+------------+-------------2item(s)found.Queryexecutedin0.001sec(s).
236
Importatreestructure
Importatreestructure
IfyouhaveatreestructureinanRDBM SorCSVfileandyouwanttoimportitinOrientDB,theETLcancometoyourrescue.Inthis
example,weuseCSVforthesakeofsimplicity,butit'sthesamewithJDBCinputandaSQLqueryagainstanRDBM S.
source.csv
ID,PARENT_ID,LAST_YEAR_INCOME,DATE_OF_BIRTH,STATE
0,-1,10000,1990-08-11,Arizona
1,0,12234,1976-11-07,Missouri
2,0,21322,1978-01-01,Minnesota
3,0,33333,1960-05-05,Iowa
etl.json
{
"source":{"file":{"path":"source.csv"}},
"extractor":{"row":{}},
"transformers":[
{"csv":{}},
{"vertex":{"class":"User"}},
{"edge":{
"class":"ParentOf",
"joinFieldName":"PARENT_ID",
"direction":"in",
"lookup":"User.ID",
"unresolvedLinkAction":"SKIP"
}
}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/mydb",
"dbType":"graph",
"classes":[
{"name":"User","extends":"V"},
{"name":"ParentOf","extends":"E"}
],"indexes":[
{"class":"User","fields":["ID:Long"],"type":"UNIQUE"}
]
}
}
}
237
ImportfromJSON
ImportformJSON
IfyouaremigratingfromM ongoDBoranyotherDBM SthatexportsdatainJSONformat,theJSONextractoriswhatyouneed.For
moreinformationlookalsoat:Import-from-PARSE.
Thisistheinputfilestoredin /tmp/database.jsonfile:
[
{
"name":"Joe",
"id":1,
"friends":[2,4,5],
"enemies":[6]
},
{
"name":"Suzie",
"id":2,
"friends":[1,4,6],
"enemies":[5,2]
}
]
Notethat friendsand enemiesrepresentrelationshipswithnodesofthesametype.TheyareintheformofanarrayofIDs.Thisis
whatweneed:
UsetheVertexclass"Account"tostorenodes
UsetheEdgeclasses"Friend"and"Enemy"toconnectvertices
M ergeandLookupswillbeon idpropertyofAccountclassthatwillbeunique
Incasetheconnectedfriendhasn'tbeeninsertedyet,createit("unresolvedLinkAction":"CREATE")
Tospeeduplookups,auniqueindexwillbecreatedon Account.it
Andthispipeline(logisat debugleveltoshowallthemessages):
238
ImportfromJSON
{
"config":{
"log":"debug"
},
"source":{
"file":{"path":"/tmp/database.json"}
},
"extractor":{
"json":{}
},
"transformers":[
{"merge":{"joinFieldName":"id","lookup":"Account.id"}},
{"vertex":{"class":"Account"}},
{"edge":{
"class":"Friend",
"joinFieldName":"friends",
"lookup":"Account.id",
"unresolvedLinkAction":"CREATE"
}},
{"edge":{
"class":"Enemy",
"joinFieldName":"enemies",
"lookup":"Account.id",
"unresolvedLinkAction":"CREATE"
}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/tmp/databases/db",
"dbUser":"admin",
"dbPassword":"admin",
"dbAutoDropIfExists":true,
"dbAutoCreate":true,
"standardElementConstraints":false,
"tx":false,
"wal":false,
"batchCommit":1000,
"dbType":"graph",
"classes":[{"name":"Account","extends":"V"},{"name":"Friend","extends":"E"},{"name":'Enemy',"extends":"E"}],
"indexes":[{"class":"Account","fields":["id:integer"],"type":"UNIQUE_HASH_INDEX"}]
}
}
}
Notealsothesetting
"standardElementConstraints":false,
Thisisneeded,inordertoallowimportingtheproperty"id"intheOrientDBLoader.Withoutthisoption,theBlueprintsstandard
wouldrejectit,because"id"isareservedname.
ByexecutingtheETLprocess,thisistheoutput:
239
ImportfromJSON
OrientDBetlv.2.1-SNAPSHOTwww.orientechnologies.com
feb09,20152:46:42AMcom.orientechnologies.common.log.OLogManagerlog
INFORMAZIONI:OrientDBauto-configDISKCACHE=10.695MB(heap=3.641MBos=16.384MBdisk=42.205MB)
[orientdb]INFODroppingexistentdatabase'plocal:/tmp/databases/db'...
BEGINETLPROCESSOR
[file]DEBUGReadingfromfile/tmp/database.json
[orientdb]DEBUG-OrientDBLoader:createdvertexclass'Account'extends'V'
[orientdb]DEBUGorientdb:found0verticesinclass'null'
[orientdb]DEBUG-OrientDBLoader:creatededgeclass'Friend'extends'E'
[orientdb]DEBUGorientdb:found0verticesinclass'null'
[orientdb]DEBUG-OrientDBLoader:creatededgeclass'Enemy'extends'E'
[orientdb]DEBUGorientdb:found0verticesinclass'null'
[orientdb]DEBUG-OrientDBLoader:createdproperty'Account.id'oftype:integer
[orientdb]DEBUG-OrientDocumentLoader:createdindex'Account.id'type'UNIQUE_HASH_INDEX'againstClass'Account',fields[
id:integer]
[0:merge]DEBUGTransformerinput:{name:Joe,id:1,friends:[3],enemies:[1]}
[0:merge]DEBUGjoinValue=1,lookupResult=null
[0:merge]DEBUGTransformeroutput:{name:Joe,id:1,friends:[3],enemies:[1]}
[0:vertex]DEBUGTransformerinput:{name:Joe,id:1,friends:[3],enemies:[1]}
[0:vertex]DEBUGTransformeroutput:v(Account)[#11:0]
[0:edge]DEBUGTransformerinput:v(Account)[#11:0]
[0:edge]DEBUGjoinCurrentValue=2,lookupResult=null
[0:edge]DEBUGcreatednewvertex=Account#11:1{id:2}v1
[0:edge]DEBUGcreatednewedge=e[#12:0][#11:0-Friend->#11:1]
[0:edge]DEBUGjoinCurrentValue=4,lookupResult=null
[0:edge]DEBUGcreatednewvertex=Account#11:2{id:4}v1
[0:edge]DEBUGcreatednewedge=e[#12:1][#11:0-Friend->#11:2]
[0:edge]DEBUGjoinCurrentValue=5,lookupResult=null
[0:edge]DEBUGcreatednewvertex=Account#11:3{id:5}v1
[0:edge]DEBUGcreatednewedge=e[#12:2][#11:0-Friend->#11:3]
[0:edge]DEBUGTransformeroutput:v(Account)[#11:0]
[0:edge]DEBUGTransformerinput:v(Account)[#11:0]
[0:edge]DEBUGjoinCurrentValue=6,lookupResult=null
[0:edge]DEBUGcreatednewvertex=Account#11:4{id:6}v1
[0:edge]DEBUGcreatednewedge=e[#13:0][#11:0-Enemy->#11:4]
[0:edge]DEBUGTransformeroutput:v(Account)[#11:0]
[1:merge]DEBUGTransformerinput:{name:Suzie,id:2,friends:[3],enemies:[2]}
[1:merge]DEBUGjoinValue=2,lookupResult=Account#11:1{id:2,in_Friend:[#12:0]}v2
[1:merge]DEBUGmergedrecordAccount#11:1{id:2,in_Friend:[#12:0],name:Suzie,friends:[3],enemies:[2]}v2withfoundrecord={na
me:Suzie,id:2,friends:[3],enemies:[2]}
[1:merge]DEBUGTransformeroutput:Account#11:1{id:2,in_Friend:[#12:0],name:Suzie,friends:[3],enemies:[2]}v2
[1:vertex]DEBUGTransformerinput:Account#11:1{id:2,in_Friend:[#12:0],name:Suzie,friends:[3],enemies:[2]}v2
[1:vertex]DEBUGTransformeroutput:v(Account)[#11:1]
[1:edge]DEBUGTransformerinput:v(Account)[#11:1]
[1:edge]DEBUGjoinCurrentValue=1,lookupResult=Account#11:0{name:Joe,id:1,friends:[3],enemies:[1],out_Friend:[#12:0,#12:1,#
12:2],out_Enemy:[#13:0]}v5
[1:edge]DEBUGcreatednewedge=e[#12:3][#11:1-Friend->#11:0]
[1:edge]DEBUGjoinCurrentValue=4,lookupResult=Account#11:2{id:4,in_Friend:[#12:1]}v2
[1:edge]DEBUGcreatednewedge=e[#12:4][#11:1-Friend->#11:2]
[1:edge]DEBUGjoinCurrentValue=6,lookupResult=Account#11:4{id:6,in_Enemy:[#13:0]}v2
[1:edge]DEBUGcreatednewedge=e[#12:5][#11:1-Friend->#11:4]
[1:edge]DEBUGTransformeroutput:v(Account)[#11:1]
[1:edge]DEBUGTransformerinput:v(Account)[#11:1]
[1:edge]DEBUGjoinCurrentValue=5,lookupResult=Account#11:3{id:5,in_Friend:[#12:2]}v2
[1:edge]DEBUGcreatednewedge=e[#13:1][#11:1-Enemy->#11:3]
[1:edge]DEBUGjoinCurrentValue=2,lookupResult=Account#11:1{id:2,in_Friend:[#12:0],name:Suzie,friends:[3],enemies:[2],out_Fri
end:[#12:3,#12:4,#12:5],out_Enemy:[#13:1]}v6
[1:edge]DEBUGcreatednewedge=e[#13:2][#11:1-Enemy->#11:1]
[1:edge]DEBUGTransformeroutput:v(Account)[#11:1]
ENDETLPROCESSOR
+extracted2entries(0entries/sec)-2entries->loaded2vertices(0vertices/sec)Totaltime:228ms[0warnings,0error
s]
Onceready,let'sopenthedatabasewithStudioandthisistheresult:
240
ImportfromJSON
241
ImportfromRDBM S
ETL-ImportfromRDBMS
M ostofDBM SssupportJDBCdriver.AllyouneedistogathertheJDBCdriverandputitinclasspathorsimplyinthe
$ORIENTDB_HOM E/libdirectory.
Withtheconfigurationbelowalltherecordsfromthetable"Client"areimportedinOrientDBfromM ySQLdatabase.
Exampleimportingaflattable
{
"config":{
"log":"debug"
},
"extractor":{
"jdbc":{"driver":"com.mysql.jdbc.Driver",
"url":"jdbc:mysql://localhost/mysqlcrm",
"userName":"root",
"userPassword":"",
"query":"select*fromClient"}
},
"transformers":[
{"vertex":{"class":"Client"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/orientdbcrm",
"dbAutoCreate":true
}
}
}
Exampleloadingrecordsfrom2connectedtables
WiththisexamplewewanttoimportadatabasethatcontainsBlogpostsinthefollowingtables:
Authors,inTABLEAuthor,withthefollowingcolumns:idandname
Posts,inTABLEPost,withthefollowingcolumns:author_id,titleandtext
ToimportthemintoOrientDBwe'dneed2ETLprocesses.
ImportingofAuthors
{
"config":{
"log":"debug"
},
"extractor":{
"jdbc":{"driver":"com.mysql.jdbc.Driver",
"url":"jdbc:mysql://localhost/mysql",
"userName":"root",
"userPassword":"",
"query":"select*fromAuthor"}
},
"transformers":[
{"vertex":{"class":"Author"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/orientdb",
"dbAutoCreate":true
}
}
}
242
ImportfromRDBM S
ImportingofPosts
{
"config":{
"log":"debug"
},
"extractor":{
"jdbc":{"driver":"com.mysql.jdbc.Driver",
"url":"jdbc:mysql://localhost/mysql",
"userName":"root",
"userPassword":"",
"query":"select*fromPost"}
},
"transformers":[
{"vertex":{"class":"Post"}},
{"edge":{"class":"Wrote","direction":"in",
"joinFieldName":"author_id",
"lookup":"Author.id","unresolvedLinkAction":"CREATE"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/orientdb",
"dbAutoCreate":true
}
}
}
Notetheedgeconfigurationhasthedirectionas"in",thatmeansstartsfromtheAuthorandfinishestoPost.
243
ImportfromDB-Pedia
ImportfromDB-Pedia
DBPediaexportsalltheentitiesasGZippedCSVfiles.Features:
Firstlinecontainscolumnnames,second,thirdandforthhasmetainformation,whichwe'llskip(lookat "skipFrom":1,"skipTo":
3inCSVtransformer)
Thevertexclassnameiscreatedautomaticallybasedonthefilename,sowecanusethesamefileagainstanyDBPediafile
ThePrimaryKeyisthe"URI"field,whereaUNIQUEindexhasalsobeencreated(referto"ORIENTDB"loader)
The"merge"transformerisusedtoallowtore-importorupdateanyfilewithoutgeneratingduplicates
Configuration
{
"config":{
"log":"debug",
"fileDirectory":"/temp/databases/dbpedia_csv/",
"fileName":"Person.csv.gz"
},
"begin":[
{"let":{"name":"$filePath","value":"$fileDirectory.append($fileName)"}},
{"let":{"name":"$className","value":"$fileName.substring(0,$fileName.indexOf('.'))"}}
],
"source":{
"file":{"path":"$filePath","lock":true}
},
"extractor":{
{"csv":{"separator":",","nullValue":"NULL","skipFrom":1,"skipTo":3}},
},
"transformers":[
{"merge":{"joinFieldName":"URI","lookup":"V.URI"}},
{"vertex":{"class":"$className"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/dbpedia",
"dbUser":"admin",
"dbPassword":"admin",
"dbAutoCreate":true,
"tx":false,
"batchCommit":1000,
"dbType":"graph",
"indexes":[{"class":"V","fields":["URI:string"],"type":"UNIQUE"}]
}
}
}
244
ImportfromParse(Facebook)
ImportfromParse
ParseisaverypopularBaaS(BackendasaService),acquiredbyFacebook.ParseusesM ongoDBasadatabaseandallowstoexportthe
databaseinJSONformat.TheformatisanarrayofJSONobjects.Example:
[
{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"Ldlskf4mfS"
},
"address":{
"__type":"Pointer",
"className":"Address",
"objectId":"lvkDfj4dmS"
},
"createdAt":"2013-11-15T18:15:59.336Z",
"updatedAt":"2014-02-27T23:47:00.440Z",
"objectId":"Ldk39fDkcj",
"ACL":{
"Lfo33mfDkf":{
"write":true
},
"*":{
"read":true
}
}
},{
"user":{
"__type":"Pointer",
"className":"_User",
"objectId":"Lflfem3mFe"
},
"address":{
"__type":"Pointer",
"className":"Address",
"objectId":"Ldldjfj3dd"
},
"createdAt":"2014-01-01T18:04:02.321Z",
"updatedAt":"2014-01-23T20:12:23.948Z",
"objectId":"fkfj49fjFFN",
"ACL":{
"dlfnDJckss":{
"write":true
},
"*":{
"read":true
}
}
}
]
Notes:
Eachobjecthasitsown objectIdthatidentifiestheobjectintheentiredatabase.
Parsehastheconceptof class,likeOrientDB.
LinksaresimilartoOrientDBRID(butitrequiresacostlyJOINtobetraversed),butmadeasanembeddedobjectcontaining:
classNameastargetclassname
objectIdastargetobjectId
ParsehasACLatrecordlevel,likeOrientDB.
InordertoimportaPARSEfile,youneedtocreatetheETLconfigurationusingJSONasExtractor.
Example
245
ImportfromParse(Facebook)
Inthisexample,we'regoingtoimportthefileextractedfromParsecontainingalltherecordsofthe userclass.Notethecreationofthe
class UserinOrientDB,whichextends V(BaseVertexclass).Wecreatedanindexagainstproperty User.objectIdtousethesame
ID,similartoParse.IfyouexecutethisETLimportmultipletimes,therecordsinOrientDBwillbeupdatedthankstothe merge
feature.
{
"config":{
"log":"debug"
},
"source":{
"file":{"path":"/temp/parse-user.json","lock":true}
},
"extractor":{
"json":{}
},
"transformers":[
{"merge":{"joinFieldName":"objectId","lookup":"User.objectId"}},
{"vertex":{"class":"User"}}
],
"loader":{
"orientdb":{
"dbURL":"plocal:/temp/databases/parse",
"dbUser":"admin",
"dbPassword":"admin",
"dbAutoCreate":true,
"tx":false,
"batchCommit":1000,
"dbType":"graph",
"classes":[
{"name":"User","extends":"V"}
],
"indexes":[
{"class":"User","fields":["objectId:string"],"type":"UNIQUE_HASH_INDEX"}
]
}
}
}
Seealso:
ImportfromJSON.
246
Logging
Logging
OrientDBhandleslogsusingtheJavaLoggingFramework,whichisbundledwiththeJVM .Thespecificformatitusesderivesfromthe
OLogFormatterclass,whichdefaultsto:
<date><level><message>[<requester>]
<date>Showsthedateofthelogentry,usingthedateformat YYYY-MM-DDHH:MM:SS:SSS.
<level>Showstheloglevel.
<message>Showsthelogmessage.
<class>ShowstheJavaclassthatmadetheentry,(optional).
ThesupportedlevelsarethosecontainedintheJREclass java.util.logging.Level.Fromhighesttolowest:
SEVERE
WARNING
INFO
CONFIG
FINE
FINER
FINEST
Bydefault,OrientDBinstallstwologgers:
console:Logstotheshellorcommand-promptthatstartstheapplicationortheserver.Youcanmodifyitbysettingthe
log.console.levelvariable.
file:Logstothelogfile.Youcanmodifyitbysettingthe log.file.levelvariable.
ConfigurationFile
YoucanconfigureloggingstrategiesandpoliciesbycreatingaconfigurationfilethatfollowstheJavaLoggingM essagesconfiguration
syntax.Forexample,considerthefollowingfromthe orientdb-server-log.propertiesfile:
#Specifythehandlerstocreateintherootlogger
#(allloggersarechildrenoftherootlogger)
#Thefollowingcreatestwohandlers
handlers=java.util.logging.ConsoleHandler,java.util.logging.FileHandler
#Setthedefaultlogginglevelfortherootlogger
.level=ALL
#SetthedefaultlogginglevelfornewConsoleHandlerinstances
java.util.logging.ConsoleHandler.level=INFO
#SetthedefaultformatterfornewConsoleHandlerinstances
java.util.logging.ConsoleHandler.formatter=com.orientechnologies.common.log.OLogFormatter
#SetthedefaultlogginglevelfornewFileHandlerinstances
java.util.logging.FileHandler.level=INFO
#Namingstylefortheoutputfile
java.util.logging.FileHandler.pattern=../log/orient-server.log
#SetthedefaultformatterfornewFileHandlerinstances
java.util.logging.FileHandler.formatter=com.orientechnologies.common.log.OLogFormatter
#Limitingsizeofoutputfileinbytes:
java.util.logging.FileHandler.limit=10000000
#Numberofoutputfilestocyclethrough,byappendingan
#integertothebasefilename:
java.util.logging.FileHandler.count=10
Whenthelogpropertiesfileisready,youneedtotelltheJVM touset,bysetting java.util.logging.config.filesystemproperty.
247
Logging
$java-Djava.util.logging.config.file=mylog.properties
SettingtheLogLevel
Tochangetheloglevelwithoutmodifyingtheloggingconfiguration,setthe log.console.leveland log.file.levelsystemvariables.
Thesesystemvariablesareaccessiblebothatstartupandatruntime.
ConfiguringLogLevelatStartup
Youcanconfigureloglevelatstartupthroughboththe orientdb-server-config.xmlconfigurationfileandbymodifyingtheJVM
beforeyoustarttheserver:
UsingtheConfigurationFile
Toconfigureloglevelfromtheconfigurationfile,updatethefollowingelementsinthe <properties>section:
<properties>
<entryvalue="info"name="log.console.level"/>
<entryvalue="fine"name="log.file.level"/>
...
</properties>
UsingtheJVM
ToconfigureloglevelfromtheJVM beforestartingtheserver,runthe javacommandtoconfigurethe log.console.leveland
log.file.levelvariables:
$java-Dlog.console.level=INFO-Dlog.file.level=FINE
ConfiguringLogLevelatRuntime
YoucanconfigureloglevelatruntimethroughboththeJavaAPIandbyexecutinganHTTP POSTagainsttheremoteserver.
UsingJavaCode
ThroughtheJavaAPI,youcansetthesystemvariablesforloggingatstartupthroughthe System.setProperty()method.Forinstance,
publicvoidmain(String[]args){
System.setProperty("log.console.level","FINE");
...
}
UsingHTTPPOST
ThroughtheHTTPrequests,youcanupdatetheloggingsystemvariablesbyexecutinga POSTagainsttheURL: /server/log.
<type>/<level>.
<type>Definesthelogtype: consoleor file.
<level>Definestheloglevel.
Examples
TheexamplesbelowusecURLtoexecutetheHTTP POSTcommandsagainsttheOrientDBserver.Itusestheserver rootuserand
password.
Enablethefinesttracingleveltotheconsole:
248
Logging
$curl-uroot:root-XPOSThttp://localhost:2480/server/log.console/FINEST
Enablethefinesttracingleveltofile:
$curl-uroot:root-XPOSThttp://localhost:2480/server/log.file/FINEST
InstallLogFormatter
OrientDBServerusesitsownlogformatter.Inordertoenablethesameforyourapplication,youneedtoincludethefollowingline:
OLogManager.installCustomFormatter();
TheServerautomaticallyinstallsthelogformatter.Todisableit,use orientdb.installCustomFormatter.
$java-Dorientdb.installCustomFormatter=false
249
Studio
StudioHomepage
StudioisawebinterfacefortheadministrationofOrientDBthatcomesinbundlewiththeOrientDBdistribution.
IfyourunOrientDBinyourmachinethewebinterfacecanbeaccessedviatheURL:
http://localhost:2480
ThisisthenewStudio2.0Homepage.
Fromhere,youcan:
Connecttoanexistingdatabase
Dropanexistingdatabase
Createanewdatabase
Importapublicdatabase
GototheServerM anagementUI
Connecttoanexistingdatabase
ToLogin,selectadatabasefromthedatabaseslistanduseanydatabaseuser.Bydefaultreader/readercanreadrecordsfromthe
database,writer/writercanread,create,updateanddeleterecords.admin/adminhasallrights.
Dropanexistingdatabase
Selectadatabasefromthedatabaseslistandclickthetrashicon.Studiowillopenaconfirmationpopupwhereyouhavetoinsert
ServerUser
ServerPassword
andthenclickthe"Dropdatabase"button.Youcanfindtheservercredentialsinthe$ORIENTDB_HOM E/config/orientdb-serverconfig.xmlfile:
<users>
<username="root"password="pwd"resources="*"/>
</users>
250
Studio
Createanewdatabase
Tocreateanewdatabase,clickthe"NewDB"buttonfromtheHomePage
Someinformationisneededtocreateanewdatabase:
Databasename
Databasetype(Document/Graph)
Storagetype(plocal/memory)
Serveruser
Serverpassword
Youcanfindtheservercredentialsinthe$ORIENTDB_HOM E/config/orientdb-server-config.xmlfile:
<users>
<username="root"password="pwd"resources="*"/>
</users>
Oncecreated,Studiowillautomaticallylogintothenewdatabase.
Importapublicdatabase
Studio2.0allowsyoutoimportdatabasesfromapublicrepository.Thesedatabasescontainspublicdataandbookmarkedqueriesthat
willallowyoutostartplayingwithOrientDBandOrientDBSQL.Theclassicbundledatabase'GratefulDeadConcerts'willbemovedto
thispublicrepository.
251
Studio
Toinstallapublicdatabase,youwillneedtheServerCredentials.Then,clickthedownloadbuttonofthedatabasethatyouare
interestedin.ThenStudiowilldownloadandinstallintoyour$ORIENTDB_HOM E/databasesdirectory.Oncefinished,Studiowill
automaticallylogintothenewlyinstalleddatabase.
252
Query
Executeaquery
Studiosupportsautorecognitionofthelanguageyou'reusingbetweenthosesupported:SQLandGremlin.Whilewriting,usetheautocompletefeaturebypressingCtrl+Space.
Othershortcutsareavailableinthequeryeditor:
Ctrl+ReturntoexecutethequeryorjustclicktheRunbutton
Ctrl/Cmd+Ztoundochanges
Ctrl/Cmd+S hift+Ztoredochanges
Ctrl/Cmd+Ftosearchintheeditor
Ctrl/Cmd+/totoggleacomment
Note:Ifyouhavemultiplequeriesintheeditor,youcanselectasinglequerywithtextselectionandexecuteitwithCtrl+
ReturnortheRunbutton
Byclickingany@ridvalueintheresultset,youwillgointodocumenteditmodeiftherecordisaDocument,otherwiseyouwillgointo
vertexedit.
Youcanbookmarkyourqueriesbyclickingthestariconintheresultssetorintheeditor.Tobrowsebookmarkedqueries,clickthe
Bookmarksbutton.Studiowillopenthebookmarkslistontheleft,whereyoucanedit/deleteorrerunqueries.
253
Query
StudiosavestheexecutedqueriesintheLocalStorageofthebrowser,inthequerysettings,youcanconfigurehowmanyqueriesstudio
willkeepinhistory.Youcanalsosearchapreviouslyexecutedquery,deleteallthequeriesfromthehistoryordeleteasinglequery.
FromStudio2.0,youcansendtheresultsetofaquerytotheGraphEditorbyclickingonthecircleiconintheresultsetactions.This
allowsyoutovisualizeyourdatagraphically.
LookattheJSONoutput
StudiocommunicateswiththeOrientDBServerusingHTTP/RESt+JSONprotocol.ToseetheoutputinJSONformat,presstheRAW
tab.
254
EditDocument
EditDocument
255
EditVertex
EditVertex
256
Schema
SchemaManager
OrientDBcanworkinschema-lessmode,schemamodeoramixofboth.Herewe'lldiscusstheschemamode.Toknowmoreabout
schemainOrientDBgohere
Hereyoucan:
BrowsealltheClassesofyourdatabase
CreateanewClass
Rename/DropaClass
ChangetheclusterselectionforaClass
Editaclassbyclickingonaclassrowinthetable
Viewallindexescreated
CreateanewClass
TocreateanewClass,justclicktheNewClassbutton.Someinformationisrequiredtocreatethenewclass.
Name
SuperClass
Alias(Optional)
Abstract
257
Schema
HereyoucanfindmoreinformationaboutClasses
Viewallindexes
Whenyouwanttohaveanoverviewofallindexescreatedinyourdatabase,justclicktheAllindexesbuttonintheSchemaUI.This
willprovidequickaccesstosomeinformationaboutindexes(name,type,properties,etc)andyoucandroporrebuildthemfromhere.
258
Class
ClassEdit
Property
AddProperty
Indexes
Createnewindex
259
Class
260
GraphEditor
GraphEditor
SinceStudio2.0wehaveanewbrandgrapheditor.Notonlyyoucanvisualizeyourdatainagraphwaybutyoucanalsointeractwith
thegraphandmodifyit.
TopopulatethegraphareajusttypeaqueryinthequeryeditororusethefunctionalityS endToGraphfromtheBrowseUI
SupportedoperationsintheGraphEditorare:
AddVertices
SavetheGraphRenderingConfiguration
CleartheGraphRenderingCanvas
DeleteVertices
RemoveVerticesfromCanvas
EditVertices
InspectVertices
ChangetheRenderingConfigurationofVertices
NavigatingRelationships
CreateEdgesbetweenVertices
DeleteEdgesbetweenVertices
InspectEdges
EditEdges
AddVertices
ToaddanewVertexinyourGraphDatabaseandintheGraphCanvasareayouhavetopressthebuttonAddVertex.Thisoperationis
doneintwosteps.
ThefirststepyouhavetochoosetheclassforthenewVertexandthenclickNext
261
GraphEditor
Inthesecondstepyouhavetoinsertthefieldsvaluesofthenewvertex,youcanalsoaddcustomfieldsasOrientDBsupportsSchemaLessmode.TomakethenewvertexpersistentclicktoS avechangesandthevertexwillbesavedintothedatabaseandaddedtothe
canvasarea
DeleteVertices
OpenthecircularmenubyclickingontheVertexthatyouwanttodelete,openthesub-menubypassinghoverthemousetothemenu
entrymore(...)andthenclickthetrashicon.
RemoveVerticesfromCanvas
Openthecircularmenu,openthesub-menubypassinghoverthemousetothemenuentrymore(...)andthenclicktheerasericon.
EditVertices
262
GraphEditor
Openthecircularmenuandthenclicktotheediticon,Studiowillopenapopupwhereyoucaneditthevertexproperties.
InspectVertices
IfyouwanttotakeaquicklooktotheVertexproperty,clicktotheeyeicon.
ChangetheRenderingConfigurationofVertices
NavigatingRelationships
CreateEdgesbetweenVertices
DeleteEdgesbetweenVertices
263
GraphEditor
InspectEdges
EditEdges
264
Functions
Functions
OrientDBallowstoextendtheSQLlanguagebyprovidingFunctions.Functionscanbeusedalsotocreatedata-drivenmicroservices.
FormoreinformationlookatFunctions.
265
Security
Security
Studio2.0includesthenewSecurityM anagementwhereyoucanmanageUsersandRolesinagraphicalway.Fordetailedinformation
aboutSecurityinOrientDB,visithere
Users
Hereyoucanmanagethedatabaseusers:
SearchUsers
AddUsers
DeleteUsers
EditUser:rolescanbeeditedin-line,forname,statusandpasswordclicktheEditbutton
AddUsers
ToaddanewUser,clicktheAddUserbutton,completetheinformationforthenewuser(name,password,status,roles)andthensave
toaddthenewusertothedatabase.
266
Security
Roles
Hereyoucanmanagethedatabaseroles:
SearchRole
AddRole
DeleteRole
EditRole
AddRole
ToaddanewUser,clicktheAddRolebutton,completetheinformationforthenewrole(name,parentrole,mode)andthensavetoadd
thenewroletothedatabase.
AddRuletoaRole
Toaddanewsecurityrulefortheselectedrole,clicktheAddRulebutton.Thiswillaskyouthestringoftheresourcethatyouwantto
secure.Foralistofavailableresources,visittheofficialdocumentationhere
ThenyoucanconfiguretheCRUDpermissionsonthenewlycreatedresource.
267
Security
268
DatabaseM anagement
DatabaseManagement
Thisisthepanelcontainingalltheinformationaboutthecurrentdatabase.
Structure
Representsthedatabasestructureasclusters.Eachclusterhasthefollowinginformation:
ID,istheclusterID
Name,isthenameofthecluster
Records,arethetotalnumberofrecordsstoredinthecluster
ConflictStrategy,istheconflictstrategyused.Iempty,thedatabase'sstrategyisusedasdefault
Configuration
Containsthedatabaseconfigurationandcustomproperties.Hereyoucandisplayandchangethefollowingsettings:
dateFormat,isthedateformatusedinthedatabasebydefault.Example:yyyy-M M -dd
dateTimeFormatisthedatetimeformatusedinthedatabasebydefault.Example:yyyy-M M -ddHH:mm:ss
localeCountry,isthecountryused."NO"meansnocountryset
localeLanguage,isthelanguageused."no"meansnolanguageset
charSet,isthecharsetused.DefaultisUTF-8
timezone,isthetimezoneused.Timezoneistakenondatabasecreation
definitionVersion,istheinternalversionusedtostorethemetadata
clusterSelection,isthestrategyusedonselectingtheclusteroncreationofnewrecordofaclass
minimumClusters,minimumnumberofclusterstocreatewhenatclasscreation
conflictStrategy,isthedatabasestrategyforresolvingconflicts
269
DatabaseM anagement
Export
AllowstoexportthecurrentdatabaseinGZippedJSONformat.Toimportthefileintoanotherdatabase,usetheImportConsole
Command.
270
ServerM anagement
ServerManagement
ThisisthesectiontoworkwithOrientDBServerasDBA/DevOps.StartingfromOrientDB2.1Studiohasbeenenrichedoffeatures
takenfromtheEnterpriseEdition.
Statistics
Thispagesummarizesallthemostimportantinformationaboutthecurrentserverandtheotherserversconnectedinclusterifany:
Serverstatus
Operationspersecond
ActiveConnections
Warnings
CPU, RAMand DISKused
LivechartwithCRUDoperationsinreal-time
Connections
Displaysalltheactiveconnectionstotheserver.Eachconnectionreportsthefollowinginformation:
SessionID,astheuniquesessionnumber
Client,astheuniqueclientnumber
Address,istheconnectionsource
Database,thedatabasenameused
User,thedatabaseuser
TotalRequests,asthetotalnumberofrequestsexecutedbytheconnection
CommandInfo,astherunningcommand
CommandDetail,asthedetailabouttherunningcommand
LastCommandOn,isthelasttimearequesthasbeenexecuted
LastCommandInfo,istheinformatonaboutlastoperationexecuted
LastCommandDetail,istheinformatonaboutthedetailsoflastoperationexecuted
LastExecutionTime,istheexecutiontimeolastrequest
TotalWorkingTime,isthetotalexecutiontimetakenbycurrentconnectionsofar
271
ServerM anagement
ConnectedSince,isthedatewhentheconnectionhasbeencreated
Protocol,istheprotocolbetweenHTTPandBinary
ClientID,atextrepresentingtheclientconnection
Driver,thedrivername
Eachsessioncanbeinterruptedorevenkilled.
Configuration
ThispanelshowstheServersettingsdividedintwoboxes:
Properties,asthecustomsettingsin config/orientdb-server-config.xmlfile
GlobalConfiguration,asalltheglobalconfiguration.Onlyfewofthemcanbechangedatrun-timewiththe"Save"button
Storages
Thispanelshowsthestoragesusedbytheserver.Belowtheinformationreportedperstorage:
272
ServerM anagement
Name,isthestoragename
Type,where OLocalPaginatedStorage(plocal)meanspersstentand ODirectMemoryStorage(memory)isinmemoryonly
Path,asthepathonserver'sfilesystemwherethestorageislocated
ActiveUsers.Thisinfomationcouldn'tbeupdatedwiththerealnumberofusersthatareusingthedatabase
273
Auditing
Auditing(Enterpriseonly)
Studio2.1includesanewfunctionalitycalledAuditing.TounderstandhowAuditingworks,pleasereadtheAuditingpage.
TheStudioAuditingpanelhelpswithconfiguringauditingbyavoidingeditingthe auditing-config.jsonfilemanually.
Bydefaultalltheauditinglogsaresavedasdocumentsofclass AuditingLog.Ifyouraccounthasenoughprivileges,youcandirectly
querytheauditinglog.Exampleonretrievinglast20logs: selectfromAuditingLogorderby@riddesclimit20.
However,StudioprovidesapaneltofiltertheAuditingLogmessageswithoutusingSQL.
274
Troubleshooting
Troubleshooting
ThispageaimstolinkalltheguidestoProblemsandTroubleshooting.
Subsections
TroubleshootingJavaAPI
Topics
Whycan'tIseealltheedges?
OrientDB,bydefault,managesedgesas"lightweight"edgesiftheyhavenoproperties.Thismeansthatifanedgehasnoproperties,it's
notstoredasphysicalrecord.Butdon'tworry,youredgeisstilltherebutencodedinaseparatedatastructure.Forthisreasonifyou
executea selectfromEnoedgesorlessedgesthanexpectedarereturned.It'sextremelyraretheneedtohavethelistofedges,butif
thisisyourcaseyoucandisablethisfeaturebyissuingthiscommandonce(withaslowdownandabiggerdatabasesize):
ALTERDATABASEcustomuseLightweightEdges=false
UseISO8601Dates
AccordingtoISO8601,CombineddateandtimeinUTC:2014-12-20T00:00:00.Tousethisstandardchangethedatetimeformatinthe
database:
ALTERDATABASEDATETIMEFORMATyyyy-MM-dd'T'HH:mm:ss.SSS'Z'
JVMcrashonSolarisandother*NIXplatforms.
Thereasonofthisissueismassiveusageofsun.misc.UnsafewhichmayhavedifferentcontractthanitisimplementedforLinuxand
WindowsJDKs.Toavoidthiserrorpleaseusefollowingsettingsduringserverstart:
java...-Dmemory.useUnsafe=falseand-Dstorage.compressionMethod=gzip...
Erroroccurredwhilelockingmemory:UnabletolockJVMmemory.Thiscanresultin
partoftheJVMbeingswappedout,especiallyifmmappingoffilesenabled.Increase
RLIMIT_MEMLOCKorrunOrientDBserverasroot(ENOMEM)
Don'tbescaredaboutit:yourOrientDBinstallationwillworkperfectly,justitcouldbeslowerwithdatabaselargerthanmemory.
ThislockisneededincaseofyouworkonOSwhichusesaggressiveswappinglikeLinux.Ifthereisthecasewhenamountofavailable
RAM isnotenoughtocacheallM M APcontentOScanswapoutrarelyusedpartsofJavaheaptothediskandwhenGCisstartedto
collectgarbagewewillhaveperformancedegradation,topreventsuchsituationJavaheapislockedintomemoryandprohibitedtobe
flushedonthedisk.
com.orientechnologies.orient.core.exception.OStorageException:Erroronreading
recordfromfile'default.0.oda',position2333,size122,14Mb:therecordsizeisbigger
thenthefileitself(233,99Kb)
Thisusuallyhappensbecausethedatabasehasbeencorruptedbyahw/swcrashorahardkilloftheprocessduringthewritingtodisk.
Ifthishappensonindexclustersjustrebuildindexes,otherwisere-importapreviouslyexporteddatabase.
Class'OUSER'or'OROLE'wasnotfoundincurrentdatabase
275
Troubleshooting
Lookat:Restoreadminuser.
User'admin'wasnotfoundincurrentdatabase
Lookat:Restoreadminuser.
WARNING:Connectionre-acquiredtransparentlyafterXXXmsandYretries:noerrors
willbethrownatapplicationlevel
Thismeansthatprobablydefaulttimeoutsaretoolowandserversideoperationneedmoretimetocomplete.FollowthesePerformance
Tuning.
Recordidinvalid-1:-2
Thismessageisrelativetoatemporaryrecordidgeneratedinsideatransaction.FormoreinformationlookatTransactions.Thismeans
thattherecordhasn'tbeencorrectlyserialized.
Brandnewrecordsarecreatedwithversiongreaterthan0
Thishappensingraphs.Thinktothisgraphofrecords:
A->B->C->A
WhenOrientDBstartstoserializerecordsgoesrecursivelyfromtherootA.WhenAisencounteredagaintoavoidloopsitsavesthe
recordasemptyjusttogettheRecordIDtostoreintotherecordC.WhentheserializationstackendstherecordA(thatwasthefirstof
thestack)isupdatedbecausehasbeencreatedasfirstbutempty.
Error:com.orientechnologies.orient.core.exception.OStorageException:Cannotopen
localstorage'/tmp/databases/demo'withmode=rw
com.orientechnologies.common.concur.lock.OLockException:File
'/tmp/databases/demo/default.0.oda'islockedbyanotherprocess,maybethedatabaseis
inusebyanotherprocess.UsetheremotemodewithaOrientDBservertoallow
multipleaccesstothesamedatabase
Botherrorshavethesamemeaning:a"plocal"databasecan'tbeopenedbymultipleJVM atthesametime.Tofix:
checkifthere'snoprocessusingOrientDB(mostofthetimesaOrientDBServerisrunningithebackground).Justshutdownthat
serverandretry
ifyouneedmultipleaccesstothesamedatabase,don'tuse"plocal"directly,butratherstartaserverandaccesstothedatabaseby
using"remote"protocol.Inthiswaytheserverisabletosharethesamedatabasewithmultipleclients.
Causedby:java.lang.NumberFormatException:Forinputstring:"500Mb"
You'reusingdifferentversionoflibraries.Forexampletheclientisusing1.3andtheserver1.4.Alignthelibrariestothesameversion
(lastissuggested).Orprobablyyou'vedifferentversionsofthesamejarsintheclasspath.
276
Java
TroubleshootingusingJavaAPI
OConcurrentModificationException:Cannotupdaterecord#X:Yin
storage'Z'becausetheversionisnotthelatest.Probablyyouare
updatinganoldrecordorithasbeenmodifiedbyanotheruser
(db=vAyour=vB)
Thisexceptionhappensbecauseyou'rerunninginaM ultiVersionControlCheck(M VCC)systemandanotherthread/userhasupdated
therecordyou'resaving.FormoreinformationaboutthistopiclookatConcurrency.Tofixthisproblemyoucan:
ChangetheGraphconsistencyleveltodon'tusetransactions.
Orwritecodeconcurrencyproof.
Example:
for(intretry=0;retry<maxRetries;++retry){
try{
//APPLYCHANGES
document.field(name,"Luca");
document.save();
break;
}catch(ONeedRetryExceptione){
//RELOADITTOGETLASTVERSION
document.reload();
}
}
Thesameintransactions:
for(intretry=0;retry<maxRetries;++retry){
db.begin();
try{
//CREATEANEWITEM
ODocumentinvoiceItem=newODocument("InvoiceItem");
invoiceItem.field(price,213231);
invoiceItem.save();
//ADDITTOTHEINVOICE
Collection<ODocument>items=invoice.field(items);
items.add(invoiceItem);
invoice.save();
db.commit();
break;
}catch(OTransactionExceptione){
//RELOADITTOGETLASTVERSION
invoice.reload();
}
}
Where maxRetriesisthemaximumnumberofattemptofreloading.
RuninOSGicontext
(byRamanGupta)OrientDBusesServiceRegistrytoloadOIndexFactoryandsomeOSGicontainersmightnotworkwithit.
OnesolutionistosettheTCCLsothattheServiceRegistrylookupworksinsideofOSGi:
277
Java
ODatabaseObjectTxdb=null;
ClassLoaderorigClassLoader=Thread.currentThread().getContextClassLoader();
try{
ClassLoaderorientClassLoader=OIndexes.class.getClassLoader();
Thread.currentThread().setContextClassLoader(orientClassLoader);
db=objectConnectionPool.acquire(dbUrl,username,password);
}finally{
Thread.currentThread().setContextClassLoader(origClassLoader);
}
BecausetheServiceLoaderusesthethreadcontextclassloader,youcanconfigureittousetheclassloaderoftheOrientDBbundlesothat
itfindstheentriesinM ETA-INF/services.
AnotherwayistoembedthedependenciesinconfigurationintheM avenpom.xmlfileunderplugin(maven-bundleplugin)/configuration/instructions:
<Embed-Dependency>
orientdb-client,
orient-commons,
orientdb-core,
orientdb-enterprise,
orientdb-object,
javassist
</Embed-Dependency>
Includingonlythejarsyouneed.LookatWhichlibrarydoIuse?
Databaseinstancehasbeenreleasedtothepool.Getanother
databaseinstancefromthepoolwiththerightusernameand
password
Thisisagenericerrortellingthatthedatabasehasbeenfoundclosedwhileusingit.
Checkthestacktracetofindthereasonofit:
OLazyObjectIterator
Thisisthecasewhenyou'reworkingwithObjectDatabaseAPIandafieldcontainsacollectionoramaploadedinlazy.Oniterationit
needsanopendatabasetofetchlinkedrecords.
Solutions:
assuretoleavethedatabaseopenwhilebrowsingthefield
orearlyloadalltheinstances(justiteratetheitems)
defineafetch-plantoloadtheentireobjecttreeinoneshootandthenworkoffline.Ifyouneedtosavetheobjectbacktothe
databasethenreopenthedatabaseandcall db.save(object).
StackOverflowonsavingobjects
Thiscouldbeduetothehighdeepofthegraph,usuallywhenyoucreatemanyrecords.Tofixitsavetherecordsmoreoften.
278
QueryExamples
QueryExamples
Thispagescollectsexampleofqueryfromusers.Feelfreetoaddyourownusecaseandquerytohelpfurtherusers.
Howtoaskthegraphwhatrelationshipsexistbetweentwovertices?InmycaseIhavetwoknown'Person'nodeseachconnectedviaa
'member_of'edgetoashared'Organization'node.Each'Person'isalsoa'member_of'other'Organization's.
selectintersect(out('member_of').org_name)from
Personwherenamein["nagu","rohit"]
Thisexampleshowshowtoformwhereclauseinordertoquery/filterbasedonpropertiesofconnectedvertices.
DocElemandM odelaresubclassesofVandhasM odelofE.
insertintoDocElemseturi='domain.tdl',type="paragraph"
insertintoModelsethash='0e1f',model="helloworld"
createedgehasModelfrom#12:2738to#13:2658
UserwishestoquerythoseverticesfilteringoncertainpropertiesofDocElemandM odel.
TofetchtheM odelverticeswhereDocElem.type="paragraph"andconnectedvertexM odelhasthepropertymodellike'%world%'
selectfrom(selectexpand(out('hasModel'))fromDocElemwhere
type="paragraph")wheremodellike"%world%"
TofindinsteadtheDocElemvertices,usethis(assumingthataDocElemisonlyconnectedtooneM odel):
select*fromDocElemwheretype="paragraph"and
out('hasModel')[0].modellike'%world%'
Howtoapplybuilt-inmathfunctionsonprojections?Forexample,tousethesum()functionover2valuesreturnedfromsub-queries
usingprojections,thefollowingsyntaxmaybeused:
selectsum($a[0].count,$b[0].count)
let$a=(selectcount(*)frome),
$b=(selectcount(*)fromv)
Giventhefollowingschema:VerticesareconnectedwithEdgesoftypeRELATEDwhichhavepropertycount.2verticescanhave
connectioninbothwaysatthesametime.
V1--RELATED(count=17)-->V2
V2--RELATED(count=3)-->V1
Needtobuildaquerythat,foragivenvertexVn,willfindallverticesconnectedwithRELATEDedgetothisVnandalso,foreachpair
[Vn,Vx]willcalculateSUM ofin_RELATED.countandout_RELATED.count.
Forthatsimpleexampleabove,thisqueryresultforV1wouldbe
Vertex
V2
Count
20
Solution:
279
QueryExamples
selectv.name,sum(count)ascntfrom(
selectif(eval("in=#17:0"),out,in)asv,countfromEwhere(
in=#17:0orout=#17:0)
)groupbyvorderbycntdesc
Thiswasdiscussedinthegooglegroupsoverhere:"https://groups.google.com/forum/#!topic/orient-database/CRR-simpmLg".Thanks
toAndreyforposingtheproblem.
280
PerformanceTuning
PerformanceTuning
ThisguidecontainsthegeneraltipstooptimizeyourapplicationthatusetheOrientDB.Belowyoucanfindlinksforthespecificguides
differentperdatabasetypeused.Lookatthespecificguidesbasedonthedatabasetypeyou'reusing:
DocumentDatabaseperformancetuning
ObjectDatabaseperformancetuning
DistributedConfigurationtuning
I/Obenchmark
ThemainrequirementforafastDBM SishavinggoodI/O.Inordertounderstandtheperformanceofyourhw/swconfiguration.Ifyou
haveaUnixderivedOS(likeLinux,M acOSX,etc.),thesimplestwaytohaveyourrawI/Operformanceisrunningthistwocommands:
ddif=/dev/zeroof=/tmp/output.imgbs=8kcount=256k
rm/tmp/output.img
ThisistheoutputonafastSSD(1.4GB/sec):
262144+0recordsin
262144+0recordsout
2147483648bytestransferredin1.467536secs(1463326070bytes/sec)
AndthisiswhatyouusuallygetwithaHDconnectedwithaUSB3.0(90M B/sec):
262144+0recordsin
262144+0recordsout
2147483648bytestransferredin23.699740secs(90612119bytes/sec)
Asyoucannoticethefirstconfiguration(SSD)is16xfasterthanthesecondconfiguration(HD).Sensibledifferencescanbefound
betweenbaremetalhwandVirtualM achines.
Java
OrientDBiswritteninJava,soitrunsontopofJavaVirtualM achine(JVM ).OrientDBiscompatiblewithJava8andwesuggestto
usethisversiontorunOrientDB.Java8isfasterthanJava7andpreviousones.
JMX
Startingfromv2.1,OrientDBexposesinternalmetricsthroughJM XBeans.UsethisinformationtotrackandprofileOrientDB.
Memorysettings
ServerandEmbeddedsettings
ThesesettingsarevalidforbothServercomponentandtheJVM whereisrunningtheJavaapplicationthatuseOrientDBinEmbedded
M ode,byusingdirectlyplocal.
Themostimportantthingontuningisassuringthememorysettingsarecorrect.Whatcanmaketherealdifferenceistherightbalancing
betweentheheapandthevirtualmemoryusedbyM emoryM apping,speciallyonlargedatasets(GBs,TBsandmore)wherethein
memorycachestructurescountlessthanrawIO.
Forexampleifyoucanassignmaximum8GBtotheJavaprocess,it'susuallybetterassigningsmallheapandlargediskcachebuffer(offheapmemory).Soratherthan:
281
PerformanceTuning
java-Xmx8g...
Youcouldinsteadtrythis:
java-Xmx800m-Dstorage.diskCache.bufferSize=7200...
Thestorage.diskCache.bufferS izesetting(withold"local"storageitwasfile.mmap.maxMemory)isinM Bandtellshowmuch
memorytouseforDiskCachecomponent.Bydefaultis4GB.
NOTE:Ifthesumofmaximumheapanddiskcachebufferistoohigh,couldcausetheOStoswapwithhugeslowdown.
JVMsettings
JVM settingsareencodedinserver.sh(andserver.bat)batchfiles.YoucanchangethemtotunetheJVM accordingtoyourusageand
hw/swsettings.Wefoundthesesettingworkwellonmostconfigurations:
-server-XX:+PerfDisableSharedMem
ThissettingwilldisablewritingdebuginformationabouttheJVM .IncaseyouneedtoprofiletheJVM ,justremovethissetting.For
moreinformationlookatthispost:http://www.evanjones.ca/jvm-mmap-pause.html.
Highconcurrentupdates
OrientDBhasanoptimisticconcurrencycontrolsystem,butonveryhighconcurrentupdatesonthefewrecordsitcouldbemore
efficientlockingrecordstoavoidretries.YoucouldsynchronizetheaccessbyyourselforbyusingthestorageAPI.Notethatthis
worksonlywithnon-remotedatabases.
((OStorageEmbedded)db.getStorage()).acquireWriteLock(finalORIDiRid)
((OStorageEmbedded)db.getStorage()).acquireSharedLock(finalORIDiRid)
((OStorageEmbedded)db.getStorage()).releaseWriteLock(finalORIDiRid)
((OStorageEmbedded)db.getStorage()).releaseSharedLock(finalORIDiRid)
Exampleofusage.Writerthreads:
try{
((OStorageEmbedded)db.getStorage()).acquireWriteLock(record.getIdentity());
//DOSOMETHING
}finally{
((OStorageEmbedded)db.getStorage()).releaseWriteLock(record.getIdentity());
}
Readerthreads:
try{
((OStorageEmbedded)db.getStorage()).acquireSharedLock(record.getIdentity());
//DOSOMETHING
}finally{
((OStorageEmbedded)db.getStorage()).releaseSharedLock(record.getIdentity());
}
Remoteconnections
Therearemanywaystoimproveperformancewhenyouaccesstothedatabaseusingtheremoteconnection.
Fetchingstrategy
282
PerformanceTuning
Whenyouworkwitharemotedatabaseyou'vetopayattentiontothefetchingstrategyused.BydefaultOrientDBClientloadsonly
therecordcontainedintheresultset.Forexampleifaqueryreturns100elements,butthenyoucrosstheseelementsfromtheclient,
thenOrientDBclientlazilyloadstheelementswithonemorenetworkcalltotheserverforeachmissedrecord.
Byspecifyingafetchplanwhenyouexecuteacommandyou'retellingtoOrientDBtoprefetchtheelementsyouknowtheclient
applicationwillaccess.Byspecifyingacompletefetchplanyoucouldreceivetheentireresultinjustonenetworkcall.
Formoreinformationlookat:Fetching-Strategies.
NetworkConnectionPool
Eachclient,bydefault,usesonlyonenetworkconnectiontotalkwiththeserver.M ultiplethreadsonthesameclientsharethesame
networkconnectionpool.
Whenyou'vemultiplethreadscouldbeabottlenecksincealotoftimeisspentonwaitingforafreenetworkconnection.Thisisthe
reasonwhyismuchimportanttoconfigurethenetworkconnectionpool.
Theconfigurationsisverysimple,just2parameters:
minPool,istheinitialsizeoftheconnectionpool.Thedefaultvalueisconfiguredasglobalparameters"client.channel.minPool"
(seeparameters)
maxPool,isthemaximumsizetheconnectionpoolcanreach.Thedefaultvalueisconfiguredasglobalparameters
"client.channel.maxPool"(seeparameters)
AtfirstconnectiontheminPoolisusedtopre-createnetworkconnectionsagainsttheserver.Whenaclientthreadisaskingfora
connectionandallthepoolisbusy,thenittriestocreateanewconnectionuntilmaxPoolisreached.
Ifallthepoolconnectionsarebusy,thentheclientthreadwillwaitforthefirstfreeconnection.
Exampleofconfigurationbyusingdatabaseproperties:
database=newODatabaseDocumentTx("remote:localhost/demo");
database.setProperty("minPool",2);
database.setProperty("maxPool",5);
database.open("admin","admin");
Enlargetimeouts
Ifyouseealotofmessageslike:
WARNING:Connectionre-acquiredtransparentlyafterXXXmsandYretries:noerrorswillbethrownatapplicationlevel
meansthatprobablydefaulttimeoutsaretoolowandserversideoperationneedmoretimetocomplete.It'sstronglysuggestedyou
enlargeyourtimeoutonlyaftertriedtoenlargetheNetworkConnectionPool.Thetimeoutparameterstotuneare:
network.lockTimeout,thetimeoutinmstoacquirealockagainstachannel.Thedefaultis15seconds.
network.socketTimeout,theTCP/IPSockettimeoutinms.Thedefaultis10seconds.
Query
Useofindexes
ThefirstimprovementtospeedupqueriesistocreateIndexesagainstthefieldsusedinWHEREconditions.Forexamplethisquery:
SELECTFROMProfileWHEREname='Jay'
Browsestheentire"profile"clusterlookingforrecordsthatsatisfytheconditions.Thesolutionistocreateanindexagainstthe'name'
propertywith:
283
PerformanceTuning
CREATEINDEXprofile.nameUNIQUE
UseNOTUNIQUEinsteadofUNIQUEifthevalueisnotunique.
Formorecomplexquerieslike
SELECT*FROMtestClassWHEREprop1=?ANDprop2=?
Compositeindexshouldbeused
CREATEINDEXcompositeIndexONtestClass(prop1,prop2)UNIQUE
orviaJavaAPI:
oClass.createIndex("compositeIndex",OClass.INDEX_TYPE.UNIQUE,"prop1","prop2");
M oreover,becauseofpartialmatchsearching,thisindexwillbeusedforoptimizingquerylike
SELECT*FROMtestClassWHEREprop1=?
Fordeepunderstandingofqueryoptimizationlookattheunittest:
http://code.google.com/p/orient/source/browse/trunk/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectIndexR
euseTest.java
Avoiduseof@ridinWHEREconditions(notactualfrom1.3version)
Using@ridinwhereconditionsslowdownqueries.M uchbettertousetheRecordIDastarget.Example:
Changethis:
SELECTFROMProfileWHERE@rid=#10:44
Withthis:
SELECTFROM#10:44
Also
SELECTFROMProfileWHERE@ridIN[#10:44,#10:45]
Withthis:
SELECTFROM[#10:44,#10:45]
MassiveInsertion
UsetheMassiveInsertintent
IntentssuggesttoOrientDBwhatyou'regoingtodo.Inthiscaseyou'retellingtoOrientDBthatyou'reexecutingamassiveinsertion.
OrientDBauto-reconfigureitselftoobtainthebestperformance.Whendoneyoucanremovetheintentjustsettingittonull.
Example:
284
PerformanceTuning
db.declareIntent(newOIntentMassiveInsert());
//YOURMASSIVEINSERTION
db.declareIntent(null);
DisableJournal
Incaseofmassiveinsertion,speciallywhenthisoperationismadejustonce,youcoulddisablethejournal(WAL)toimproveinsertion
speed:
-storage.useWAL=false
BydefaultWAL(WriteAheadLog)isenabled.
Disablesynconflushofpages
ThissettingavoidstoexecuteasyncatOSlevelwhenapageisflushed.Disablingthissettingwillimprovethroughputonwrites:
-Dstorage.wal.syncOnPageFlush=false
MassiveUpdates
Updatesgenerates"holes"atStoragelevelbecauserarelythenewrecordfitsperfectlythesizeofthepreviousone.Holesarefreespaces
betweendata.Holesarerecycledbutanexcessivenumberofsmallholesit'sthesameashavingahighlydefragmentedFileSystem:space
iswasted(becausesmallholescan'tbeeasilyrecycled)andperformancedegradeswhenthedatabasegrowth.
Oversize
Ifyouknowyouwillupdatecertaintypeofrecords,createaclassforthemandsettheOversize(defaultis0)to2ormore.
BydefaulttheOGraphVertexclasshasanoversizevaluesettedat2.Ifyoudefineyourownclassessetthisvalueatleastat2.
OClassmyClass=getM etadata().getSchema().createClass("Car");myClass.setOverSize(2);
Wiseuseoftransactions
ToobtainreallinearperformancewithOrientDByoushouldavoidtouseTransactionsasfarasyoucan.InfactsOrientDBkeepsin
memoryallthechangesuntilyouflushitwithacommit.SothebottleneckisyourHeapspaceandthemanagementoflocaltransaction
cache(implementedasaM ap).
Transactionsslowdownmassiveinsertsunlessyou'reusinga"remote"connection.Inthatcaseitspeedsupalltheinsertionbecausethe
client/servercommunicationhappensonlyatcommittime.
DisableTransactionLog
IfyouneedtogroupoperationstospeedupremoteexecutioninalogicaltransactionbutrenouncingtotheTransactionLog,justdisable
itbysettingthepropertytx.useLogtofalse.
ViaJVM configuration:
java...-Dtx.useLog=false...
orviaAPI:
OGlobalConfiguration.TX_USE_LOG.setValue(false);
285
PerformanceTuning
NOTE:PleasenotethatincaseofcrashoftheJVMthependingtransactionOrientDBcouldnotbeabletorollbackit.
Usetheschema
StartingfromOrientDB2.0,iffieldsaredeclaredintheschema,fieldnamesarenotstoredindocument/vertex/edgethemselves.This
improvesperformanceandsavesalotofspaceondisk.
Configuration
TotuneOrientDBlookattheConfigurationsettings.
Platforms
PerformanceanalysisonZFS
286
SettingConfiguration
GlobalConfiguration
OrientDBcanbeconfiguredinseveralways.Toknowthecurrentsettingsusetheconsolewiththeconfigcommand.
Changesettings
Bycommandline
YoucanpasssettingsviacommandlinewhentheJVM islaunched.Thisistypicallystoredinsideserver.sh(orserver.batonWindows):
java-Dcache.size=10000-Dstorage.keepOpen=true...
Byserverconfiguration
Putinthe <properties>sectionofthefileorientdb-server-config.xml(ororientdb-dserver-config.xml)theentriestoconfigure.
Example:
...
<properties>
<entryname="cache.size"value="10000"/>
<entryname="storage.keepOpen"value="true"/>
</properties>
...
Atrun-time
OGlobalConfiguration.MVRBTREE_NODE_PAGE_SIZE.setValue(2048);
Dumptheconfiguration
TodumptheOrientDBconfigurationyoucansetaparameteratJVM launch:
java-Denvironment.dumpCfgAtStartup=true...
OrviaAPIatanytime:
OGlobalConfiguration.dumpConfiguration(System.out);
Parameters
ToknowmorelookattheJavaenumeration: OGlobalConfiguration.java.
Environment
environment.dumpCfgAtS tartup
Dumpstheconfigurationduringapplicationstartup..
Settingname...:environment.dumpCfgAtStartup
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
287
SettingConfiguration
environment.concurrent
Specifiesifrunninginmulti-threadenvironment.Settingthistofalseturnsofftheinternallockmanagement..
Settingname...:environment.concurrent
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
environment.allowJVMS hutdown
AllowstheshutdownoftheJVM ,ifneeded/requested..
Settingname...:environment.allowJVMShutdown
Defaultvalue..:true
Setatrun-time:true
Hidden.........:false
Script
script.pool.maxS ize
M aximumnumberofinstancesinthepoolofscriptengines..
Settingname...:script.pool.maxSize
Defaultvalue..:20
Setatrun-time:false
Hidden.........:false
Memory
memory.useUnsafe
IndicateswhetherUnsafewillbeused,ifitispresent..
Settingname...:memory.useUnsafe
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
memory.directMemory.safeMode
Indicateswhethertoperformarangecheckbeforeeachdirectmemoryupdate.Itistruebydefault,butusuallyitcanbesafelysetto
false.Itshouldonlybetotrueafterdramaticchangeshavebeenmadeinthestoragestructures..
Settingname...:memory.directMemory.safeMode
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
memory.directMemory.trackMode
If'trackmode'isswitchedon,thenthefollowingstepsareperformed:1.directmemoryJM Xbeanisregistered.2.Youmaycheck
amountofallocateddirectmemoryasapropertyoftheJM Xbean.3.Ifamemoryleakisdetected,thenaJM Xeventwillbefired.This
modecausesalargeoverheadandshouldbeusedfortestingpurposesonly..
Settingname...:memory.directMemory.trackMode
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
288
SettingConfiguration
memory.directMemory.onlyAlignedMemoryAccess
Somearchitecturesdonotallowunalignedmemoryaccessormaysufferfromspeeddegradation.Forsuchplatforms,thisflagshouldbe
settotrue..
Settingname...:memory.directMemory.onlyAlignedMemoryAccess
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Jvm
jvm.gc.delayForOptimize
M inimalamountoftime(inseconds),sincethelastSystem.gc(),whencalledaftertreeoptimization..
Settingname...:jvm.gc.delayForOptimize
Defaultvalue..:600
Setatrun-time:false
Hidden.........:false
Storage
storage.diskCache.bufferS ize
Sizeofdiskbufferinmegabytes..
Settingname...:storage.diskCache.bufferSize
Defaultvalue..:4096
Setatrun-time:false
Hidden.........:false
storage.diskCache.writeCachePart
Percentageofdiskcache,whichisusedaswritecache.
Settingname...:storage.diskCache.writeCachePart
Defaultvalue..:15
Setatrun-time:false
Hidden.........:false
storage.diskCache.writeCachePageTTL
M axtimeuntilapagewillbeflushedfromwritecache(inseconds)..
Settingname...:storage.diskCache.writeCachePageTTL
Defaultvalue..:86400
Setatrun-time:false
Hidden.........:false
storage.diskCache.writeCachePageFlushInterval
Intervalbetweenflushingofpagesfromwritecache(inms)..
Settingname...:storage.diskCache.writeCachePageFlushInterval
Defaultvalue..:25
Setatrun-time:false
Hidden.........:false
storage.diskCache.writeCacheFlushInactivityInterval
289
SettingConfiguration
Intervalbetween2writestothediskcache,ifwritesaredonewithanintervalmorethanprovided,allfileswillbefsyncedbeforethe
nextwrite,whichallowsadatarestoreafteraservercrash(inms)..
Settingname...:storage.diskCache.writeCacheFlushInactivityInterval
Defaultvalue..:60000
Setatrun-time:false
Hidden.........:false
storage.diskCache.writeCacheFlushLockTimeout
M aximumamountoftimethewritecachewillwaitbeforeapageflushes(inms,-1todisable).
Settingname...:storage.diskCache.writeCacheFlushLockTimeout
Defaultvalue..:-1
Setatrun-time:false
Hidden.........:false
storage.diskCache.diskFreeS paceLimit
M inimumamountofspaceondisk,which,whenexceeded,willcausethedatabasetoswitchtoread-onlymode(inmegabytes)..
Settingname...:storage.diskCache.diskFreeSpaceLimit
Defaultvalue..:100
Setatrun-time:false
Hidden.........:false
storage.diskCache.diskFreeS paceCheckInterval
Theinterval(inseconds),afterwhichthestorageperiodicallycheckswhethertheamountoffreediskspaceisenoughtoworkinwrite
mode.
Settingname...:storage.diskCache.diskFreeSpaceCheckInterval
Defaultvalue..:5
Setatrun-time:false
Hidden.........:false
storage.configuration.syncOnUpdate
Indicatesaforcesyncshouldbeperformedforeachupdateonthestorageconfiguration..
Settingname...:storage.configuration.syncOnUpdate
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
storage.compressionMethod
Recordcompressionmethodusedinstorage.Possiblevalues:gzip,nothing,snappy,snappy-native.Defaultis'nothing'thatmeansno
compression..
Settingname...:storage.compressionMethod
Defaultvalue..:nothing
Setatrun-time:false
Hidden.........:false
storage.encryptionMethod
Recordencryptionmethodusedinstorage.Possiblevalues:'aes'and'des'.Defaultis'nothing'fornoencryption..
Settingname...:storage.encryptionMethod
Defaultvalue..:nothing
Setatrun-time:false
Hidden.........:false
290
SettingConfiguration
storage.encryptionKey
Containsthestorageencryptionkey.Thissettingishidden..
Settingname...:storage.encryptionKey
Defaultvalue..:null
Setatrun-time:false
Hidden.........:true
storage.makeFullCheckpointAfterCreate
Indicateswhetherafullcheckpointshouldbeperformed,ifstoragewascreated..
Settingname...:storage.makeFullCheckpointAfterCreate
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
storage.makeFullCheckpointAfterOpen
Indicateswhetherafullcheckpointshouldbeperformed,ifstoragewasopened.Itisneededsofuzzycheckpointscanworkproperly..
Settingname...:storage.makeFullCheckpointAfterOpen
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
storage.makeFullCheckpointAfterClusterCreate
Indicateswhetherafullcheckpointshouldbeperformed,ifstoragewasopened.
Settingname...:storage.makeFullCheckpointAfterClusterCreate
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
storage.useWAL
WhetherWALshouldbeusedinpaginatedstorage..
Settingname...:storage.useWAL
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
storage.wal.syncOnPageFlush
IndicateswhetheraforcesyncshouldbeperformedduringWALpageflush..
Settingname...:storage.wal.syncOnPageFlush
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
storage.wal.cacheS ize
M aximumsizeofWALcache(inamountofWALpages,eachpageis64k)Ifsetto0,cachingwillbedisabled..
Settingname...:storage.wal.cacheSize
Defaultvalue..:3000
Setatrun-time:false
Hidden.........:false
storage.wal.maxS egmentS ize
291
SettingConfiguration
M aximumsizeofsingleWALsegment(inmegabytes)..
Settingname...:storage.wal.maxSegmentSize
Defaultvalue..:128
Setatrun-time:false
Hidden.........:false
storage.wal.maxS ize
M aximumsizeofWALondisk(inmegabytes)..
Settingname...:storage.wal.maxSize
Defaultvalue..:4096
Setatrun-time:false
Hidden.........:false
storage.wal.commitTimeout
M aximumintervalbetweenWALcommits(inms.).
Settingname...:storage.wal.commitTimeout
Defaultvalue..:1000
Setatrun-time:false
Hidden.........:false
storage.wal.shutdownTimeout
M aximumwaitintervalbetweenevents,whenthebackgroundflushthreadreceivesashutdowncommandandwhenthebackgroundflush
willbestopped(inms.).
Settingname...:storage.wal.shutdownTimeout
Defaultvalue..:10000
Setatrun-time:false
Hidden.........:false
storage.wal.fuzzyCheckpointInterval
Intervalbetweenfuzzycheckpoints(inseconds).
Settingname...:storage.wal.fuzzyCheckpointInterval
Defaultvalue..:300
Setatrun-time:false
Hidden.........:false
storage.wal.reportAfterOperationsDuringRestore
Amountofprocessedlogoperations,afterwhichstatusofdatarestoreprocedurewillbeprinted(0oranegativevalue,disablesthe
logging)..
Settingname...:storage.wal.reportAfterOperationsDuringRestore
Defaultvalue..:10000
Setatrun-time:false
Hidden.........:false
storage.wal.restore.batchS ize
AmountofWALrecords,whicharereadatonceinasinglebatchduringarestoreprocedure..
Settingname...:storage.wal.restore.batchSize
Defaultvalue..:1000
Setatrun-time:false
Hidden.........:false
storage.wal.readCacheS ize
292
SettingConfiguration
SizeofWALreadcacheinamountofpages..
Settingname...:storage.wal.readCacheSize
Defaultvalue..:1000
Setatrun-time:false
Hidden.........:false
storage.wal.fuzzyCheckpointS hutdownWait
TheamountoftimetheDBshouldwaituntilitshutsdown(inseconds)..
Settingname...:storage.wal.fuzzyCheckpointShutdownWait
Defaultvalue..:600
Setatrun-time:false
Hidden.........:false
storage.wal.fullCheckpointS hutdownTimeout
TheamountoftimetheDBwillwait,untilacheckpointisfinished,duringaDBshutdown(inseconds)..
Settingname...:storage.wal.fullCheckpointShutdownTimeout
Defaultvalue..:600
Setatrun-time:false
Hidden.........:false
storage.wal.path
PathtotheWALfileonthedisk.Bydefault,itisplacedintheDBdirectory,butitishighlyrecommendedtouseaseparatediskto
storelogoperations..
Settingname...:storage.wal.path
Defaultvalue..:null
Setatrun-time:false
Hidden.........:false
storage.diskCache.pageS ize
Sizeofpageofdiskbuffer(inkilobytes).!!!NEVERCHANGETHISVALUE!!!.
Settingname...:storage.diskCache.pageSize
Defaultvalue..:64
Setatrun-time:false
Hidden.........:false
storage.lowestFreeListBound
Theleastamountoffreespace(inkb)inapage,whichistrackedinpaginatedstorage..
Settingname...:storage.lowestFreeListBound
Defaultvalue..:16
Setatrun-time:false
Hidden.........:false
storage.lockTimeout
M aximumamountoftime(inms)tolockthestorage..
Settingname...:storage.lockTimeout
Defaultvalue..:0
Setatrun-time:false
Hidden.........:false
storage.record.lockTimeout
293
SettingConfiguration
M aximumoftime(inms)tolockasharedrecord..
Settingname...:storage.record.lockTimeout
Defaultvalue..:2000
Setatrun-time:false
Hidden.........:false
storage.useTombstones
Whenarecordisdeleted,thespaceintheclusterwillnotbefreed,butrathertombstoned..
Settingname...:storage.useTombstones
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
storage.cluster.usecrc32
Indicateswhethercrc32shouldbeusedforeachrecordtocheckrecordintegrity..
Settingname...:storage.cluster.usecrc32
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
storage.keepOpen
Deprecated.
Settingname...:storage.keepOpen
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Record
record.downsizing.enabled
Onupdates,iftherecordsizeislowerthanbefore,thisreducesthespacetakenaccordingly.Ifenabledthiscouldincrease
defragmentation,butitreducestheuseddiskspace..
Settingname...:record.downsizing.enabled
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Object
object.saveOnlyDirty
ObjectDatabaseonly!Itsavesobjectsboundtodirtyrecords..
Settingname...:object.saveOnlyDirty
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
Db
294
SettingConfiguration
db.pool.min
Defaultdatabasepoolminimumsize..
Settingname...:db.pool.min
Defaultvalue..:1
Setatrun-time:false
Hidden.........:false
db.pool.max
Defaultdatabasepoolmaximumsize..
Settingname...:db.pool.max
Defaultvalue..:100
Setatrun-time:false
Hidden.........:false
db.pool.idleTimeout
Timeoutforcheckingforfreedatabasesinthepool..
Settingname...:db.pool.idleTimeout
Defaultvalue..:0
Setatrun-time:false
Hidden.........:false
db.pool.idleCheckDelay
Delaytimeoncheckingforidledatabases..
Settingname...:db.pool.idleCheckDelay
Defaultvalue..:0
Setatrun-time:false
Hidden.........:false
db.mvcc.throwfast
Usefast-thrownexceptionsforM VCCOConcurrentM odificationExceptions.Nocontextinformationwillbeavailable.Settotrue,
whentheseexceptionsarethrown,butthedetailsarenotnecessary..
Settingname...:db.mvcc.throwfast
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
db.validation
Enablesordisablesvalidationofrecords..
Settingname...:db.validation
Defaultvalue..:true
Setatrun-time:true
Hidden.........:false
db.makeFullCheckpointOnIndexChange
Whenindexmetadataischanged,afullcheckpointisperformed..
Settingname...:db.makeFullCheckpointOnIndexChange
Defaultvalue..:true
Setatrun-time:true
Hidden.........:false
295
SettingConfiguration
db.makeFullCheckpointOnS chemaChange
Whenindexschemaischanged,afullcheckpointisperformed..
Settingname...:db.makeFullCheckpointOnSchemaChange
Defaultvalue..:true
Setatrun-time:true
Hidden.........:false
db.document.serializer
Thedefaultrecordserializerusedbythedocumentdatabase..
Settingname...:db.document.serializer
Defaultvalue..:ORecordSerializerBinary
Setatrun-time:false
Hidden.........:false
db.mvcc
Deprecated,M VCCcannotbedisabledanymore.
Settingname...:db.mvcc
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
db.use.distributedVersion
Deprecated,distributedversionisnotusedanymore.
Settingname...:db.use.distributedVersion
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
NonTX
nonTX.recordUpdate.synch
Executesasyncagainstthefile-systemforeveryrecordoperation.Thisslowsdownrecordupdates,butguaranteesreliabilityon
unreliabledrives..
Settingname...:nonTX.recordUpdate.synch
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
nonTX.clusters.sync.immediately
Listofclusterstosyncimmediatelyafterupdate(separatedbycommas).Canbeusefulforamanualindex..
Settingname...:nonTX.clusters.sync.immediately
Defaultvalue..:manindex
Setatrun-time:false
Hidden.........:false
Tx
tx.trackAtomicOperations
296
SettingConfiguration
Thissettingisusedonlyfordebugpurposes.Itcreatesastacktraceofmethods,whenanatomicoperationisstarted..
Settingname...:tx.trackAtomicOperations
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
tx.commit.synch
Synchronizesthestorageaftertransactioncommit.
Settingname...:tx.commit.synch
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
tx.autoRetry
M aximumnumberofautomaticretryifsomeresourcehasbeenlockedinthemiddleofthetransaction(Timeoutexception).
Settingname...:tx.autoRetry
Defaultvalue..:1
Setatrun-time:false
Hidden.........:false
tx.log.fileType
Filetypetohandletransactionlogs:mmaporclassic.
Settingname...:tx.log.fileType
Defaultvalue..:classic
Setatrun-time:false
Hidden.........:false
tx.log.synch
Executesasynchagainstthefile-systemateverylogentry.Thisslowsdowntransactionsbutguaranteetransactionreliabilityon
unreliabledrives.
Settingname...:tx.log.synch
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
tx.useLog
Transactionsuselogfiletostoretemporarydatatoberolledbackincaseofcrash.
Settingname...:tx.useLog
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Index
index.embeddedToS btreeBonsaiThreshold
Amountofvalues,afterwhichtheindeximplementationwilluseansbtreeasavaluescontainer.Setto-1,todisableandforceusingan
sbtree..
297
SettingConfiguration
Settingname...:index.embeddedToSbtreeBonsaiThreshold
Defaultvalue..:40
Setatrun-time:true
Hidden.........:false
index.sbtreeBonsaiToEmbeddedThreshold
Amountofvalues,afterwhichindeximplementationwilluseanembeddedvaluescontainer(disabledbydefault).
Settingname...:index.sbtreeBonsaiToEmbeddedThreshold
Defaultvalue..:-1
Setatrun-time:true
Hidden.........:false
index.auto.synchronousAutoRebuild
Synchronousexecutionofautorebuildingofindexes,incaseofaDBcrash.
Settingname...:index.auto.synchronousAutoRebuild
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
index.auto.lazyUpdates
ConfiguretheTreeM apsforautomaticindexes,asbufferedornot.-1meansbuffereduntiltx.commit()ordb.close()arecalled..
Settingname...:index.auto.lazyUpdates
Defaultvalue..:10000
Setatrun-time:false
Hidden.........:false
index.flushAfterCreate
Flushstoragebufferafterindexcreation..
Settingname...:index.flushAfterCreate
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
index.manual.lazyUpdates
ConfiguretheTreeM apsformanualindexesasbufferedornot.-1meansbuffereduntiltx.commit()ordb.close()arecalled.
Settingname...:index.manual.lazyUpdates
Defaultvalue..:1
Setatrun-time:false
Hidden.........:false
index.durableInNonTxMode
Indicateswhetherindeximplementationforplocalstoragewillbedurableinnon-Txmode(truebydefault)..
Settingname...:index.durableInNonTxMode
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
index.txMode
IndicatestheindexdurabilitylevelinTXmode.CanbeROLLBACK_ONLYorFULL(ROLLBACK_ONLYbydefault)..
298
SettingConfiguration
Settingname...:index.txMode
Defaultvalue..:FULL
Setatrun-time:false
Hidden.........:false
index.cursor.prefetchS ize
Defaultprefetchsizeofindexcursor..
Settingname...:index.cursor.prefetchSize
Defaultvalue..:500000
Setatrun-time:false
Hidden.........:false
index.auto.rebuildAfterNotS oftClose
Autorebuildallautomaticindexesafterupondatabaseopenwhenwasn'tclosedproperly.
Settingname...:index.auto.rebuildAfterNotSoftClose
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
HashTable
hashTable.slitBucketsBuffer.length
Lengthofbuffer(inpages),wherebucketsthatweresplit,butnotflushedtothedisk,arekept.Thisbufferisusedtominimizerandom
IOoverhead..
Settingname...:hashTable.slitBucketsBuffer.length
Defaultvalue..:1500
Setatrun-time:false
Hidden.........:false
Sbtree
sbtree.maxDepth
M aximumdepthofsbtree,whichwillbetraversedduringkeylookupuntilitwillbetreatedasbroken(64bydefault).
Settingname...:sbtree.maxDepth
Defaultvalue..:64
Setatrun-time:false
Hidden.........:false
sbtree.maxKeyS ize
M aximumsizeofakey,whichcanbeputintheSBTreeinbytes(10240bydefault).
Settingname...:sbtree.maxKeySize
Defaultvalue..:10240
Setatrun-time:false
Hidden.........:false
sbtree.maxEmbeddedValueS ize
M aximumsizeofvaluewhichcanbeputinanSBTreewithoutcreationlinktoastandalonepageinbytes(40960bydefault).
299
SettingConfiguration
Settingname...:sbtree.maxEmbeddedValueSize
Defaultvalue..:40960
Setatrun-time:false
Hidden.........:false
Sbtreebonsai
sbtreebonsai.bucketS ize
SizeofbucketinOSBTreeBonsai(inkB).Contract:bucketSize<storagePageSize,storagePageSize%bucketSize==0..
Settingname...:sbtreebonsai.bucketSize
Defaultvalue..:2
Setatrun-time:false
Hidden.........:false
sbtreebonsai.linkBagCache.size
AmountofLINKBAGcollectionstobecached,toavoidconstantreloadingofdata..
Settingname...:sbtreebonsai.linkBagCache.size
Defaultvalue..:100000
Setatrun-time:false
Hidden.........:false
sbtreebonsai.linkBagCache.evictionS ize
ThenumberofcachedLINKBAGcollections,whichwillberemoved,whenthecachelimitisreached..
Settingname...:sbtreebonsai.linkBagCache.evictionSize
Defaultvalue..:1000
Setatrun-time:false
Hidden.........:false
sbtreebonsai.freeS paceReuseTrigger
Howmuchfreespaceshouldbeinansbtreebonsaifile,beforeitwillbereusedduringthenextallocation..
Settingname...:sbtreebonsai.freeSpaceReuseTrigger
Defaultvalue..:0.5
Setatrun-time:false
Hidden.........:false
RidBag
ridBag.embeddedDefaultS ize
SizeofembeddedRidBagarray,whencreated(empty).
Settingname...:ridBag.embeddedDefaultSize
Defaultvalue..:4
Setatrun-time:false
Hidden.........:false
ridBag.embeddedToS btreeBonsaiThreshold
AmountofvaluesafterwhichaLINKBAGimplementationwillusesbtreeasvaluescontainer.Setto-1toalwaysuseansbtree..
300
SettingConfiguration
Settingname...:ridBag.embeddedToSbtreeBonsaiThreshold
Defaultvalue..:40
Setatrun-time:true
Hidden.........:false
ridBag.sbtreeBonsaiToEmbeddedToThreshold
Amountofvalues,afterwhichaLINKBAGimplementationwilluseanembeddedvaluescontainer(disabledbydefault)..
Settingname...:ridBag.sbtreeBonsaiToEmbeddedToThreshold
Defaultvalue..:-1
Setatrun-time:true
Hidden.........:false
Collections
collections.preferS BTreeS et
Thisconfigurationsettingisexperimental..
Settingname...:collections.preferSBTreeSet
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
File
file.trackFileClose
Logallthecaseswhenfilesareclosed.Thisisneededonlyforinternaldebuggingpurposes..
Settingname...:file.trackFileClose
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
file.lock
Locksfileswhenused.Defaultistrue.
Settingname...:file.lock
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
file.deleteDelay
Delaytime(inms)towaitforanotherattempttodeletealockedfile..
Settingname...:file.deleteDelay
Defaultvalue..:10
Setatrun-time:false
Hidden.........:false
file.deleteRetry
Numberofretriestodeletealockedfile..
301
SettingConfiguration
Settingname...:file.deleteRetry
Defaultvalue..:50
Setatrun-time:false
Hidden.........:false
Jna
jna.disable.system.library
ThispropertydisablesusingJNA,shoulditbeinstalledonyoursystem.(Defaulttrue)TouseJNAbundledwithdatabase..
Settingname...:jna.disable.system.library
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Security
security.userPasswordS altIterations
Numberofiterationstogeneratethesaltoruserpassword.Changingthissettingdoesnotaffectstoredpasswords..
Settingname...:security.userPasswordSaltIterations
Defaultvalue..:65536
Setatrun-time:false
Hidden.........:false
security.userPasswordS altCacheS ize
Cachesizeofhashedsaltpasswords.ThecacheworksasLRU.Use0todisablethecache..
Settingname...:security.userPasswordSaltCacheSize
Defaultvalue..:500
Setatrun-time:false
Hidden.........:false
Network
network.maxConcurrentS essions
M aximumnumberofconcurrentsessions..
Settingname...:network.maxConcurrentSessions
Defaultvalue..:1000
Setatrun-time:true
Hidden.........:false
network.socketBufferS ize
TCP/IPSocketbuffersize..
Settingname...:network.socketBufferSize
Defaultvalue..:32768
Setatrun-time:true
Hidden.........:false
network.lockTimeout
Timeout(inms)toacquirealockagainstachannel..
302
SettingConfiguration
Settingname...:network.lockTimeout
Defaultvalue..:15000
Setatrun-time:true
Hidden.........:false
network.socketTimeout
TCP/IPSockettimeout(inms)..
Settingname...:network.socketTimeout
Defaultvalue..:15000
Setatrun-time:true
Hidden.........:false
network.requestTimeout
Requestcompletiontimeout(inms)..
Settingname...:network.requestTimeout
Defaultvalue..:3600000
Setatrun-time:true
Hidden.........:false
network.retry
Numberofattemptstoconnecttotheserveronfailure..
Settingname...:network.retry
Defaultvalue..:5
Setatrun-time:true
Hidden.........:false
network.retryDelay
Thetime(inms)theclientmustwait,beforereconnectingtotheserveronfailure..
Settingname...:network.retryDelay
Defaultvalue..:500
Setatrun-time:true
Hidden.........:false
network.binary.loadBalancing.enabled
AsksforDNSTXTrecord,todetermineifloadbalancingissupported..
Settingname...:network.binary.loadBalancing.enabled
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
network.binary.loadBalancing.timeout
M aximumtime(inms)towaitfortheanswerfromDNSabouttheTXTrecordforloadbalancing..
Settingname...:network.binary.loadBalancing.timeout
Defaultvalue..:2000
Setatrun-time:true
Hidden.........:false
network.binary.maxLength
TCP/IPmaxcontentlength(inbytes)ofBINARYrequests..
303
SettingConfiguration
Settingname...:network.binary.maxLength
Defaultvalue..:32736
Setatrun-time:true
Hidden.........:false
network.binary.readResponse.maxTimes
M aximumattempts,untilaresponsecanberead.Otherwise,theresponsewillbedroppedfromthechannel..
Settingname...:network.binary.readResponse.maxTimes
Defaultvalue..:20
Setatrun-time:true
Hidden.........:false
network.binary.debug
Debugmode:printalldataincomingonthebinarychannel..
Settingname...:network.binary.debug
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
network.http.maxLength
TCP/IPmaxcontentlength(inbytes)forHTTPrequests..
Settingname...:network.http.maxLength
Defaultvalue..:1000000
Setatrun-time:true
Hidden.........:false
network.http.charset
Httpresponsecharset.
Settingname...:network.http.charset
Defaultvalue..:utf-8
Setatrun-time:true
Hidden.........:false
network.http.jsonResponseError
Httpresponseerrorinjson..
Settingname...:network.http.jsonResponseError
Defaultvalue..:true
Setatrun-time:true
Hidden.........:false
network.http.jsonp
EnabletheusageofJSONP,ifrequestedbytheclient.Theparameternametouseis'callback'..
Settingname...:network.http.jsonp
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
network.http.sessionExpireTimeout
Timeout,afterwhichanhttpsessionisconsideredtohaveexpired(inseconds)..
304
SettingConfiguration
Settingname...:network.http.sessionExpireTimeout
Defaultvalue..:300
Setatrun-time:false
Hidden.........:false
network.http.useToken
EnableTokenbasedsessionsforhttp..
Settingname...:network.http.useToken
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
network.token.secretyKey
Networktokensercretkey..
Settingname...:network.token.secretyKey
Defaultvalue..:
Setatrun-time:false
Hidden.........:false
network.token.encriptionAlgorithm
Networktokenalgorithm..
Settingname...:network.token.encriptionAlgorithm
Defaultvalue..:HmacSHA256
Setatrun-time:false
Hidden.........:false
network.token.expireTimeout
Timeout,afterwhichabinarysessionisconsideredtohaveexpired(inminutes)..
Settingname...:network.token.expireTimeout
Defaultvalue..:60
Setatrun-time:false
Hidden.........:false
Profiler
profiler.enabled
Enablestherecordingofstatisticsandcounters..
Settingname...:profiler.enabled
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
profiler.config
Configurestheprofileras,,.
Settingname...:profiler.config
Defaultvalue..:null
Setatrun-time:true
Hidden.........:false
profiler.autoDump.interval
305
SettingConfiguration
Dumpstheprofilervaluesatregularintervals(inseconds)..
Settingname...:profiler.autoDump.interval
Defaultvalue..:0
Setatrun-time:true
Hidden.........:false
Log
log.console.level
Consolelogginglevel..
Settingname...:log.console.level
Defaultvalue..:info
Setatrun-time:true
Hidden.........:false
log.file.level
Filelogginglevel..
Settingname...:log.file.level
Defaultvalue..:fine
Setatrun-time:true
Hidden.........:false
Cache
cache.local.impl
LocalRecordcacheimplementation..
Settingname...:cache.local.impl
Defaultvalue..:com.orientechnologies.orient.core.cache.ORecordCacheWeakRefs
Setatrun-time:false
Hidden.........:false
cache.local.enabled
Deprecated,Level1cachecannotbedisabledanymore.
Settingname...:cache.local.enabled
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Command
command.timeout
Defaulttimeoutforcommands(inms)..
Settingname...:command.timeout
Defaultvalue..:0
Setatrun-time:true
Hidden.........:false
command.cache.enabled
306
SettingConfiguration
Enablecommandcache..
Settingname...:command.cache.enabled
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
command.cache.evictS trategy
Commandcachestrategybetween:[INVALIDATE_ALL,PER_CLUSTER].
Settingname...:command.cache.evictStrategy
Defaultvalue..:PER_CLUSTER
Setatrun-time:false
Hidden.........:false
command.cache.minExecutionTime
M inimumexecutiontimetoconsidercachingtheresultset..
Settingname...:command.cache.minExecutionTime
Defaultvalue..:10
Setatrun-time:false
Hidden.........:false
command.cache.maxResultsetS ize
M aximumresultsettimetoconsidercachingresultset..
Settingname...:command.cache.maxResultsetSize
Defaultvalue..:500
Setatrun-time:false
Hidden.........:false
Query
query.parallelAuto
Autoenableparallelquery,ifrequirementsaremet..
Settingname...:query.parallelAuto
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
query.parallelMinimumRecords
M inimumnumberofrecordstoactivateparallelqueryautomatically..
Settingname...:query.parallelMinimumRecords
Defaultvalue..:300000
Setatrun-time:false
Hidden.........:false
query.parallelResultQueueS ize
Sizeofthequeuethatholdsresultsonparallelexecution.Thequeueisblocking,soincasethequeueisfull,thequerythreadswillbeina
waitstate..
307
SettingConfiguration
Settingname...:query.parallelResultQueueSize
Defaultvalue..:20000
Setatrun-time:false
Hidden.........:false
query.scanPrefetchPages
Pagestoprefetchduringscan.Settingthisvaluehighermakesscansfaster,becauseitreducesthenumberofI/Ooperations,thoughit
consumesmorememory.(Use0todisable).
Settingname...:query.scanPrefetchPages
Defaultvalue..:20
Setatrun-time:false
Hidden.........:false
query.scanBatchS ize
Scanclustersinblocksofrecords.Thissettingreducesthelocktimeontheclusterduringscans.Ahighvaluemeanafasterexecution,
butalsoalowerconcurrencylevel.Setto0todisablebatchscanning.Disablingbatchscanningissuggestedforread-onlydatabasesonly.
Settingname...:query.scanBatchSize
Defaultvalue..:100000
Setatrun-time:false
Hidden.........:false
query.scanThresholdTip
Ifthetotalnumberofrecordsscannedinaqueryexceedsthissetting,thenawarningisgiven.(Use0todisable).
Settingname...:query.scanThresholdTip
Defaultvalue..:50000
Setatrun-time:false
Hidden.........:false
query.limitThresholdTip
Ifthetotalnumberofreturnedrecordsexceedsthisvalue,thenawarningisgiven.(Use0todisable).
Settingname...:query.limitThresholdTip
Defaultvalue..:10000
Setatrun-time:false
Hidden.........:false
Statement
statement.cacheS ize
NumberofparsedSQLstatementskeptincache..
Settingname...:statement.cacheSize
Defaultvalue..:100
Setatrun-time:false
Hidden.........:false
Client
client.channel.maxPool
M aximumsizeofpoolofnetworkchannelsbetweenclientandserver.AchannelisaTCP/IPconnection..
308
SettingConfiguration
Settingname...:client.channel.maxPool
Defaultvalue..:100
Setatrun-time:false
Hidden.........:false
client.connectionPool.waitTimeout
M aximumtime,wheretheclientshouldwaitforaconnectionfromthepool,whenallconnectionsbusy..
Settingname...:client.connectionPool.waitTimeout
Defaultvalue..:5000
Setatrun-time:true
Hidden.........:false
client.channel.dbReleaseWaitTimeout
Delay(inms),afterwhichadatamodificationcommandwillberesent,iftheDBwasfrozen..
Settingname...:client.channel.dbReleaseWaitTimeout
Defaultvalue..:10000
Setatrun-time:true
Hidden.........:false
client.ssl.enabled
UseSSLforclientconnections..
Settingname...:client.ssl.enabled
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
client.ssl.keyS tore
UseSSLforclientconnections..
Settingname...:client.ssl.keyStore
Defaultvalue..:null
Setatrun-time:false
Hidden.........:false
client.ssl.keyS torePass
UseSSLforclientconnections..
Settingname...:client.ssl.keyStorePass
Defaultvalue..:null
Setatrun-time:false
Hidden.........:false
client.ssl.trustS tore
UseSSLforclientconnections..
Settingname...:client.ssl.trustStore
Defaultvalue..:null
Setatrun-time:false
Hidden.........:false
client.ssl.trustS torePass
UseSSLforclientconnections..
309
SettingConfiguration
Settingname...:client.ssl.trustStorePass
Defaultvalue..:null
Setatrun-time:false
Hidden.........:false
client.session.tokenBased
Requestatokenbasedsessiontotheserver..
Settingname...:client.session.tokenBased
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
client.channel.minPool
M inimumpoolsize.
Settingname...:client.channel.minPool
Defaultvalue..:1
Setatrun-time:false
Hidden.........:false
Server
server.openAllDatabasesAtS tartup
Iftrue,theserveropensalltheavailabledatabasesatstartup.Availablesince2.2.
Settingname...:server.openAllDatabasesAtStartup
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
server.channel.cleanDelay
Timeinmsofdelaytocheckpendingclosedconnections..
Settingname...:server.channel.cleanDelay
Defaultvalue..:5000
Setatrun-time:false
Hidden.........:false
server.cache.staticFile
Cachestaticresourcesuponloading..
Settingname...:server.cache.staticFile
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
server.log.dumpClientExceptionLevel
Logsclientexceptions.UseanylevelsupportedbyJavajava.util.logging.Levelclass:OFF,FINE,CONFIG,INFO,WARNING,
SEVERE.
Settingname...:server.log.dumpClientExceptionLevel
Defaultvalue..:FINE
Setatrun-time:false
Hidden.........:false
310
SettingConfiguration
server.log.dumpClientExceptionFullS tackTrace
Dumpsthefullstacktraceoftheexceptionsenttotheclient.
Settingname...:server.log.dumpClientExceptionFullStackTrace
Defaultvalue..:false
Setatrun-time:true
Hidden.........:false
Distributed
distributed.crudTaskTimeout
M aximumtimeout(inms)towaitforCRUDremotetasks..
Settingname...:distributed.crudTaskTimeout
Defaultvalue..:3000
Setatrun-time:true
Hidden.........:false
distributed.commandTaskTimeout
M aximumtimeout(inms)towaitforCommandremotetasks..
Settingname...:distributed.commandTaskTimeout
Defaultvalue..:10000
Setatrun-time:true
Hidden.........:false
distributed.commandLongTaskTimeout
M aximumtimeout(inms)towaitforLong-runningremotetasks..
Settingname...:distributed.commandLongTaskTimeout
Defaultvalue..:86400000
Setatrun-time:true
Hidden.........:false
distributed.deployDbTaskTimeout
M aximumtimeout(inms)towaitfordatabasedeployment..
Settingname...:distributed.deployDbTaskTimeout
Defaultvalue..:1200000
Setatrun-time:true
Hidden.........:false
distributed.deployChunkTaskTimeout
M aximumtimeout(inms)towaitfordatabasechunkdeployment..
Settingname...:distributed.deployChunkTaskTimeout
Defaultvalue..:15000
Setatrun-time:true
Hidden.........:false
distributed.deployDbTaskCompression
Compressionlevel(between0and9)touseinbackupfordatabasedeployment..
311
SettingConfiguration
Settingname...:distributed.deployDbTaskCompression
Defaultvalue..:7
Setatrun-time:true
Hidden.........:false
distributed.queueTimeout
M aximumtimeout(inms)towaitfortheresponseinreplication..
Settingname...:distributed.queueTimeout
Defaultvalue..:5000
Setatrun-time:true
Hidden.........:false
distributed.asynchQueueS ize
Queuesizetohandledistributedasynchronousoperations.Thebiggeristhequeue,themoreoperationarebuffered,butalsomore
memoryit'sconsumed.0=dynamicallocation,whichmeansupto2^31-1entries..
Settingname...:distributed.asynchQueueSize
Defaultvalue..:0
Setatrun-time:false
Hidden.........:false
distributed.asynchResponsesTimeout
M aximumtimeout(inms)tocollectalltheasynchronousresponsesfromreplication.Afterthistimetheoperationisrolledback
(throughanUNDO)..
Settingname...:distributed.asynchResponsesTimeout
Defaultvalue..:15000
Setatrun-time:false
Hidden.........:false
distributed.purgeResponsesTimerDelay
M aximumtimeout(inms)tocollectalltheasynchronousresponsesfromreplication.Thisisthedelaythepurgethreadusestocheck
asynchronousrequestsintimeout..
Settingname...:distributed.purgeResponsesTimerDelay
Defaultvalue..:15000
Setatrun-time:false
Hidden.........:false
distributed.queueMaxS ize
M aximumqueuesizetomarkanodeasstalled.Ifthenumerofmessagesinqueuearemorethanthisvalues,thenodeisrestartedwitha
remotecommand(0=nomaximum,whichmeansupto2^31-1entries)..
Settingname...:distributed.queueMaxSize
Defaultvalue..:100
Setatrun-time:false
Hidden.........:false
distributed.backupDirectory
Directorywherethecopyofanexistentdatabaseissaved,beforeitisdownloadedfromthecluster..
Settingname...:distributed.backupDirectory
Defaultvalue..:../backup/databases
Setatrun-time:false
Hidden.........:false
312
SettingConfiguration
distributed.concurrentTxMaxAutoRetry
M aximumattemptsthetransactioncoordinatorshouldexecuteatransactionautomatically,ifrecordsarelocked.(M inimumis1=no
attempts).
Settingname...:distributed.concurrentTxMaxAutoRetry
Defaultvalue..:10
Setatrun-time:true
Hidden.........:false
distributed.concurrentTxAutoRetryDelay
Delay(inms)betweenattemptsonexecutingadistributedtransaction,whichhadfailedbecauseoflockedrecords.(0=nodelay).
Settingname...:distributed.concurrentTxAutoRetryDelay
Defaultvalue..:100
Setatrun-time:true
Hidden.........:false
Oauth2
oauth2.secretkey
HttpOAuth2secretkey..
Settingname...:oauth2.secretkey
Defaultvalue..:
Setatrun-time:false
Hidden.........:false
Lazyset
lazyset.workOnS tream
Deprecated,nowBINARYserializationisusedinplaceofCSV.
Settingname...:lazyset.workOnStream
Defaultvalue..:true
Setatrun-time:false
Hidden.........:false
Mvrbtree
mvrbtree.timeout
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.timeout
Defaultvalue..:0
Setatrun-time:false
Hidden.........:false
mvrbtree.nodePageS ize
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
313
SettingConfiguration
Settingname...:mvrbtree.nodePageSize
Defaultvalue..:256
Setatrun-time:false
Hidden.........:false
mvrbtree.loadFactor
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.loadFactor
Defaultvalue..:0.7
Setatrun-time:false
Hidden.........:false
mvrbtree.optimizeThreshold
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.optimizeThreshold
Defaultvalue..:100000
Setatrun-time:false
Hidden.........:false
mvrbtree.entryPoints
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.entryPoints
Defaultvalue..:64
Setatrun-time:false
Hidden.........:false
mvrbtree.optimizeEntryPointsFactor
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.optimizeEntryPointsFactor
Defaultvalue..:1.0
Setatrun-time:false
Hidden.........:false
mvrbtree.entryKeysInMemory
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.entryKeysInMemory
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
mvrbtree.entryValuesInMemory
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.entryValuesInMemory
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
mvrbtree.ridBinaryThreshold
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
314
SettingConfiguration
Settingname...:mvrbtree.ridBinaryThreshold
Defaultvalue..:-1
Setatrun-time:false
Hidden.........:false
mvrbtree.ridNodePageS ize
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.ridNodePageSize
Defaultvalue..:64
Setatrun-time:false
Hidden.........:false
mvrbtree.ridNodeS aveMemory
Deprecated,M VRBTREEISNOTUSEDANYM OREINFAVOROFSBTREEANDHASHINDEX.
Settingname...:mvrbtree.ridNodeSaveMemory
Defaultvalue..:false
Setatrun-time:false
Hidden.........:false
NOTE:On64-bitsystemsyouhavenotthelimitationof32-bitsystemswithmemory.
Logging
Loggingisconfiguredinaseparatefile,lookatLoggingformoreinformation.
Storageconfiguration
OrientDBallowsmodificationstothestorageconfiguration.Eventhoughthiswillbesupportedwithhighlevelcommands,fornowit's
pretty"internal"usingJavaAPI.
Togetthestorageconfigurationforthecurrentdatabase:
OStorageConfigurationcfg=db.getStorage().getConfiguration();
Lookat OStorageConfigurationtodiscoverallthepropertiesyoucanchange.TochangetheconfigurationofaclustergetitbyID;
OStoragePhysicalClusterConfigurationLocalclusterCfg=(OStoragePhysicalClusterConfigurationLocal)cfg.clusters.get(3);
Tochangethedefaultsettingsfornewclustersgetthefiletemplateobject.Inthisexamplewechangetheinitialfilesizefromthedefault
500Kbdownto10Kb:
OStorageSegmentConfigurationdefaultCfg=(OStorageSegmentConfiguration)cfg.fileTemplate;
defaultCfg.fileStartSize="10Kb";
Afterchangescall OStorageConfiguration.update():
cfg.update();
315
GraphAPI
TuningtheGraphAPI
ThisguideisspecificfortheTinkerPopBlueprintsGraphDatabase.PleasebesuretoreadthegenericguidetothePerformance-Tuning.
Connecttothedatabaselocally
Localconnectionismuchfasterthanremote.Souse"plocal"basedonthestorageengineusedondatabasecreation.Ifyouneedto
connecttothedatabasefromthenetworkyoucanusethe"Embedtheservertechnique".
Avoidputtingpropertiesonedges
Eventhoughsupportspropertiesonedges,thisismuchexpensivebecauseitcreatesanewrecordperedge.Soifyouneedthemyou've
toknowthatthedatabasewillbebiggerandinsertiontimewillbemuchlonger.
Setpropertiesalltogether
It'smuchlightertosetpropertiesinblockthanonebyone.Lookatthisparagraph:Graph-Database-Tinkerpop#setting-multipleproperties.
Setpropertiesonvertexandedgecreation
It'sevenfasterifyousetpropertiesdirectlyoncreationofverticesandedges.Lookatthisparagraph:Graph-DatabaseTinkerpop#create-element-and-properties.
MassiveInsertion
SeeGenericimprovementonmassiveinsertion.Toaccesstotheunderlyingdatabaseuse:
database.getRawGraph().declareIntent(newOIntentMassiveInsert());
//YOURMASSIVEINSERTION
database.getRawGraph().declareIntent(null);
Avoidtransactionsifyoucan
UsetheOrientGraphNoTximplementationthatdoesn'tusetransactionforbasicoperationslikecreationanddeletionofverticesand
edges.Ifyouplantoson'tusetransactionschangetheconsistencylevel.OrientGraphNoTxisnotcompatiblewithOrientBatchGraph
souseitplain:
OrientGraphNoTxgraph=newOrientGraphNoTx("local:/tmp/mydb");
Usetheschema
Evenifyoucanmodelyourgraphwithonlytheentities(V)ertexand(E)dgeit'smuchbettertouseschemaforyourtypesextending
VertexandEdgeclasses.Inthiswaytraversingwillbefasterandverticesandedgeswillbesplitondifferentfiles.Formoreinformation
lookat:GraphSchema.
Example:
316
GraphAPI
OClassaccount=graph.createVertexType("Account");
Vertexv=graph.addVertex("class:Account");
UseindexestolookupverticesbyanID
Ifyou'veyourownIDonverticesandyouneedtolookupthemtocreateedgesthencreateanindexagainstit:
graph.createKeyIndex("id",Vertex.class,newParameter("class","Account"));
IftheIDisuniquethencreateanUNIQUEindexthatismuchfasterandlighter:
graph.createKeyIndex("id",Vertex.class,newParameter("type","UNIQUE"),newParameter("class","Account"));
TolookupverticesbyID:
for(Vertexv:graph.getVertices("Account.id","23876JS2")){
System.out.println("Foundvertex:"+v);
}
Disablevalidation
Everytimeagraphelementismodified,OrientDBexecutesavalidationtoassurethegraphrulesareallrespected,thatmeans:
putedgeinout/incollections
putvertexinedgesin/out
NowifyouusetheGraphAPIwithoutbypassinggraphelementmanipulationthiscouldbeturnedoffwithahugegaininperformance:
graph.setValidationEnabled(false);
Reducevertexobjects
YoucanavoidthecreationofanewODocumentforeachnewvertexbyreusingitwithODocument.reset()methodthatclearsthe
instancemakingitreadyforanewinsertoperation.Bearinmindthatyouwillneedtoassignthedocumentwiththeproperclassafter
resettingasitisdoneinthecodebelow.
NOTE:ThistrickworksONLYINNON-TRANSACTIONALcontexts,becauseduringtransactionsthedocumentscouldbekeptin
memoryuntilcommit.
Example:
db.declareIntent(newOIntentMassiveInsert());
ODocumentdoc=db.createVertex("myVertex");
for(inti=0;i<1000000;++i){
doc.reset();
doc.setClassName("myVertex");
doc.field("id",i);
doc.field("name","Jason");
doc.save();
}
db.declareIntent(null);
Cachemanagement
317
GraphAPI
GraphDatabase,bydefault,cachesthemostusedelements.Formassiveinsertionisstronglysuggestedtodisablecachetoavoidto
keepalltheelementinmemory.M assiveInsertIntentautomaticallysetsittofalse.
graph.setRetainObjects(false);
318
DocumentAPI
TuningtheDocumentAPI
ThisguideisspecificfortheDocumentDatabase.PleasebesuretoreadthegenericguidetothePerformance-Tuning.
MassiveInsertion
SeeGenericimprovementonmassiveinsertion.
Avoiddocumentcreation
YoucanavoidthecreationofanewODocumentforeachinsertionbyusingtheODocument.reset()methodthatclearstheinstance
makingitreadyforanewinsertoperation.Bearinmindthatyouwillneedtoassignthedocumentwiththeproperclassafterresetting
asitisdoneinthecodebelow.
NOTE:ThistrickworksONLYINNON-TRANSACTIONALcontexts,becauseduringtransactionsthedocumentscouldbekeptin
memoryuntilcommit.
Example:
importcom.orientechnologies.orient.core.intent.OIntentMassiveInsert;
db.declareIntent(newOIntentMassiveInsert());
ODocumentdoc=newODocument();
for(inti=0;i<1000000;++i){
doc.reset();
doc.setClassName("Customer");
doc.field("id",i);
doc.field("name","Jason");
doc.save();
}
db.declareIntent(null);
319
ObjectAPI
TuningtheObjectAPI
ThisguideisspecificfortheObjectDatabase.PleasebesuretoreadthegenericguidetothePerformance-Tuning.
MassiveInsertion
SeeGenericimprovementonmassiveinsertion.
320
Profiler
Profiler
OrientDBEnterpriseEditioncomeswithaprofilerthatcollectsallthemetricsabouttheengineandthesystemwhereisrunning.
Automaticdump
Whenyouincurinproblems,thebestwaytoproduceinformationaboutOrientDBisactivatingaregulardumpoftheprofiler.Setthis
configurationvariableatstart:
java...-Dprofiler.autoDump.reset=true-Dprofiler.autoDump.interval=60-Dprofiler.enabled=true...
Thiswilldumptheprofilerintheconsoleevery60secondsandresetsthemetricsafterthedump.Formoreinformationaboutsettings
lookatParameters.
RetrieveprofilermetricsviaHTTP
http://<server>[<:port>]/profiler/<command>/[<config>]|[<from>/<to>]
Where:
serveristheserverwhereOrientDBisrunning
portisthehttpport,OrientDBlistensat2480bydefault
command,isthecommandbetween:
realtimetoretrieverealtimeinformation
lasttoretrieverealtimeinformation
archivetoretrievearchivedprofiling
summarytoretrievesummaryofpastprofiling
starttostartprofiling
stoptostopprofiling
resettoresettheprofiler(equalstostop+start)
statustoknowthestatusofprofiler
configuretoconfigureprofiling
metadatatoretrievemetadata
Example:
http://localhost:2480/profiler/realtime
Metrictype
Chrono
Chronoarerecordingofoperation.EachChronohasthefollowingvalues:
last,asthelasttimerecorded
min,astheminimumtimerecorded
max,asthemaximumtimerecorded
average,astheaveragetimerecorded
total,asthetotaltimerecorded
entries,asthenumberoftimesthemetrichasbeenrecorded
Counter
321
Profiler
It'sacounteraslongvaluethatrecordsresources.
HookValues
Aregenericvaluesofanytypebetweenthesupportedones:string,number,booleanornull.
Ahookvalueisnotcollectedincentralway,butit'sgatheredatruntimebycallingthehooksascallbacks.
Metricmaincategories
Followsthemaincategoriesofmetrics:
db.<db-name>:databaserelatedmetrics
db.<db-name>.cache:metricsaboutdb'scaching
db.<db-name>.index:metricsaboutdb'sindexes
system:systemmetricslikeCPU,memory,OS,etc.
system.disk:Filesystemmetrics
process:notstrictlyrelatedtodatabasebuttotheprocess(JVM )thatisrunningOrientDBasclient,serverorembedded
process.network:networkmetrics
process.runtime:process'sruntimeinformationlikememoryused,etc
server:serverrelatedmetrics
Exampleofprofilervaluesextractedfromtheserveraftertestsuiteisrun(http://localhost:2480/profiler/realtime):
{
"realtime":{
"from":1344531312356,
"to":9223372036854776000,
"hookValues":{
"db.0$db.cache.level1.current":0,
"db.0$db.cache.level1.enabled":false,
"db.0$db.cache.level1.max":-1,
"db.0$db.cache.level2.current":0,
"db.0$db.cache.level2.enabled":true,
"db.0$db.cache.level2.max":-1,
"db.0$db.data.holeSize":0,
"db.0$db.data.holes":0,
"db.0$db.index.dictionary.entryPointSize":64,
"db.0$db.index.dictionary.items":0,
"db.0$db.index.dictionary.maxUpdateBeforeSave":5000,
"db.0$db.index.dictionary.optimizationThreshold":100000,
"db.1$db.cache.level1.current":0,
"db.1$db.cache.level1.enabled":false,
"db.1$db.cache.level1.max":-1,
"db.1$db.cache.level2.current":0,
"db.1$db.cache.level2.enabled":true,
"db.1$db.cache.level2.max":-1,
"db.1$db.data.holeSize":0,
"db.1$db.data.holes":0,
"db.1$db.index.dictionary.entryPointSize":64,
"db.1$db.index.dictionary.items":0,
"db.1$db.index.dictionary.maxUpdateBeforeSave":5000,
"db.1$db.index.dictionary.optimizationThreshold":100000,
"db.2$db.cache.level1.current":0,
"db.2$db.cache.level1.enabled":false,
"db.2$db.cache.level1.max":-1,
"db.2$db.cache.level2.current":0,
"db.2$db.cache.level2.enabled":true,
"db.2$db.cache.level2.max":-1,
"db.2$db.data.holeSize":0,
"db.2$db.data.holes":0,
"db.2$db.index.dictionary.entryPointSize":64,
"db.2$db.index.dictionary.items":0,
"db.2$db.index.dictionary.maxUpdateBeforeSave":5000,
"db.2$db.index.dictionary.optimizationThreshold":100000,
"db.demo.cache.level1.current":0,
"db.demo.cache.level1.enabled":false,
"db.demo.cache.level1.max":-1,
"db.demo.cache.level2.current":20520,
322
Profiler
"db.demo.cache.level2.enabled":true,
"db.demo.cache.level2.max":-1,
"db.demo.data.holeSize":47553,
"db.demo.data.holes":24,
"db.demo.index.BaseTestClass.testParentProperty.entryPointSize":64,
"db.demo.index.BaseTestClass.testParentProperty.items":2,
"db.demo.index.BaseTestClass.testParentProperty.maxUpdateBeforeSave":5000,
"db.demo.index.BaseTestClass.testParentProperty.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeEmbeddedList.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeEmbeddedList.items":0,
"db.demo.index.ClassIndexTestCompositeEmbeddedList.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeEmbeddedList.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeEmbeddedMap.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeEmbeddedMap.items":0,
"db.demo.index.ClassIndexTestCompositeEmbeddedMap.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeEmbeddedMap.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByKey.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByKey.items":0,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByKey.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByKey.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByValue.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByValue.items":0,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByValue.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeEmbeddedMapByValue.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeEmbeddedSet.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeEmbeddedSet.items":0,
"db.demo.index.ClassIndexTestCompositeEmbeddedSet.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeEmbeddedSet.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeLinkList.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeLinkList.items":0,
"db.demo.index.ClassIndexTestCompositeLinkList.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeLinkList.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeLinkMapByValue.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeLinkMapByValue.items":0,
"db.demo.index.ClassIndexTestCompositeLinkMapByValue.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeLinkMapByValue.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeOne.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeOne.items":0,
"db.demo.index.ClassIndexTestCompositeOne.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeOne.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestCompositeTwo.entryPointSize":64,
"db.demo.index.ClassIndexTestCompositeTwo.items":0,
"db.demo.index.ClassIndexTestCompositeTwo.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestCompositeTwo.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestDictionaryIndex.entryPointSize":64,
"db.demo.index.ClassIndexTestDictionaryIndex.items":0,
"db.demo.index.ClassIndexTestDictionaryIndex.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestDictionaryIndex.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestFulltextIndex.entryPointSize":64,
"db.demo.index.ClassIndexTestFulltextIndex.items":0,
"db.demo.index.ClassIndexTestFulltextIndex.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestFulltextIndex.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestNotUniqueIndex.entryPointSize":64,
"db.demo.index.ClassIndexTestNotUniqueIndex.items":0,
"db.demo.index.ClassIndexTestNotUniqueIndex.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestNotUniqueIndex.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestParentPropertyNine.entryPointSize":64,
"db.demo.index.ClassIndexTestParentPropertyNine.items":0,
"db.demo.index.ClassIndexTestParentPropertyNine.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestParentPropertyNine.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestPropertyByKeyEmbeddedMap.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyByKeyEmbeddedMap.items":0,
"db.demo.index.ClassIndexTestPropertyByKeyEmbeddedMap.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyByKeyEmbeddedMap.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestPropertyByValueEmbeddedMap.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyByValueEmbeddedMap.items":0,
"db.demo.index.ClassIndexTestPropertyByValueEmbeddedMap.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyByValueEmbeddedMap.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestPropertyEmbeddedMap.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyEmbeddedMap.items":0,
"db.demo.index.ClassIndexTestPropertyEmbeddedMap.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyEmbeddedMap.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestPropertyLinkedMap.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyLinkedMap.items":0,
"db.demo.index.ClassIndexTestPropertyLinkedMap.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyLinkedMap.optimizationThreshold":100000,
323
Profiler
"db.demo.index.ClassIndexTestPropertyLinkedMapByKey.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyLinkedMapByKey.items":0,
"db.demo.index.ClassIndexTestPropertyLinkedMapByKey.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyLinkedMapByKey.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestPropertyLinkedMapByValue.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyLinkedMapByValue.items":0,
"db.demo.index.ClassIndexTestPropertyLinkedMapByValue.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyLinkedMapByValue.optimizationThreshold":100000,
"db.demo.index.ClassIndexTestPropertyOne.entryPointSize":64,
"db.demo.index.ClassIndexTestPropertyOne.items":0,
"db.demo.index.ClassIndexTestPropertyOne.maxUpdateBeforeSave":5000,
"db.demo.index.ClassIndexTestPropertyOne.optimizationThreshold":100000,
"db.demo.index.Collector.stringCollection.entryPointSize":64,
"db.demo.index.Collector.stringCollection.items":0,
"db.demo.index.Collector.stringCollection.maxUpdateBeforeSave":5000,
"db.demo.index.Collector.stringCollection.optimizationThreshold":100000,
"db.demo.index.DropPropertyIndexCompositeIndex.entryPointSize":64,
"db.demo.index.DropPropertyIndexCompositeIndex.items":0,
"db.demo.index.DropPropertyIndexCompositeIndex.maxUpdateBeforeSave":5000,
"db.demo.index.DropPropertyIndexCompositeIndex.optimizationThreshold":100000,
"db.demo.index.Fruit.color.entryPointSize":64,
"db.demo.index.Fruit.color.items":0,
"db.demo.index.Fruit.color.maxUpdateBeforeSave":5000,
"db.demo.index.Fruit.color.optimizationThreshold":100000,
"db.demo.index.IndexCountPlusCondition.entryPointSize":64,
"db.demo.index.IndexCountPlusCondition.items":5,
"db.demo.index.IndexCountPlusCondition.maxUpdateBeforeSave":5000,
"db.demo.index.IndexCountPlusCondition.optimizationThreshold":100000,
"db.demo.index.IndexNotUniqueIndexKeySize.entryPointSize":64,
"db.demo.index.IndexNotUniqueIndexKeySize.items":5,
"db.demo.index.IndexNotUniqueIndexKeySize.maxUpdateBeforeSave":5000,
"db.demo.index.IndexNotUniqueIndexKeySize.optimizationThreshold":100000,
"db.demo.index.IndexNotUniqueIndexSize.entryPointSize":64,
"db.demo.index.IndexNotUniqueIndexSize.items":5,
"db.demo.index.IndexNotUniqueIndexSize.maxUpdateBeforeSave":5000,
"db.demo.index.IndexNotUniqueIndexSize.optimizationThreshold":100000,
"db.demo.index.MapPoint.x.entryPointSize":64,
"db.demo.index.MapPoint.x.items":9999,
"db.demo.index.MapPoint.x.maxUpdateBeforeSave":5000,
"db.demo.index.MapPoint.x.optimizationThreshold":100000,
"db.demo.index.MapPoint.y.entryPointSize":64,
"db.demo.index.MapPoint.y.items":10000,
"db.demo.index.MapPoint.y.maxUpdateBeforeSave":5000,
"db.demo.index.MapPoint.y.optimizationThreshold":100000,
"db.demo.index.MyFruit.color.entryPointSize":64,
"db.demo.index.MyFruit.color.items":10,
"db.demo.index.MyFruit.color.maxUpdateBeforeSave":5000,
"db.demo.index.MyFruit.color.optimizationThreshold":100000,
"db.demo.index.MyFruit.flavor.entryPointSize":64,
"db.demo.index.MyFruit.flavor.items":0,
"db.demo.index.MyFruit.flavor.maxUpdateBeforeSave":5000,
"db.demo.index.MyFruit.flavor.optimizationThreshold":100000,
"db.demo.index.MyFruit.name.entryPointSize":64,
"db.demo.index.MyFruit.name.items":5000,
"db.demo.index.MyFruit.name.maxUpdateBeforeSave":5000,
"db.demo.index.MyFruit.name.optimizationThreshold":100000,
"db.demo.index.MyProfile.name.entryPointSize":64,
"db.demo.index.MyProfile.name.items":3,
"db.demo.index.MyProfile.name.maxUpdateBeforeSave":5000,
"db.demo.index.MyProfile.name.optimizationThreshold":100000,
"db.demo.index.Profile.hash.entryPointSize":64,
"db.demo.index.Profile.hash.items":5,
"db.demo.index.Profile.hash.maxUpdateBeforeSave":5000,
"db.demo.index.Profile.hash.optimizationThreshold":100000,
"db.demo.index.Profile.name.entryPointSize":64,
"db.demo.index.Profile.name.items":20,
"db.demo.index.Profile.name.maxUpdateBeforeSave":5000,
"db.demo.index.Profile.name.optimizationThreshold":100000,
"db.demo.index.Profile.nick.entryPointSize":64,
"db.demo.index.Profile.nick.items":38,
"db.demo.index.Profile.nick.maxUpdateBeforeSave":5000,
"db.demo.index.Profile.nick.optimizationThreshold":100000,
"db.demo.index.PropertyIndexFirstIndex.entryPointSize":64,
"db.demo.index.PropertyIndexFirstIndex.items":0,
"db.demo.index.PropertyIndexFirstIndex.maxUpdateBeforeSave":5000,
"db.demo.index.PropertyIndexFirstIndex.optimizationThreshold":100000,
324
Profiler
"db.demo.index.PropertyIndexSecondIndex.entryPointSize":64,
"db.demo.index.PropertyIndexSecondIndex.items":0,
"db.demo.index.PropertyIndexSecondIndex.maxUpdateBeforeSave":5000,
"db.demo.index.PropertyIndexSecondIndex.optimizationThreshold":100000,
"db.demo.index.PropertyIndexTestClass.prop1.entryPointSize":64,
"db.demo.index.PropertyIndexTestClass.prop1.items":0,
"db.demo.index.PropertyIndexTestClass.prop1.maxUpdateBeforeSave":5000,
"db.demo.index.PropertyIndexTestClass.prop1.optimizationThreshold":100000,
"db.demo.index.SQLDropClassCompositeIndex.entryPointSize":64,
"db.demo.index.SQLDropClassCompositeIndex.items":0,
"db.demo.index.SQLDropClassCompositeIndex.maxUpdateBeforeSave":5000,
"db.demo.index.SQLDropClassCompositeIndex.optimizationThreshold":100000,
"db.demo.index.SQLDropIndexCompositeIndex.entryPointSize":64,
"db.demo.index.SQLDropIndexCompositeIndex.items":0,
"db.demo.index.SQLDropIndexCompositeIndex.maxUpdateBeforeSave":5000,
"db.demo.index.SQLDropIndexCompositeIndex.optimizationThreshold":100000,
"db.demo.index.SQLDropIndexTestClass.prop1.entryPointSize":64,
"db.demo.index.SQLDropIndexTestClass.prop1.items":0,
"db.demo.index.SQLDropIndexTestClass.prop1.maxUpdateBeforeSave":5000,
"db.demo.index.SQLDropIndexTestClass.prop1.optimizationThreshold":100000,
"db.demo.index.SQLDropIndexWithoutClass.entryPointSize":64,
"db.demo.index.SQLDropIndexWithoutClass.items":0,
"db.demo.index.SQLDropIndexWithoutClass.maxUpdateBeforeSave":5000,
"db.demo.index.SQLDropIndexWithoutClass.optimizationThreshold":100000,
"db.demo.index.SQLSelectCompositeIndexDirectSearchTestIndex.entryPointSize":64,
"db.demo.index.SQLSelectCompositeIndexDirectSearchTestIndex.items":0,
"db.demo.index.SQLSelectCompositeIndexDirectSearchTestIndex.maxUpdateBeforeSave":5000,
"db.demo.index.SQLSelectCompositeIndexDirectSearchTestIndex.optimizationThreshold":100000,
"db.demo.index.SchemaSharedIndexCompositeIndex.entryPointSize":64,
"db.demo.index.SchemaSharedIndexCompositeIndex.items":0,
"db.demo.index.SchemaSharedIndexCompositeIndex.maxUpdateBeforeSave":5000,
"db.demo.index.SchemaSharedIndexCompositeIndex.optimizationThreshold":100000,
"db.demo.index.TRPerson.name.entryPointSize":64,
"db.demo.index.TRPerson.name.items":4,
"db.demo.index.TRPerson.name.maxUpdateBeforeSave":5000,
"db.demo.index.TRPerson.name.optimizationThreshold":100000,
"db.demo.index.TRPerson.surname.entryPointSize":64,
"db.demo.index.TRPerson.surname.items":3,
"db.demo.index.TRPerson.surname.maxUpdateBeforeSave":5000,
"db.demo.index.TRPerson.surname.optimizationThreshold":100000,
"db.demo.index.TestClass.name.entryPointSize":64,
"db.demo.index.TestClass.name.items":2,
"db.demo.index.TestClass.name.maxUpdateBeforeSave":5000,
"db.demo.index.TestClass.name.optimizationThreshold":100000,
"db.demo.index.TestClass.testLink.entryPointSize":64,
"db.demo.index.TestClass.testLink.items":2,
"db.demo.index.TestClass.testLink.maxUpdateBeforeSave":5000,
"db.demo.index.TestClass.testLink.optimizationThreshold":100000,
"db.demo.index.TransactionUniqueIndexWithDotTest.label.entryPointSize":64,
"db.demo.index.TransactionUniqueIndexWithDotTest.label.items":1,
"db.demo.index.TransactionUniqueIndexWithDotTest.label.maxUpdateBeforeSave":5000,
"db.demo.index.TransactionUniqueIndexWithDotTest.label.optimizationThreshold":100000,
"db.demo.index.Whiz.account.entryPointSize":64,
"db.demo.index.Whiz.account.items":1,
"db.demo.index.Whiz.account.maxUpdateBeforeSave":5000,
"db.demo.index.Whiz.account.optimizationThreshold":100000,
"db.demo.index.Whiz.text.entryPointSize":64,
"db.demo.index.Whiz.text.items":275,
"db.demo.index.Whiz.text.maxUpdateBeforeSave":5000,
"db.demo.index.Whiz.text.optimizationThreshold":100000,
"db.demo.index.a.entryPointSize":64,
"db.demo.index.a.items":0,
"db.demo.index.a.maxUpdateBeforeSave":5000,
"db.demo.index.a.optimizationThreshold":100000,
"db.demo.index.anotherproperty.entryPointSize":64,
"db.demo.index.anotherproperty.items":0,
"db.demo.index.anotherproperty.maxUpdateBeforeSave":5000,
"db.demo.index.anotherproperty.optimizationThreshold":100000,
"db.demo.index.byte-array-manualIndex-notunique.entryPointSize":64,
"db.demo.index.byte-array-manualIndex-notunique.items":6,
"db.demo.index.byte-array-manualIndex-notunique.maxUpdateBeforeSave":5000,
"db.demo.index.byte-array-manualIndex-notunique.optimizationThreshold":100000,
"db.demo.index.byte-array-manualIndex.entryPointSize":64,
"db.demo.index.byte-array-manualIndex.items":11,
"db.demo.index.byte-array-manualIndex.maxUpdateBeforeSave":5000,
"db.demo.index.byte-array-manualIndex.optimizationThreshold":100000,
325
Profiler
"db.demo.index.byteArrayKeyIndex.entryPointSize":64,
"db.demo.index.byteArrayKeyIndex.items":2,
"db.demo.index.byteArrayKeyIndex.maxUpdateBeforeSave":5000,
"db.demo.index.byteArrayKeyIndex.optimizationThreshold":100000,
"db.demo.index.classIndexManagerComposite.entryPointSize":64,
"db.demo.index.classIndexManagerComposite.items":0,
"db.demo.index.classIndexManagerComposite.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerComposite.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestClass.prop1.entryPointSize":64,
"db.demo.index.classIndexManagerTestClass.prop1.items":0,
"db.demo.index.classIndexManagerTestClass.prop1.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestClass.prop1.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestClass.prop2.entryPointSize":64,
"db.demo.index.classIndexManagerTestClass.prop2.items":0,
"db.demo.index.classIndexManagerTestClass.prop2.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestClass.prop2.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestClass.prop4.entryPointSize":64,
"db.demo.index.classIndexManagerTestClass.prop4.items":0,
"db.demo.index.classIndexManagerTestClass.prop4.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestClass.prop4.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestClass.prop6.entryPointSize":64,
"db.demo.index.classIndexManagerTestClass.prop6.items":0,
"db.demo.index.classIndexManagerTestClass.prop6.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestClass.prop6.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestIndexByKey.entryPointSize":64,
"db.demo.index.classIndexManagerTestIndexByKey.items":0,
"db.demo.index.classIndexManagerTestIndexByKey.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestIndexByKey.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestIndexByValue.entryPointSize":64,
"db.demo.index.classIndexManagerTestIndexByValue.items":0,
"db.demo.index.classIndexManagerTestIndexByValue.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestIndexByValue.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestIndexValueAndCollection.entryPointSize":64,
"db.demo.index.classIndexManagerTestIndexValueAndCollection.items":0,
"db.demo.index.classIndexManagerTestIndexValueAndCollection.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestIndexValueAndCollection.optimizationThreshold":100000,
"db.demo.index.classIndexManagerTestSuperClass.prop0.entryPointSize":64,
"db.demo.index.classIndexManagerTestSuperClass.prop0.items":0,
"db.demo.index.classIndexManagerTestSuperClass.prop0.maxUpdateBeforeSave":5000,
"db.demo.index.classIndexManagerTestSuperClass.prop0.optimizationThreshold":100000,
"db.demo.index.compositeByteArrayKey.entryPointSize":64,
"db.demo.index.compositeByteArrayKey.items":4,
"db.demo.index.compositeByteArrayKey.maxUpdateBeforeSave":5000,
"db.demo.index.compositeByteArrayKey.optimizationThreshold":100000,
"db.demo.index.compositeIndexWithoutSchema.entryPointSize":64,
"db.demo.index.compositeIndexWithoutSchema.items":0,
"db.demo.index.compositeIndexWithoutSchema.maxUpdateBeforeSave":5000,
"db.demo.index.compositeIndexWithoutSchema.optimizationThreshold":100000,
"db.demo.index.compositeone.entryPointSize":64,
"db.demo.index.compositeone.items":0,
"db.demo.index.compositeone.maxUpdateBeforeSave":5000,
"db.demo.index.compositeone.optimizationThreshold":100000,
"db.demo.index.compositetwo.entryPointSize":64,
"db.demo.index.compositetwo.items":0,
"db.demo.index.compositetwo.maxUpdateBeforeSave":5000,
"db.demo.index.compositetwo.optimizationThreshold":100000,
"db.demo.index.curotorCompositeIndex.entryPointSize":64,
"db.demo.index.curotorCompositeIndex.items":0,
"db.demo.index.curotorCompositeIndex.maxUpdateBeforeSave":5000,
"db.demo.index.curotorCompositeIndex.optimizationThreshold":100000,
"db.demo.index.dictionary.entryPointSize":64,
"db.demo.index.dictionary.items":2,
"db.demo.index.dictionary.maxUpdateBeforeSave":5000,
"db.demo.index.dictionary.optimizationThreshold":100000,
"db.demo.index.diplomaThesisUnique.entryPointSize":64,
"db.demo.index.diplomaThesisUnique.items":3,
"db.demo.index.diplomaThesisUnique.maxUpdateBeforeSave":5000,
"db.demo.index.diplomaThesisUnique.optimizationThreshold":100000,
"db.demo.index.equalityIdx.entryPointSize":64,
"db.demo.index.equalityIdx.items":0,
"db.demo.index.equalityIdx.maxUpdateBeforeSave":5000,
"db.demo.index.equalityIdx.optimizationThreshold":100000,
"db.demo.index.idx.entryPointSize":64,
"db.demo.index.idx.items":2,
"db.demo.index.idx.maxUpdateBeforeSave":5000,
"db.demo.index.idx.optimizationThreshold":100000,
326
Profiler
"db.demo.index.idxTerm.entryPointSize":64,
"db.demo.index.idxTerm.items":1,
"db.demo.index.idxTerm.maxUpdateBeforeSave":5000,
"db.demo.index.idxTerm.optimizationThreshold":100000,
"db.demo.index.idxTransactionUniqueIndexTest.entryPointSize":64,
"db.demo.index.idxTransactionUniqueIndexTest.items":1,
"db.demo.index.idxTransactionUniqueIndexTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTransactionUniqueIndexTest.optimizationThreshold":100000,
"db.demo.index.idxTxAwareMultiValueGetEntriesTest.entryPointSize":64,
"db.demo.index.idxTxAwareMultiValueGetEntriesTest.items":0,
"db.demo.index.idxTxAwareMultiValueGetEntriesTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTxAwareMultiValueGetEntriesTest.optimizationThreshold":100000,
"db.demo.index.idxTxAwareMultiValueGetTest.entryPointSize":64,
"db.demo.index.idxTxAwareMultiValueGetTest.items":0,
"db.demo.index.idxTxAwareMultiValueGetTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTxAwareMultiValueGetTest.optimizationThreshold":100000,
"db.demo.index.idxTxAwareMultiValueGetValuesTest.entryPointSize":64,
"db.demo.index.idxTxAwareMultiValueGetValuesTest.items":0,
"db.demo.index.idxTxAwareMultiValueGetValuesTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTxAwareMultiValueGetValuesTest.optimizationThreshold":100000,
"db.demo.index.idxTxAwareOneValueGetEntriesTest.entryPointSize":64,
"db.demo.index.idxTxAwareOneValueGetEntriesTest.items":0,
"db.demo.index.idxTxAwareOneValueGetEntriesTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTxAwareOneValueGetEntriesTest.optimizationThreshold":100000,
"db.demo.index.idxTxAwareOneValueGetTest.entryPointSize":64,
"db.demo.index.idxTxAwareOneValueGetTest.items":0,
"db.demo.index.idxTxAwareOneValueGetTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTxAwareOneValueGetTest.optimizationThreshold":100000,
"db.demo.index.idxTxAwareOneValueGetValuesTest.entryPointSize":64,
"db.demo.index.idxTxAwareOneValueGetValuesTest.items":0,
"db.demo.index.idxTxAwareOneValueGetValuesTest.maxUpdateBeforeSave":5000,
"db.demo.index.idxTxAwareOneValueGetValuesTest.optimizationThreshold":100000,
"db.demo.index.inIdx.entryPointSize":64,
"db.demo.index.inIdx.items":0,
"db.demo.index.inIdx.maxUpdateBeforeSave":5000,
"db.demo.index.inIdx.optimizationThreshold":100000,
"db.demo.index.indexForMap.entryPointSize":64,
"db.demo.index.indexForMap.items":0,
"db.demo.index.indexForMap.maxUpdateBeforeSave":5000,
"db.demo.index.indexForMap.optimizationThreshold":100000,
"db.demo.index.indexWithoutSchema.entryPointSize":64,
"db.demo.index.indexWithoutSchema.items":0,
"db.demo.index.indexWithoutSchema.maxUpdateBeforeSave":5000,
"db.demo.index.indexWithoutSchema.optimizationThreshold":100000,
"db.demo.index.indexfive.entryPointSize":64,
"db.demo.index.indexfive.items":0,
"db.demo.index.indexfive.maxUpdateBeforeSave":5000,
"db.demo.index.indexfive.optimizationThreshold":100000,
"db.demo.index.indexfour.entryPointSize":64,
"db.demo.index.indexfour.items":0,
"db.demo.index.indexfour.maxUpdateBeforeSave":5000,
"db.demo.index.indexfour.optimizationThreshold":100000,
"db.demo.index.indexone.entryPointSize":64,
"db.demo.index.indexone.items":0,
"db.demo.index.indexone.maxUpdateBeforeSave":5000,
"db.demo.index.indexone.optimizationThreshold":100000,
"db.demo.index.indexsix.entryPointSize":64,
"db.demo.index.indexsix.items":0,
"db.demo.index.indexsix.maxUpdateBeforeSave":5000,
"db.demo.index.indexsix.optimizationThreshold":100000,
"db.demo.index.indexthree.entryPointSize":64,
"db.demo.index.indexthree.items":0,
"db.demo.index.indexthree.maxUpdateBeforeSave":5000,
"db.demo.index.indexthree.optimizationThreshold":100000,
"db.demo.index.indextwo.entryPointSize":64,
"db.demo.index.indextwo.items":0,
"db.demo.index.indextwo.maxUpdateBeforeSave":5000,
"db.demo.index.indextwo.optimizationThreshold":100000,
"db.demo.index.linkCollectionIndex.entryPointSize":64,
"db.demo.index.linkCollectionIndex.items":0,
"db.demo.index.linkCollectionIndex.maxUpdateBeforeSave":5000,
"db.demo.index.linkCollectionIndex.optimizationThreshold":100000,
"db.demo.index.lpirtCurator.name.entryPointSize":64,
"db.demo.index.lpirtCurator.name.items":0,
"db.demo.index.lpirtCurator.name.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtCurator.name.optimizationThreshold":100000,
327
Profiler
"db.demo.index.lpirtCurator.salary.entryPointSize":64,
"db.demo.index.lpirtCurator.salary.items":0,
"db.demo.index.lpirtCurator.salary.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtCurator.salary.optimizationThreshold":100000,
"db.demo.index.lpirtDiploma.GPA.entryPointSize":64,
"db.demo.index.lpirtDiploma.GPA.items":3,
"db.demo.index.lpirtDiploma.GPA.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtDiploma.GPA.optimizationThreshold":100000,
"db.demo.index.lpirtDiploma.thesis.entryPointSize":64,
"db.demo.index.lpirtDiploma.thesis.items":54,
"db.demo.index.lpirtDiploma.thesis.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtDiploma.thesis.optimizationThreshold":100000,
"db.demo.index.lpirtGroup.curator.entryPointSize":64,
"db.demo.index.lpirtGroup.curator.items":0,
"db.demo.index.lpirtGroup.curator.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtGroup.curator.optimizationThreshold":100000,
"db.demo.index.lpirtGroup.name.entryPointSize":64,
"db.demo.index.lpirtGroup.name.items":0,
"db.demo.index.lpirtGroup.name.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtGroup.name.optimizationThreshold":100000,
"db.demo.index.lpirtStudent.group.entryPointSize":64,
"db.demo.index.lpirtStudent.group.items":0,
"db.demo.index.lpirtStudent.group.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtStudent.group.optimizationThreshold":100000,
"db.demo.index.lpirtStudent.name.entryPointSize":64,
"db.demo.index.lpirtStudent.name.items":0,
"db.demo.index.lpirtStudent.name.maxUpdateBeforeSave":5000,
"db.demo.index.lpirtStudent.name.optimizationThreshold":100000,
"db.demo.index.manualTxIndexTest.entryPointSize":64,
"db.demo.index.manualTxIndexTest.items":1,
"db.demo.index.manualTxIndexTest.maxUpdateBeforeSave":5000,
"db.demo.index.manualTxIndexTest.optimizationThreshold":100000,
"db.demo.index.mapIndexTestKey.entryPointSize":64,
"db.demo.index.mapIndexTestKey.items":0,
"db.demo.index.mapIndexTestKey.maxUpdateBeforeSave":5000,
"db.demo.index.mapIndexTestKey.optimizationThreshold":100000,
"db.demo.index.mapIndexTestValue.entryPointSize":64,
"db.demo.index.mapIndexTestValue.items":0,
"db.demo.index.mapIndexTestValue.maxUpdateBeforeSave":5000,
"db.demo.index.mapIndexTestValue.optimizationThreshold":100000,
"db.demo.index.newV.f_int.entryPointSize":64,
"db.demo.index.newV.f_int.items":3,
"db.demo.index.newV.f_int.maxUpdateBeforeSave":5000,
"db.demo.index.newV.f_int.optimizationThreshold":100000,
"db.demo.index.nullkey.entryPointSize":64,
"db.demo.index.nullkey.items":0,
"db.demo.index.nullkey.maxUpdateBeforeSave":5000,
"db.demo.index.nullkey.optimizationThreshold":100000,
"db.demo.index.nullkeytwo.entryPointSize":64,
"db.demo.index.nullkeytwo.items":0,
"db.demo.index.nullkeytwo.maxUpdateBeforeSave":5000,
"db.demo.index.nullkeytwo.optimizationThreshold":100000,
"db.demo.index.propOne1.entryPointSize":64,
"db.demo.index.propOne1.items":0,
"db.demo.index.propOne1.maxUpdateBeforeSave":5000,
"db.demo.index.propOne1.optimizationThreshold":100000,
"db.demo.index.propOne2.entryPointSize":64,
"db.demo.index.propOne2.items":0,
"db.demo.index.propOne2.maxUpdateBeforeSave":5000,
"db.demo.index.propOne2.optimizationThreshold":100000,
"db.demo.index.propOne3.entryPointSize":64,
"db.demo.index.propOne3.items":0,
"db.demo.index.propOne3.maxUpdateBeforeSave":5000,
"db.demo.index.propOne3.optimizationThreshold":100000,
"db.demo.index.propOne4.entryPointSize":64,
"db.demo.index.propOne4.items":0,
"db.demo.index.propOne4.maxUpdateBeforeSave":5000,
"db.demo.index.propOne4.optimizationThreshold":100000,
"db.demo.index.propertyone.entryPointSize":64,
"db.demo.index.propertyone.items":0,
"db.demo.index.propertyone.maxUpdateBeforeSave":5000,
"db.demo.index.propertyone.optimizationThreshold":100000,
"db.demo.index.simplekey.entryPointSize":64,
"db.demo.index.simplekey.items":0,
"db.demo.index.simplekey.maxUpdateBeforeSave":5000,
"db.demo.index.simplekey.optimizationThreshold":100000,
328
Profiler
"db.demo.index.simplekeytwo.entryPointSize":64,
"db.demo.index.simplekeytwo.items":0,
"db.demo.index.simplekeytwo.maxUpdateBeforeSave":5000,
"db.demo.index.simplekeytwo.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexCompositeIndex.entryPointSize":64,
"db.demo.index.sqlCreateIndexCompositeIndex.items":0,
"db.demo.index.sqlCreateIndexCompositeIndex.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexCompositeIndex.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexCompositeIndex2.entryPointSize":64,
"db.demo.index.sqlCreateIndexCompositeIndex2.items":0,
"db.demo.index.sqlCreateIndexCompositeIndex2.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexCompositeIndex2.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexEmbeddedListIndex.entryPointSize":64,
"db.demo.index.sqlCreateIndexEmbeddedListIndex.items":0,
"db.demo.index.sqlCreateIndexEmbeddedListIndex.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexEmbeddedListIndex.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexEmbeddedMapByKeyIndex.entryPointSize":64,
"db.demo.index.sqlCreateIndexEmbeddedMapByKeyIndex.items":0,
"db.demo.index.sqlCreateIndexEmbeddedMapByKeyIndex.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexEmbeddedMapByKeyIndex.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexEmbeddedMapByValueIndex.entryPointSize":64,
"db.demo.index.sqlCreateIndexEmbeddedMapByValueIndex.items":0,
"db.demo.index.sqlCreateIndexEmbeddedMapByValueIndex.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexEmbeddedMapByValueIndex.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexEmbeddedMapIndex.entryPointSize":64,
"db.demo.index.sqlCreateIndexEmbeddedMapIndex.items":0,
"db.demo.index.sqlCreateIndexEmbeddedMapIndex.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexEmbeddedMapIndex.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexTestClass.prop1.entryPointSize":64,
"db.demo.index.sqlCreateIndexTestClass.prop1.items":0,
"db.demo.index.sqlCreateIndexTestClass.prop1.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexTestClass.prop1.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexTestClass.prop3.entryPointSize":64,
"db.demo.index.sqlCreateIndexTestClass.prop3.items":0,
"db.demo.index.sqlCreateIndexTestClass.prop3.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexTestClass.prop3.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexTestClass.prop5.entryPointSize":64,
"db.demo.index.sqlCreateIndexTestClass.prop5.items":0,
"db.demo.index.sqlCreateIndexTestClass.prop5.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexTestClass.prop5.optimizationThreshold":100000,
"db.demo.index.sqlCreateIndexWithoutClass.entryPointSize":64,
"db.demo.index.sqlCreateIndexWithoutClass.items":0,
"db.demo.index.sqlCreateIndexWithoutClass.maxUpdateBeforeSave":5000,
"db.demo.index.sqlCreateIndexWithoutClass.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedList.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedList.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedList.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedList.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedListTwoProp8.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedListTwoProp8.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedListTwoProp8.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedListTwoProp8.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKey.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKey.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKey.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKey.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKeyProp8.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKeyProp8.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKeyProp8.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByKeyProp8.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValue.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValue.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValue.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValue.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValueProp8.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValueProp8.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValueProp8.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedMapByValueProp8.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedSetProp8.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedSetProp8.items":0,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedSetProp8.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestEmbeddedSetProp8.optimizationThreshold":100000,
"db.demo.index.sqlSelectIndexReuseTestProp9EmbeddedSetProp8.entryPointSize":64,
"db.demo.index.sqlSelectIndexReuseTestProp9EmbeddedSetProp8.items":0,
"db.demo.index.sqlSelectIndexReuseTestProp9EmbeddedSetProp8.maxUpdateBeforeSave":5000,
"db.demo.index.sqlSelectIndexReuseTestProp9EmbeddedSetProp8.optimizationThreshold":100000,
329
Profiler
"db.demo.index.studentDiplomaAndNameIndex.entryPointSize":64,
"db.demo.index.studentDiplomaAndNameIndex.items":0,
"db.demo.index.studentDiplomaAndNameIndex.maxUpdateBeforeSave":5000,
"db.demo.index.studentDiplomaAndNameIndex.optimizationThreshold":100000,
"db.demo.index.testIdx.entryPointSize":64,
"db.demo.index.testIdx.items":1,
"db.demo.index.testIdx.maxUpdateBeforeSave":5000,
"db.demo.index.testIdx.optimizationThreshold":100000,
"db.demo.index.test_class_by_data.entryPointSize":64,
"db.demo.index.test_class_by_data.items":0,
"db.demo.index.test_class_by_data.maxUpdateBeforeSave":5000,
"db.demo.index.test_class_by_data.optimizationThreshold":100000,
"db.demo.index.twoclassproperty.entryPointSize":64,
"db.demo.index.twoclassproperty.items":0,
"db.demo.index.twoclassproperty.maxUpdateBeforeSave":5000,
"db.demo.index.twoclassproperty.optimizationThreshold":100000,
"db.demo.index.vertexA_name_idx.entryPointSize":64,
"db.demo.index.vertexA_name_idx.items":2,
"db.demo.index.vertexA_name_idx.maxUpdateBeforeSave":5000,
"db.demo.index.vertexA_name_idx.optimizationThreshold":100000,
"db.demo.index.vertexB_name_idx.entryPointSize":64,
"db.demo.index.vertexB_name_idx.items":2,
"db.demo.index.vertexB_name_idx.maxUpdateBeforeSave":5000,
"db.demo.index.vertexB_name_idx.optimizationThreshold":100000,
"db.subTest.cache.level1.current":0,
"db.subTest.cache.level1.enabled":false,
"db.subTest.cache.level1.max":-1,
"db.subTest.cache.level2.current":0,
"db.subTest.cache.level2.enabled":false,
"db.subTest.cache.level2.max":-1,
"db.subTest.data.holeSize":0,
"db.subTest.data.holes":0,
"db.subTest.index.dictionary.entryPointSize":64,
"db.subTest.index.dictionary.items":0,
"db.subTest.index.dictionary.maxUpdateBeforeSave":5000,
"db.subTest.index.dictionary.optimizationThreshold":100000,
"db.temp.cache.level1.current":0,
"db.temp.cache.level1.enabled":false,
"db.temp.cache.level1.max":-1,
"db.temp.cache.level2.current":3,
"db.temp.cache.level2.enabled":true,
"db.temp.cache.level2.max":-1,
"db.temp.index.dictionary.entryPointSize":64,
"db.temp.index.dictionary.items":0,
"db.temp.index.dictionary.maxUpdateBeforeSave":5000,
"db.temp.index.dictionary.optimizationThreshold":100000,
"process.network.channel.binary./0:0:0:0:0:0:0:1:451822480.flushes":0,
"process.network.channel.binary./0:0:0:0:0:0:0:1:451822480.receivedBytes":513,
"process.network.channel.binary./0:0:0:0:0:0:0:1:451822480.transmittedBytes":0,
"process.network.channel.binary./127.0.0.1:451282424.flushes":3,
"process.network.channel.binary./127.0.0.1:451282424.receivedBytes":98,
"process.network.channel.binary./127.0.0.1:451282424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451292424.flushes":3,
"process.network.channel.binary./127.0.0.1:451292424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451292424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451352424.flushes":3,
"process.network.channel.binary./127.0.0.1:451352424.receivedBytes":79,
"process.network.channel.binary./127.0.0.1:451352424.transmittedBytes":134,
"process.network.channel.binary./127.0.0.1:451362424.flushes":3,
"process.network.channel.binary./127.0.0.1:451362424.receivedBytes":105,
"process.network.channel.binary./127.0.0.1:451362424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451382424.flushes":3,
"process.network.channel.binary./127.0.0.1:451382424.receivedBytes":79,
"process.network.channel.binary./127.0.0.1:451382424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451392424.flushes":3,
"process.network.channel.binary./127.0.0.1:451392424.receivedBytes":79,
"process.network.channel.binary./127.0.0.1:451392424.transmittedBytes":134,
"process.network.channel.binary./127.0.0.1:451402424.flushes":3,
"process.network.channel.binary./127.0.0.1:451402424.receivedBytes":105,
"process.network.channel.binary./127.0.0.1:451402424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451422424.flushes":3,
"process.network.channel.binary./127.0.0.1:451422424.receivedBytes":79,
"process.network.channel.binary./127.0.0.1:451422424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451432424.flushes":3,
"process.network.channel.binary./127.0.0.1:451432424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451432424.transmittedBytes":127,
330
Profiler
"process.network.channel.binary./127.0.0.1:451442424.flushes":3,
"process.network.channel.binary./127.0.0.1:451442424.receivedBytes":98,
"process.network.channel.binary./127.0.0.1:451442424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451452424.flushes":3,
"process.network.channel.binary./127.0.0.1:451452424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451452424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451462424.flushes":7,
"process.network.channel.binary./127.0.0.1:451462424.receivedBytes":194,
"process.network.channel.binary./127.0.0.1:451462424.transmittedBytes":2606,
"process.network.channel.binary./127.0.0.1:451472424.flushes":3,
"process.network.channel.binary./127.0.0.1:451472424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451472424.transmittedBytes":127,
"process.network.channel.binary./127.0.0.1:451482424.flushes":3,
"process.network.channel.binary./127.0.0.1:451482424.receivedBytes":98,
"process.network.channel.binary./127.0.0.1:451482424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451492424.flushes":3,
"process.network.channel.binary./127.0.0.1:451492424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451492424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451502424.flushes":7,
"process.network.channel.binary./127.0.0.1:451502424.receivedBytes":194,
"process.network.channel.binary./127.0.0.1:451502424.transmittedBytes":2606,
"process.network.channel.binary./127.0.0.1:451512424.flushes":3,
"process.network.channel.binary./127.0.0.1:451512424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451512424.transmittedBytes":127,
"process.network.channel.binary./127.0.0.1:451522424.flushes":3,
"process.network.channel.binary./127.0.0.1:451522424.receivedBytes":98,
"process.network.channel.binary./127.0.0.1:451522424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451532424.flushes":3,
"process.network.channel.binary./127.0.0.1:451532424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451532424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451542424.flushes":7,
"process.network.channel.binary./127.0.0.1:451542424.receivedBytes":194,
"process.network.channel.binary./127.0.0.1:451542424.transmittedBytes":2606,
"process.network.channel.binary./127.0.0.1:451552424.flushes":3,
"process.network.channel.binary./127.0.0.1:451552424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451552424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451562424.flushes":3,
"process.network.channel.binary./127.0.0.1:451562424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451562424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451572424.flushes":3,
"process.network.channel.binary./127.0.0.1:451572424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451572424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451582424.flushes":3,
"process.network.channel.binary./127.0.0.1:451582424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451582424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451592424.flushes":3,
"process.network.channel.binary./127.0.0.1:451592424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451592424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451602424.flushes":3,
"process.network.channel.binary./127.0.0.1:451602424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451602424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451612424.flushes":3,
"process.network.channel.binary./127.0.0.1:451612424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451612424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451622424.flushes":3,
"process.network.channel.binary./127.0.0.1:451622424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451622424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451632424.flushes":3,
"process.network.channel.binary./127.0.0.1:451632424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451632424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451642424.flushes":3,
"process.network.channel.binary./127.0.0.1:451642424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451642424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451652424.flushes":3,
"process.network.channel.binary./127.0.0.1:451652424.receivedBytes":98,
"process.network.channel.binary./127.0.0.1:451652424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451672424.flushes":3,
"process.network.channel.binary./127.0.0.1:451672424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451672424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451682424.flushes":3,
"process.network.channel.binary./127.0.0.1:451682424.receivedBytes":98,
"process.network.channel.binary./127.0.0.1:451682424.transmittedBytes":16,
"process.network.channel.binary./127.0.0.1:451692424.flushes":3,
"process.network.channel.binary./127.0.0.1:451692424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451692424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451702424.flushes":76545,
331
Profiler
"process.network.channel.binary./127.0.0.1:451702424.receivedBytes":4937639,
"process.network.channel.binary./127.0.0.1:451702424.transmittedBytes":53391585,
"process.network.channel.binary./127.0.0.1:451712424.flushes":3,
"process.network.channel.binary./127.0.0.1:451712424.receivedBytes":72,
"process.network.channel.binary./127.0.0.1:451712424.transmittedBytes":17,
"process.network.channel.binary./127.0.0.1:451762424.flushes":16176,
"process.network.channel.binary./127.0.0.1:451762424.receivedBytes":435578,
"process.network.channel.binary./127.0.0.1:451762424.transmittedBytes":7744941,
"process.network.channel.binary./127.0.0.1:451772424.flushes":16181,
"process.network.channel.binary./127.0.0.1:451772424.receivedBytes":446949,
"process.network.channel.binary./127.0.0.1:451772424.transmittedBytes":7932617,
"process.network.channel.binary./127.0.0.1:451782424.flushes":16103,
"process.network.channel.binary./127.0.0.1:451782424.receivedBytes":437708,
"process.network.channel.binary./127.0.0.1:451782424.transmittedBytes":7192022,
"process.network.channel.binary./127.0.0.1:451792424.flushes":15663,
"process.network.channel.binary./127.0.0.1:451792424.receivedBytes":422013,
"process.network.channel.binary./127.0.0.1:451792424.transmittedBytes":1128841,
"process.network.channel.binary.flushes":140851,
"process.network.channel.binary.receivedBytes":6687263,
"process.network.channel.binary.transmittedBytes":77419866,
"process.runtime.availableMemory":311502288,
"process.runtime.maxMemory":939524096,
"process.runtime.totalMemory":442368000,
"server.connections.actives":101,
"system.config.cpus":8,
"system.disk.C.freeSpace":50445692928,
"system.disk.C.totalSpace":127928365056,
"system.disk.C.usableSpace":50445692928,
"system.disk.D.freeSpace":0,
"system.disk.D.totalSpace":0,
"system.disk.D.usableSpace":0,
"system.disk.G.freeSpace":12820815872,
"system.disk.G.totalSpace":500103213056,
"system.disk.G.usableSpace":12820815872,
"system.file.mmap.mappedPages":177,
"system.file.mmap.nonPooledBufferUsed":0,
"system.file.mmap.pooledBufferCreated":0,
"system.file.mmap.pooledBufferUsed":0,
"system.file.mmap.reusedPages":31698774,
"system.memory.alerts":0,
"system.memory.stream.resize":21154
},
"chronos":{
"db.0$db.close":{
"entries":4,
"last":16,
"min":0,
"max":16,
"average":4,
"total":16
},
"db.0$db.create":{
"entries":1,
"last":13,
"min":13,
"max":13,
"average":13,
"total":13
},
"db.0$db.createRecord":{
"entries":10,
"last":1,
"min":0,
"max":1,
"average":0,
"total":6
},
"db.0$db.data.createHole":{
"entries":14,
"last":2,
"min":0,
"max":2,
"average":0,
"total":8
},
"db.0$db.data.findClosestHole":{
332
Profiler
"entries":11,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.0$db.data.move":{
"entries":6,
"last":1,
"min":0,
"max":1,
"average":0,
"total":3
},
"db.0$db.data.recycled.notFound":{
"entries":7,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.0$db.data.recycled.partial":{
"entries":11,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.0$db.data.updateHole":{
"entries":21,
"last":0,
"min":0,
"max":1,
"average":0,
"total":2
},
"db.0$db.delete":{
"entries":1,
"last":101,
"min":101,
"max":101,
"average":101,
"total":101
},
"db.0$db.metadata.load":{
"entries":3,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.0$db.open":{
"entries":3,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.0$db.readRecord":{
"entries":15,
"last":0,
"min":0,
"max":1,
"average":0,
"total":5
},
"db.0$db.updateRecord":{
"entries":18,
"last":2,
"min":0,
"max":2,
333
Profiler
"average":0,
"total":9
},
"db.1$db.close":{
"entries":4,
"last":13,
"min":0,
"max":13,
"average":3,
"total":13
},
"db.1$db.create":{
"entries":1,
"last":15,
"min":15,
"max":15,
"average":15,
"total":15
},
"db.1$db.createRecord":{
"entries":10,
"last":1,
"min":0,
"max":1,
"average":0,
"total":5
},
"db.1$db.data.createHole":{
"entries":14,
"last":3,
"min":0,
"max":3,
"average":0,
"total":8
},
"db.1$db.data.findClosestHole":{
"entries":11,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.1$db.data.move":{
"entries":6,
"last":0,
"min":0,
"max":1,
"average":0,
"total":3
},
"db.1$db.data.recycled.notFound":{
"entries":7,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.1$db.data.recycled.partial":{
"entries":11,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.1$db.data.updateHole":{
"entries":21,
"last":1,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.1$db.delete":{
334
Profiler
"entries":1,
"last":115,
"min":115,
"max":115,
"average":115,
"total":115
},
"db.1$db.metadata.load":{
"entries":3,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.1$db.open":{
"entries":3,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.1$db.readRecord":{
"entries":15,
"last":0,
"min":0,
"max":1,
"average":0,
"total":4
},
"db.1$db.updateRecord":{
"entries":18,
"last":3,
"min":0,
"max":3,
"average":0,
"total":7
},
"db.2$db.close":{
"entries":4,
"last":15,
"min":0,
"max":15,
"average":3,
"total":15
},
"db.2$db.create":{
"entries":1,
"last":17,
"min":17,
"max":17,
"average":17,
"total":17
},
"db.2$db.createRecord":{
"entries":10,
"last":1,
"min":0,
"max":1,
"average":0,
"total":5
},
"db.2$db.data.createHole":{
"entries":14,
"last":1,
"min":0,
"max":1,
"average":0,
"total":5
},
"db.2$db.data.findClosestHole":{
"entries":11,
"last":0,
"min":0,
"max":0,
335
Profiler
"average":0,
"total":0
},
"db.2$db.data.move":{
"entries":6,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.2$db.data.recycled.notFound":{
"entries":7,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.2$db.data.recycled.partial":{
"entries":11,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.2$db.data.updateHole":{
"entries":21,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.2$db.delete":{
"entries":1,
"last":61,
"min":61,
"max":61,
"average":61,
"total":61
},
"db.2$db.metadata.load":{
"entries":3,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.2$db.open":{
"entries":3,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.2$db.readRecord":{
"entries":15,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.2$db.updateRecord":{
"entries":18,
"last":1,
"min":0,
"max":1,
"average":0,
"total":5
},
"db.demo.close":{
336
Profiler
"entries":1396,
"last":0,
"min":0,
"max":31,
"average":0,
"total":51
},
"db.demo.create":{
"entries":3,
"last":19,
"min":19,
"max":40,
"average":27,
"total":81
},
"db.demo.createRecord":{
"entries":35716,
"last":0,
"min":0,
"max":12,
"average":0,
"total":1187
},
"db.demo.data.createHole":{
"entries":58886,
"last":0,
"min":0,
"max":23,
"average":0,
"total":9822
},
"db.demo.data.findClosestHole":{
"entries":51022,
"last":0,
"min":0,
"max":1,
"average":0,
"total":181
},
"db.demo.data.move":{
"entries":1327946,
"last":0,
"min":0,
"max":16,
"average":0,
"total":4091
},
"db.demo.data.recycled.complete":{
"entries":24,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.demo.data.recycled.notFound":{
"entries":16070,
"last":0,
"min":0,
"max":1,
"average":0,
"total":59
},
"db.demo.data.recycled.partial":{
"entries":57638,
"last":0,
"min":0,
"max":1,
"average":0,
"total":102
},
"db.demo.data.updateHole":{
"entries":108613,
"last":0,
"min":0,
"max":12,
337
Profiler
"average":0,
"total":451
},
"db.demo.delete":{
"entries":2,
"last":61,
"min":61,
"max":124,
"average":92,
"total":185
},
"db.demo.deleteRecord":{
"entries":12362,
"last":0,
"min":0,
"max":24,
"average":0,
"total":4626
},
"db.demo.metadata.load":{
"entries":1423,
"last":0,
"min":0,
"max":1,
"average":0,
"total":49
},
"db.demo.open":{
"entries":1423,
"last":0,
"min":0,
"max":1,
"average":0,
"total":6
},
"db.demo.readRecord":{
"entries":476697,
"last":0,
"min":0,
"max":16,
"average":0,
"total":3071
},
"db.demo.synch":{
"entries":484,
"last":2,
"min":0,
"max":34,
"average":2,
"total":1251
},
"db.demo.updateRecord":{
"entries":180667,
"last":0,
"min":0,
"max":12,
"average":0,
"total":2343
},
"db.subTest.close":{
"entries":10,
"last":0,
"min":0,
"max":16,
"average":3,
"total":31
},
"db.subTest.create":{
"entries":2,
"last":44,
"min":18,
"max":44,
"average":31,
"total":62
},
"db.subTest.createRecord":{
338
Profiler
"entries":20,
"last":1,
"min":0,
"max":1,
"average":0,
"total":11
},
"db.subTest.data.createHole":{
"entries":28,
"last":2,
"min":0,
"max":2,
"average":0,
"total":12
},
"db.subTest.data.findClosestHole":{
"entries":22,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.subTest.data.move":{
"entries":12,
"last":0,
"min":0,
"max":1,
"average":0,
"total":4
},
"db.subTest.data.recycled.notFound":{
"entries":14,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.subTest.data.recycled.partial":{
"entries":22,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"db.subTest.data.updateHole":{
"entries":42,
"last":0,
"min":0,
"max":1,
"average":0,
"total":2
},
"db.subTest.delete":{
"entries":2,
"last":118,
"min":76,
"max":118,
"average":97,
"total":194
},
"db.subTest.metadata.load":{
"entries":6,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.subTest.open":{
"entries":6,
"last":0,
"min":0,
"max":0,
339
Profiler
"average":0,
"total":0
},
"db.subTest.readRecord":{
"entries":30,
"last":0,
"min":0,
"max":1,
"average":0,
"total":3
},
"db.subTest.updateRecord":{
"entries":36,
"last":2,
"min":0,
"max":2,
"average":0,
"total":16
},
"db.temp.createRecord":{
"entries":10,
"last":0,
"min":0,
"max":1,
"average":0,
"total":2
},
"db.temp.readRecord":{
"entries":7,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"db.temp.updateRecord":{
"entries":21,
"last":0,
"min":0,
"max":1,
"average":0,
"total":2
},
"process.file.mmap.commitPages":{
"entries":2034,
"last":1,
"min":0,
"max":21,
"average":0,
"total":1048
},
"process.mvrbtree.clear":{
"entries":16007,
"last":0,
"min":0,
"max":1,
"average":0,
"total":141
},
"process.mvrbtree.commitChanges":{
"entries":165235,
"last":0,
"min":0,
"max":55,
"average":0,
"total":5730
},
"process.mvrbtree.entry.fromStream":{
"entries":5408,
"last":0,
"min":0,
"max":1,
"average":0,
"total":45
},
"process.mvrbtree.entry.toStream":{
340
Profiler
"entries":60839,
"last":0,
"min":0,
"max":26,
"average":0,
"total":3013
},
"process.mvrbtree.fromStream":{
"entries":7424,
"last":0,
"min":0,
"max":1,
"average":0,
"total":54
},
"process.mvrbtree.get":{
"entries":97863,
"last":0,
"min":0,
"max":1,
"average":0,
"total":233
},
"process.mvrbtree.put":{
"entries":151070,
"last":0,
"min":0,
"max":55,
"average":0,
"total":5002
},
"process.mvrbtree.putAll":{
"entries":1847,
"last":0,
"min":0,
"max":8,
"average":0,
"total":84
},
"process.mvrbtree.remove":{
"entries":41000,
"last":0,
"min":0,
"max":10,
"average":0,
"total":2226
},
"process.mvrbtree.toStream":{
"entries":124870,
"last":0,
"min":0,
"max":6,
"average":0,
"total":543
},
"process.mvrbtree.unload":{
"entries":7424,
"last":0,
"min":0,
"max":10,
"average":0,
"total":519
},
"process.serializer.record.string.binary2string":{
"entries":1867,
"last":0,
"min":0,
"max":1,
"average":0,
"total":18
},
"process.serializer.record.string.bool2string":{
"entries":43,
"last":0,
"min":0,
"max":0,
341
Profiler
"average":0,
"total":0
},
"process.serializer.record.string.byte2string":{
"entries":1143,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"process.serializer.record.string.date2string":{
"entries":114176,
"last":0,
"min":0,
"max":6,
"average":0,
"total":464
},
"process.serializer.record.string.datetime2string":{
"entries":2,
"last":0,
"min":0,
"max":0,
"average":0,
"total":0
},
"process.serializer.record.string.decimal2string":{
"entries":2,
"last":1,
"min":0,
"max":1,
"average":0,
"total":1
},
"process.serializer.record.string.double2string":{
"entries":30237,
"last":0,
"min":0,
"max":1,
"average":0,
"total":104
},
"process.serializer.record.string.embed2string":{
"entries":122581,
"last":0,
"min":0,
"max":1,
"average":0,
"total":117
},
"process.serializer.record.string.embedList2string":{
"entries":29922,
"last":0,
"min":0,
"max":2,
"average":0,
"total":87
},
"process.serializer.record.string.embedMap2string":{
"entries":3160,
"last":0,
"min":0,
"max":1,
"average":0,
"total":25
},
"process.serializer.record.string.embedSet2string":{
"entries":32280,
"last":1,
"min":0,
"max":8,
"average":0,
"total":1430
},
"process.serializer.record.string.float2string":{
342
Profiler
"entries":20640,
"last":0,
"min":0,
"max":1,
"average":0,
"total":63
},
"process.serializer.record.string.fromStream":{
"entries":1735665,
"last":0,
"min":0,
"max":82,
"average":0,
"total":7174
},
"process.serializer.record.string.int2string":{
"entries":246700,
"last":0,
"min":0,
"max":1,
"average":0,
"total":101
},
"process.serializer.record.string.link2string":{
"entries":18664,
"last":0,
"min":0,
"max":6,
"average":0,
"total":62
},
"process.serializer.record.string.linkList2string":{
"entries":2648,
"last":0,
"min":0,
"max":2,
"average":0,
"total":52
},
"process.serializer.record.string.linkMap2string":{
"entries":28,
"last":0,
"min":0,
"max":1,
"average":0,
"total":1
},
"process.serializer.record.string.linkSet2string":{
"entries":1269,
"last":0,
"min":0,
"max":33,
"average":0,
"total":80
},
"process.serializer.record.string.long2string":{
"entries":1620,
"last":0,
"min":0,
"max":1,
"average":0,
"total":6
},
"process.serializer.record.string.string2string":{
"entries":358585,
"last":0,
"min":0,
"max":3,
"average":0,
"total":183
},
"process.serializer.record.string.toStream":{
"entries":183912,
"last":0,
"min":0,
"max":34,
343
Profiler
"average":0,
"total":3149
},
"server.http.0:0:0:0:0:0:0:1.request":{
"entries":2,
"last":2,
"min":2,
"max":19,
"average":10,
"total":21
}
},
"statistics":{},
"counters":{
"db.0$db.cache.level2.cache.found":7,
"db.0$db.cache.level2.cache.notFound":8,
"db.0$db.data.update.notReused":11,
"db.0$db.data.update.reusedAll":7,
"db.1$db.cache.level2.cache.found":7,
"db.1$db.cache.level2.cache.notFound":8,
"db.1$db.data.update.notReused":11,
"db.1$db.data.update.reusedAll":7,
"db.2$db.cache.level2.cache.found":7,
"db.2$db.cache.level2.cache.notFound":8,
"db.2$db.data.update.notReused":11,
"db.2$db.data.update.reusedAll":7,
"db.demo.cache.level2.cache.found":364467,
"db.demo.cache.level2.cache.notFound":393509,
"db.demo.data.update.notReused":38426,
"db.demo.data.update.reusedAll":140921,
"db.demo.data.update.reusedPartial":100,
"db.demo.query.compositeIndexUsed":46,
"db.demo.query.compositeIndexUsed.2":42,
"db.demo.query.compositeIndexUsed.2.1":20,
"db.demo.query.compositeIndexUsed.2.2":18,
"db.demo.query.compositeIndexUsed.3":4,
"db.demo.query.compositeIndexUsed.3.1":1,
"db.demo.query.compositeIndexUsed.3.2":1,
"db.demo.query.compositeIndexUsed.3.3":2,
"db.demo.query.indexUsed":2784,
"db.subTest.cache.level2.cache.found":14,
"db.subTest.cache.level2.cache.notFound":16,
"db.subTest.data.update.notReused":22,
"db.subTest.data.update.reusedAll":14,
"db.temp.cache.level2.cache.found":5,
"db.temp.cache.level2.cache.notFound":4,
"process.file.mmap.pagesCommitted":2034,
"process.mvrbtree.entry.serializeKey":4617509,
"process.mvrbtree.entry.serializeValue":68620,
"process.mvrbtree.entry.unserializeKey":6127,
"process.mvrbtree.entry.unserializeValue":225,
"process.serializer.record.string.linkList2string.cached":19,
"server.http.0:0:0:0:0:0:0:1.requests":3,
"server.http.0:0:0:0:0:0:0:1.timeout":1
}
}
}
344
Distributedtuning
DistributedConfigurationTuning
Whenyourundistributedonmultipleservers,youcouldfaceonadropofperformanceyougotwithsinglenode.Whileit'snormalthat
replicationhasacost,therearemanywaystoimproveperformanceondistributedconfiguration:
Usetransactions
ReplicationvsSharding
Scaleuponwrites
Scaleuponreads
ReplicationvsSharding
Genericadvice
LoadBalancing
Activeloadbalancingtodistributetheloadacrossmultiplenodes.
Usetransactions
Eventhoughwhenyouupdategraphsyoushouldalwaysworkintransactions,OrientDBallowsalsotoworkoutsideofthem.
Commoncasesareread-onlyqueriesormassiveandnonconcurrentoperationscanberestoredincaseoffailure.Whenyourunon
distributedconfiguration,usingtransactionshelpstoreducelatency.Thisisbecausethedistributedoperationhappensonlyatcommit
time.Distributingonebigoperationismuchefficientthantransferingsmallmultipleoperations,becausethelatency.
ReplicationvsSharding
OrientDBdistributedconfigurationissettofullreplication.Havingmultiplenodeswiththeverysamecopyofdatabaseisimportant
forHAandscalereads.Infacts,eachserverisindependentonexecutingreadsandqueries.Ifyouhave10servernodes,theread
throughputis10x.
Withwritesit'stheopposite:havingmultiplenodeswithfullreplicationslowsdownoperationsifthereplicationissynchronous.In
thiscaseShardingthedatabaseacrossmultiplenodesallowsyoutoscaleupwrites,becauseonlyasubsetofnodesareinvolvedon
write.FurthermoreyoucouldhaveadatabasebiggerthanoneservernodeHD.
Scaleuponwrites
Ifyouhaveaslownetworkandyouhaveasynchronous(default)replication,youcouldpaythecostoflatency.Infactswhen
OrientDBrunssynchronously,itwaitsatleastforthe writeQuorum.Thismeansthatifthe writeQuorumis3,andyouhave5nodes,
thecoordinatorservernode(wherethedistributedoperationisstarted)hastowaitfortheanswerfromatleast3nodesinorderto
providetheanswertotheclient.
Inordertomaintaintheconsistency,the writeQuorumshouldbesettothemajority.Ifyouhave5nodesthemajorityis3.With4
nodesisstill3.Settingthe writeQuorumto3insteadof4or5allowstoreducethelatencycostandstillmaintaintheconsistency.
Asynchronousreplication
Tospeedupthings,youcansetupAsynchronousReplicationtoremovethelatencybottleneck.Inthiscasethecoordinatorservernode
executetheoperationlocallyandgivestheanswertotheclient.Theentirereplicationwillbeinbackground.Incasethequorumisnot
reached,thechangeswillberollbackedtransparently.
Scaleuponreads
Ifyoualreadysetthe writeQuorumtothemajoritytothenodes,youcanleavethe readQuorumto1(thedefault).Thisspeedsupall
thereads.
345
Distributedtuning
346
Security
Security
OrientDBistheNoSQLimplementationwiththegreatestfocusonsecurity.
Toconnecttoanexistingdatabase,youneedauserandpassword.Usersandrolesaredefinedinsidethedatabase.Formore
informationonthisprocess,seeDatabaseSecurity.
Intheeventthatyou'reconnectingtotheOrientDBServerthatishostingthedatabase,youcanaccessthedatabaseusingthe
server'suser.Formoreinformationonthisprocess,seeSeverSecurity.
Additionally,youcanencryptthedatabasecontentsondisk.Formoreinformationonthisprocess,seeDatabaseEncryption.
WhileOrientDBServercanfunctionasaregularWebServer,itisnotrecommendedthatyouexposeitdirectlyto
eithertheInternetorpublicnetworks.Instead,alwayshideOrientDBserverinprivatenetworks.
Seealso:
Databasesecurity
Serversecurity
DatabaseEncryption
SecureSSLconnections
OrientDBWebServer
347
Databasesecurity
DatabaseSecurity
OrientDBusesasecuritymodelbasedonwell-knownconceptsofusersandroles.Thatis,adatabasehasitsownusers.EachUserhas
oneormoreroles.Rolesareacombinationoftheworkingmodeandasetofpermissions.
Formoreinformationonsecurity,see:
Serversecurity
DatabaseEncryption
SecureSSLconnections
RecordLevelSecurity
Users
Auserisanactoronthedatabase.Whenyouopenadatabase,youneedtospecifytheusernameandthepasswordtouse.Eachuser
hasitsowncredentialsandpermissions.
Byconvention,eachtimeyoucreateanewdatabaseOrientDBcreatesthreedefaultusers.Thepasswordsfortheseusersarethesame
astheusernames.Thatis,bydefaultthe adminuserhasapasswordof admin.
adminThisuserhasaccesstoallfunctionsonthedatabasewithoutlimitation.
readerThisuserisaread-onlyuser.The readercanqueryanyrecordsinthedatabase,butcan'tmodifyordeletethem.Ithas
noaccesstointernalinformation,suchastheusersandrolesthemselves.
writerThisuseristhesameastheuser reader,butitcanalsocreate,updateanddeleterecords.
Theusersthemselvesarerecordsstoredinsidethecluster ouser.OrientDBstorespasswordsinhash.Fromversion2.2on,OrientDB
usesthePBKDF2algorithm.PriorreleasesreliedonSHA-256.Formoreinformationonpasswords,seePasswordM anagement.
OrientDBstorestheuserstatusinthefield status.Itcaneitherbe SUSPENDEDor ACTIVE.Only ACTIVEuserscanlogin.
348
Databasesecurity
WorkingwithUsers
Whenyouareconnectedtoadatabase,youcanquerythecurrentusersonthedatabasebyusing SELECTqueriesonthe OUserclass.
orientdb>SELECTRID,name,statusFROMOUser
---+--------+--------+-------#|@CLASS|name|status
---+--------+--------+-------0|null|admin|ACTIVE
1|null|reader|ACTIVE
2|null|writer|ACTIVE
---+--------+--------+-------3item(s)found.Queryexecutedin0.005sec(s).
CreatingaNewUser
Tocreateanewuser,usethe INSERTcommand.Rememberindoingso,thatyoumustsetthestatusto ACTIVEandgiveitavalidrole.
orientdb>INSERTINTOOUserSETname='jay',password='JaY',status='ACTIVE',
roles=(SELECTFROMORoleWHEREname='reader')
UpdatingUsers
Youcanchangethenamefortheuserwiththe UPDATEstatement:
orientdb>UPDATEOUserSETname='jay'WHEREname='reader'
Inthesameway,youcanalsochangethepasswordfortheuser:
orientdb>UPDATEOUserSETpassword='hello'WHEREname='reader'
OrientDBsavesthepasswordinahashformat.Thetrigger OUserTriggerencryptsthepasswordtransparentlybeforeitsavesthe
record.
DisablingUsers
Todisableauser,use UPDATEtoswitchitsstatusfrom ACTIVEto SUSPENDED.Forinstance,ifyouwantedtodisableallusersexcept
for admin:
orientdb>UPDATEOUserSETstatus='SUSPENDED'WHEREname<>'admin'
NOTE:Intheeventthat,duetoaccidentordatabasecorruption,youlosetheuser adminandneedtorestoreitonthedatabase,
seeRestoringtheadminUser`.
Roles
Aroledetermineswhatoperationsausercanperformagainstaresource.M ainly,thisdecisiondependsontheworkingmodeandthe
rules.Therulesthemselvesworkdifferently,dependingontheworkingmode.
WorkingwithRoles
Whenyouareconnectedtoadatabase,youcanquerythecurrentrolesonthedatabaseusing SELECTqueriesonthe ORoleclass.
349
Databasesecurity
orientdb>SELECTRID,mode,name,rulesFROMORole
--+------+----+--------+---------------------------------------------------------#|@CLASS|mode|name|rules
--+------+----+--------+---------------------------------------------------------0|null|1|admin|{database.bypassRestricted=15}
1|null|0|reader|{database.cluster.internal=2,database.cluster.orole=0...
2|null|0|writer|{database.cluster.internal=2,database.cluster.orole=0...
--+------+----+--------+---------------------------------------------------------3item(s)found.Queryexecutedin0.002sec(s).
CreatingNewRoles
Tocreateanewrole,usethe INSERTstatement.
orientdb>INSERTINTOORoleSETname='developer',mode=0
RoleInheritance
Rolescaninheritpermissionsfromotherrolesinanobject-orientedfashion.Toletaroleextendanother,addtheparentroleinthe
inheritedRoleattribute.Forinstance,sayyouwantuserswiththerole appusertoinheritsettingsfromtherole writer.
orientdb>UPDATEORoleSETinheritedRole=(SELECTFROMORoleWHEREname='writer')
WHEREname='appuser'
WorkingwithModes
Whererulesdeterminewhatusersbelongingtocertainrolescandoonthedatabases,workingmodesdeterminehowOrientDBinterprets
theserules.Therearetwotypesofworkingmodes,designatingby 1and 0.
AllowAllBut(Rules)Bydefaultisthesuperusermode.Specifyexceptionstothisusingtherules.IfOrientDBfindsnorulesfor
arequestedresource,thenitallowstheusertoexecutetheoperation.Usethismodemainlyforpowerusersandadministrators.
Thedefaultrole adminusesthismodebydefaultandhasnoexceptionrules.Itiswrittenas 1inthedatabase.
DenyAllBut(Rules)Bydefaultthismodeallowsnothing.Specifyexceptionstothisusingtherules.IfOrientDBfindsrulesfor
arequestedresource,thenitallowstheusertoexecutetheoperation.Usethismodeasthedefaultforallclassicusers.Thedefault
roles readerand writerusethismode.Itiswrittenas 0inthedatabase.
Operations
ThesupportedoperationsaretheclassicCRUDoperations.Thatis,Create,Read,Update,Delete.Rolescanhavenoneofthese
permissionsorallofthem.OrientDBrepresentseachpermissioninternallybya4-digitbitmaskflask.
NONE:#0000-0
CREATE:#0001-1
READ:#0010-2
UPDATE:#0100-4
DELETE:#1000-8
ALL:#1111-15
Inadditiontothesebasepermissions,youcanalsocombinethemtocreatenewpermissions.Forinstance,sayyouwanttoallowonly
theReadandUpdatepermissions:
READ:#0010-1
UPDATE:#0100-4
Permissiontouse:#0110-5
350
Databasesecurity
Resources
ResourcesarestringsboundtoOrientDBconcepts.
NOTE:Resourceentriesarecase-sensitive.
database,checkedonaccessingtothedatabase
database.class.<class-name>,checkedonaccessingonspecificclass
database.cluster.<cluster-name>,checkedonaccessingonspecificcluster
database.query,checkedonqueryexecution
database.command,checkedoncommandexecution
database.schema,checkedtoaccesstotheschema
database.function,checkedonfunctionexecution
database.config,checkedonaccessingatdatabaseconfiguration
database.hook.record
server.admin,checkedonaccessingtoremoteserveradministration
Forinstance,sayyouhavearole motorcyclistthatyouwanttohaveaccesstoallclassesexceptfortheclass Car.
orientdb>UPDATEORolePUTrules="database.class.*",15WHEREname="motorcyclist"
orientdb>UPDATEORolePUTrules="database.class.Car",0WHEREname="motorcyclist"
GrantingandRevokingPermissions
Tograntandrevokepermissionsfromarole,usetheGRANTandREVOKEcommands.
orientdb>GRANTUPDATEONdatabase.cluster.CarTOmotorcyclist
Record-levelSecurity
Thesectionsabovemanagesecurityinaverticalfashionattheschema-level,butinOrientDByoucanalsomanagesecurityina
horizontalfashion,thatis:perrecord.Thisallowsyoutocompletelyseparatedatabaserecordsassandboxes,whereonlyauthorized
userscanaccessrestrictedrecords.
Toactiverecord-levelsecurity,createclassesthatextendthe ORestrictedsuperclass.IntheeventthatyouareworkingwithaGraph
Database,setthe Vand Eclasses(thatis,thevertexandedgeclasses)themselvestoextend ORestricted.
orientdb>ALTERCLASSVSUPERCLASSORestricted
orientdb>ALTERCLASSESUPERCLASSORestricted
Thiscausesallverticesandedgestoinherittherecord-levelsecurity.Beginningwithversion2.1,OrientDBallowsyoutousemultiple
inheritances,tocauseonlycertainvertexoredgecalssestoberestricted.
orientdb>CREATECLASSOrderEXTENDSV,ORestricted
Wheneveraclassextendstheclass ORestricted,OrientDBusesspecialfieldstotype-set _<OIdentifiable>tostoreauthorizationon
eachrecord.
_allowContainstheusersthathavefullaccesstotherecord,(thatis,allCRUDoperations).
_allowReadContainstheusersthatcanreadtherecord.
_allowUpdateContainstheusersthatcanupdatetherecord.
_allowDeleteContainstheusersthatcandeletetherecord.
Toallowfullcontroloverarecordtoauser,addtheuser'sRIDtothe _allowset.Toprovideonlyreadpermissions,use _allowRead.
Intheexamplebelow,youallowtheuserwiththeRID #5:10toreadrecord #43:22:
351
Databasesecurity
orientdb>UPDATE#43:22ADD_allowRead#5:10
Ifyouwanttoremovereadpermissions,usethefollowingcommand:
orientdb>UPDATE#43:22REMOVE_allowRead#5:10
Run-timeChecks
OrientDBchecksrecord-levelsecurityusingahookthatinjectsthecheckbeforeeachCRUDoperation:
CreateDocuments:Setsthecurrentdatabase'suserinthe _allowfield.Tochangethisbehavior,seeCustomizeonCreation.
ReadDocuments:Checksifthecurrentuser,oritsroles,arelistedinthe _allowor _allowReadfields.Ifnot,OrientDBskips
therecord.Thisallowseachquerytoworkperuser.
UpdateDocuments:Checksifthecurrentuser,oritsroles,arelistedinthe _allowor _allowUpdatefield.Ifnot,OrientDB
raisesan OSecurityExceptionexception.
DeleteDocuments:Checksifthecurrentuser,oritsroles,arelistedinthe _allowor _allowDeletefield.Ifnot,OrientDB
raisesan OSecurityExceptionexception.
Theallowfields,(thatis, _allow, _allowRead, _allowUpdate,and _allowDelete)cancontaininstancesof OUserand ORole
records,asbothclassesextend OIdentity.Usetheclass OUsertoallowsingleusersandusetheclass ORoletoallowallusersthat
areapartofthatrole.
UsingtheAPI
Inadditiontomanagingrecord-levelsecurityfeaturesthroughtheOrientDBconsole,youcanalsoconfigureitthroughtheGraphand
DocumentAPI's.
GraphAPI
OrientVertexv=graph.addVertex("class:Invoice");
v.setProperty("amount",1234567);
graph.getRawGraph().getMetadata().getSecurity().allowUser(
v.getRecord(),ORestrictedOperation.ALLOW_READ,"report");
v.save();
DocumentAPI
ODocumentinvoice=newODocument("Invoice").field("amount",1234567);
database.getMetadata().getSecurity().allowUser(
invoice,ORestrictedOperation.ALLOW_READ,"report");
invoice.save();
CustomizeonCreation
Bydefault,wheneveryoucreatearestrictedrecord,(thatis,createaclassthatextendstheclass ORestricted),OrientDBinsertsthe
currentuserintothe _allowfield.Youcanchangethisusingcustompropertiesintheclassschema:
onCreate.fieldsSpecifiesthenamesofthefieldsitsets.Bydefault,theseare _allow,butyoucanalsospecify _allowRead,
_allowUpdate, _allowDeleteoracombinationofthemasanalternative.Usecommastoseparatemultiplefields.
onCreate.identityTypeSpecifieswhethertoinserttheuser'sobjectoritsrole(thefirstone).Bydefault,itissetto user,but
youcanalsosetittouseits role.
Forinstance,sayyouwantedtopreventauserfromdeletingnewposts:
orientdb>ALTERCLASSPostCUSTOMonCreate.fields=_allowRead,_allowUpdate
Consideranotherexample,whereyouwanttoassignaroleinsteadofausertonewinstancesof Post.
352
Databasesecurity
orientdb>ALTERCLASSPostCUSTOMonCreate.identityType=role
BypassingSecurityConstraints
Onoccasion,youmayneedarolethatcanbypassrestrictions,suchasforbackuporadministrativeoperations.Youcanmanagethis
throughthespecialpermission database.bypassRestricted,bychangingitsvalueto READ.Bydefault,therole adminhasthis
permission.
Forsecurityreasons,thispermissionisnotinheritable.Intheeventthatyouneedtoassignittootherrolesinyourdatabase,youneed
tosetitoneachrole.
UsingSecurity
NowthatyouhavesomefamiliaritywithhowsecurityworksinOrientDB,considertheusecaseofOrientDBservingasthedatabase
forablog-likeapplication.Theblogisaccessiblethroughthewebandyouneedtoimplementvarioussecurityfeaturestoensurethatit
worksproperlyanddoesnotgrantitsusersaccesstorestrictedcontent.
Tobegin,theadministratorconnectstothedatabaseandcreatesthedocumentclass Post,whichextends ORestricted.Thisensures
thatuserscanonlyseetheirownentriesintheblogandentriesthataresharedwiththem.
orientdb>CONNECTREMOTE:localhost/blogadminadmin
orientdb>CREATECLASSPostEXTENDSORestricted
Class'Post'createdsuccessfully.
TheuserLukeisregisteredin OUseras luke,withan RIDof #5:5.Helogsintothedatabaseandcreatesanewblog,whichisan
instanceoftheclass Post.
orientdb>CONNECTREMOTE:localhost/bloglukelukepassword
orientdb>INSERTINTOPostSETtitle="YesterdayinItaly"
Createddocument#18:0
orientdb>SELECTFROMPost
-------+--------+-------------------RID|_allow|title
-------+--------+-------------------#18:0|[#5:5]|YesterdayinItaly
-------+--------+--------------------
Independentoftheusers adminand luke,thereistheuserSteve.Steveisregisterswith OUseras steve,hehasanRIDof #5:6.
StevelogsintoOrientDBandalsocreatesanewentryontheclass Post:
353
Databasesecurity
orientdb>CONNECTREMOTE:localhost/blogstevesteve
orientdb>INSERTINTOPostSETtitle="MyNutellaCake!"
Createddocument#18:1
orientdb>SELECTFROMPost
-------+--------+-----------------RID|_allow|title
-------+--------+-----------------#18:1|[#5:6]|MyNutellaCake!
-------+--------+------------------
Asyoucansee,theusersSteveandLukecanonlyseetherecordsthattheyhaveaccessto.Now,aftersomeeditorialwork,Lukeis
satisfiedwiththestateofhisblogentry YesterdayinItaly.Heisnowreadytoshareitwithothers.Fromthedatabaseconsole,he
candosobyaddingtheuserSteve'sRIDtothe _allowfield.
orientdb>UPDATE#18:0ADD_allow=#5:6
Now,whenStevelogsin,thesamequeryfrombeforegiveshimdifferentresults,sincehecannowseethecontentLukesharedwithhim.
orientdb>SELECTFROMPost
-------+--------+--------------------RID|_allow|title
-------+--------+--------------------#18:0|[#5:5]|YesterdayinItaly
#18:1|[#5:6]|MyNutellaCake!
-------+--------+---------------------
Whilethisisaneffectivesolution,itdoeshaveoneminorflawforLuke.ByaddingStevetothe _allowlist,Stevecannotonlyread
postsLukemakes,buthecanalsomodifythem.WhileLukemayfindSteveareasonableperson,hebeginstohavesecondthoughts
aboutthisblanketpermissionanddecidestoremoveStevefromthe _allowfieldandinsteadaddhimtothe _allowReadfield:
orientdb>UPDATE#18:0REMOVE_allow=5:6
orientdb>UPDATE#18:0ADD_allowRead=#5:6
Forthesakeofargument,assumethatLuke'smisgivingsaboutStevehavesomefoundation.StevedecidesthathedoesnotlikeLuke's
entry YesterdayinItalyandwouldliketoremoveitfromthedatabase.HelogsintoOrientDB,runs SELECTtofinditsRID,and
attemptsto DELETEtherecord:
orientdb>SELECTFROMPost
-------+--------+--------------------RID|_allow|title
-------+--------+--------------------#18:0|[#5:5]|YesterdayinItaly
#18:1|[#5:6]|MyNutellaCake!
-------+--------+--------------------orientdb>DELETEFROM#18:0
!Error:Cannotdeleterecord#18:0becausetheaccesstotheresourceisrestricted.
354
Databasesecurity
Asyoucansee,OrientDBblocksthe DELETEoperation,giventhatthecurrentuser,Steve,doesnothavepermissiontodosoonthis
resource.
PasswordManagement
OrientDBstoresuserpasswordsinthe OUserrecordsusingthePBKDF2HASHalgorithmwitha24-bitlengthSaltperuserfora
configurablenumberofiterations.Bydefault,thisnumberis65,536iterations.Youcanchangethisaccountthroughthe
security.userPasswordSaltIterationsglobalconfiguration.Notethatwhileahigheriterationcountcanslowdownattacks,italso
slowsdowntheauthenticationprocessonlegitimateOrientDBuse.
Inordertospeeduppasswordhashing,OrientDBusesapasswordcache,whichitimplementsasanLRUwithamaximumoffive
hundredentries.Youcanchangethissettingthroughthe security.userPasswordSaltCacheSizeglobalconfiguration.Givingthisglobal
configurationthevalueof 0disablesthecache.
NOTE:IntheeventthatattackersgainaccesstotheJavavirtualmachinememorydump,hecouldaccessthismap,whichwould
givethemaccesstoallpasswords.Youcanprotectyourdatabasefromthisattackbydisablingtheinmemorypasswordcache.
355
Serversecurity
ServerSecurity
IndividualOrientDBserverscanmanagemultipledatabasesatatimeandeachdatabasecanhaveitsownsetofusers.Whenusing
OrientDBthroughtheHTTPprotocol,theOrientDBserverusesonerealmperdatabase.
WhileOrientDBcanfunctionasaregularWebServer,itisnotrecommendedthatyouexposeitdirectlytothe
internetortopublicnetworks.Instead,alwayshidetheOrientDBserverwithinaprivatenetwork.
Serverusersarestoredinthe config/orientdb-server-config.xmlconfigurationfile,inthe <users>element.
<users>
<username="root"password="{SHA-256}55F95B91628EF3E679628ACB23AE"resources="*"/>
<username="guest"password="guest"resources="connect,server.listDatabases,server.dblist"/>
</users>
WhentheOrientDBserverstartsforthefirsttime,itcreatestheuser rootautomatically,byaskingyoutogivethepasswordinthe
terminal.Intheeventthatyoudonotspecifyapassword,OrientDBgeneratesarandompassword.Beginningwithversion2.2,
OrientDBhashesthepasswordsusingSHA-256algorithm.
FormoreinformationonsecurityinOrientdb,see:
Databasesecurity
DatabaseEncryption
SecureSSLconnections
Configuration
Whilethedefaultusersandpasswordsarefinewhileyouaresettingyoursystemup,itwouldbeinadvisabletoleavethemin
production.TohelprestrictuntrustedusersfromaccessingtheOrientDBserver,addanewuserandchangethepasswordsinthe
config/orientdb-server-config.xmlserverconfigurationfile.
TorestrictunauthorizedusersfromgivingthemselvesprivilegesontheOrientDBserver,disablewrite-accesstotheconfigurationfile.
Tohelppreventthemfromviewingpasswords,disableread-accessaswell.Notethatevenifthepasswordsarehashed,therearemany
techniquesavailabletocrackthehashorotherwiseguesstherealpassword.
Itisstronglyrecommendedthatyouallowread/writeaccesstotheentire configdirectoryonlytothe
userthatstartstheOrientDBserver.
ManagingUsers
Beginningwithversion2.2,theOrientDBconsoleprovidesaseriesofcommandsformanagingusers:
LISTSERVERUSERS:Displaysallusers.
SETSERVERUSER:Createsormodifiesauser.
DROPSERVERUSER:Dropsauser.
ServerResources
356
Serversecurity
Eachusercandeclarewhichresourceshaveaccess.Thewildcard *grantsaccesstoanyresource.Bydefault,theuser roothasall
privileges,soitcanaccessallthemanageddatabases.
Resources
Description
server.info
Retrievesserverinformationandstatistics.
server.listDatabases
Listsavailabledatabasesontheserver.
database.create
Createsanewdatabaseintheserver
database.drop
Dropsadatabase
database.passthrough
Allowsaccesstoallmanageddatabases.
Forexample,
<username="replicator"password="repl"resources="database.passthrough"/>
SecuringConnectionswithSSL
Beginningwithversion1.7,youcanfurtherimprovesecurityonyourOrientDBserverbysecuringconnectionswithSSL.Formore
informationonimplementingthis,seeUsingSSL.
RestoringtheUseradmin
Intheeventthatsomethinghappensandyoudroptheclass OUserortheuser admin,youcanusethefollowingproceduretorestore
theusertoyourdatabase.
1. EnsurethatthedatabaseisintheOrientDBserverdatabasedirectory, $ORIENTDB_HOME/database/folder.
2. Launchtheconsoleorstudioandlogintothedatabasewiththeuser root.
$$ORIENTDB_HOME/bin/console.sh
OrientDBconsolev.X.X.X(build0)www.orientdb.com
Type'HELP'todisplayallthecommandssupported.
InstallingextensionsforGREMLINlanguagev.X.X.X
orientdb>CONNECTremote:localhost/my_databaserootrootpassword
3. Checkthattheclass OUserexists:
orientdb>SELECTFROMOUserWHEREname='admin'
Intheeventthatthiscommandfailsbecausetheclass OUserdoesn'texist,createit:
orientdb>CREATECLASSOUserEXTENDSOIdentity
Intheeventthatthiscommandfailsbecausetheclass`OIdentitydoesn'texist,createitfirst:
orinetdb>CREATECLASSOIdentity
Thenrepeattheabovecommand,creatingtheclass OUser
4. Checkthattheclass ORoleexists.
357
Serversecurity
orientdb>SELECTFROMORoleWHEREname='admin'
Intheeventthattheclass ORoledoesn'texist,createit:
orientdb>CREATECLASSORoleEXTENDSOIdentity
5. Intheeventthattheuserorrole admindoesn'texist,runthefollowingcommands:
Intheeventthattherole admindoesn'texist,createit:
orientdb>INSERTINTOORoleSETname='admin',mode=1,
rules={"database.bypassrestricted":15}
Intheeventthattheuser admindoesn'texist,createit:
orientdb>INSERTINTOOUserSETname='admin',
password='my-admin_password',status='ACTIVE',
rules=(SELECTFROMORoleWHEREname='admin')
Theuser adminisnowactiveagainonyourdatabase.
358
Databaseencryption
DatabaseEncryption
Beginningwithversion2.2,OrientDBcanencryptrecordsondisk.Thispreventsunauthorizedusersfromaccessingdatabasecontentor
evenfrombypassingOrientDBsecurity.OrientDBdoesnotsavetheencryptionkeytothedatabase.Youmustprovideitatrun-time.
Intheeventthatyoulosetheencryptionkey,thedatabase,(oratleastthepartsofthedatabaseyouhaveencrypted),youloseaccess
toitscontent.
NOTE:Asof2.2thisfeatureisinbeta.Itwillbefinalwith2.2GA.
Encryptionworksthroughtheencryptioninterface.Itactsatthecluster(collection)level.OrientDBsupportstwoalgorithmsfor
encryption:
aesalgorithm,whichusesAES
desalgorithm,whichusesDES
TheAESalgorithmispreferabletoDES,giventhatit'sstronger.
EncryptioninOrientDBoperatesatthedatabase-level.Youcanhavemultipledatabases,eachwithdifferentencryptioninterfaces,
runningunderthesameserver,(or,JVM ,intheeventthatyourunOrientDBembedded).Thatsaid,youcanuseglobalconfigurationsto
definethesameencryptionrulesforalldatabasesopeninthesameJVM .Forinstance,youcandefinerulesthroughtheJavaAPI:
OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD.setValue("aes");
OGlobalConfiguration.STORAGE_ENCRYPTION_KEY.setValue("T1JJRU5UREJfSVNfQ09PTA==");
YoucanenablethisatstartupbypassingthesesettingsasJVM arguments:
$java...-Dstorage.encryptionMethod=aes\
-Dstorage.encryptionKey="T1JJRU5UREJfSVNfQ09PTA=="
FormoreinformationonsecurityinOrientDB,seethefollowingpages:
Databasesecurity
Serversecurity
SecureSSLconnections
CreatingEncryptedDatabases
YoucancreateanencrypteddatabaseusingeithertheconsoleorthroughtheJavaAPI.Tocreateanencrypteddatabase,usethe encryptionoptionthroughthe CREATEDATABASEcommand.However,beforeyoudoso,youmustsettheencryptionkeybydefining
the storage.encryptionKeyvaluethroughthe CONFIGcommand.
orientdb>CONFIGSETstorage.encryptionKeyT1JJRU5UREJfSVNfQ09PTA==
orientdb>CREATEDATABASEplocal:/tmp/db/encrypted-dbadminmy_admin_password
plocaldocument-encryption=aes
TocreateanencrypteddatabasethroughtheJavaAPI,definetheencryptionalgorithmandthensettheencryptionkeyasdatabase
properties:
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/tmp/db/encrypted");
db.setProperty(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD.getKey(),"aes");
db.setProperty(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY.getKey(),"T1JJRU5UREJfSVNfQ09PTA==");
db.create();
WhetheryouusetheconsoleortheJavaAPI,thesecommandsencrypttheentiredatabaseondisk.OrientDBdoesnotstorethe
encryptionkeywithinthedatabase.Youmustprovideitatrun-time.
359
Databaseencryption
EncryptingClusters
Inadditiontotheentiredatabase,youcanalsoonlyencryptcertainclustersonthedatabase.Todoso,settheencryptiontothedefault
of nothingwhenyoucreatethedatabase,thenconfiguretheencryptionperclusterthroughthe ALTERCLUSTERcommand.
ToencrypttheclusterthroughtheJavaAPI,createthedatabase,thenaltertheclustertouseencryption:
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/tmp/db/encrypted");
db.setProperty(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY.getKey(),"T1JJRU5UREJfSVNfQ09PTA==");
db.create();
db.command(newOCommandSQL("ALTERCLUSTERSalaryencryptionaes")).execute();
Bearinmindthatthekeyremainsthesamefortheentiredatabase.Youcannotusedifferentkeyspercluster.Ifyouattempttoapply
encryptionoranencryptionsettingonaclusterthatisnotempty,itraisesanerror.
Toaccomplishthesamethroughtheconsole,settheencryptionkeythrough storage.encryptionKeythendefinetheencryption
algorithmforthecluster:
orientdb>CONFIGSETstorage.encryptionKeyT1JJRU5UREJfSVNfQ09PTA==
orientdb>ALTERCLUSTERSalaryencryptionaes
OpeningEncryptedDatabases
YoucanaccessanencrypteddatabasethrougheithertheconsoleortheJavaAPI.Todosothroughtheconsole,settheencryptionkey
with storage.encryptionKeythenopenthedatabase.
orientdb>CONFIGSETstorage.encryptionKeyT1JJRU5UREJfSVNfQ09PTA==
orientdb>CONNECTplocal:/tmp/db/encrypted-dbadminmy_admin_password
WhenopeningthroughtheJavaAPI,giventhattheencryptionsettingsarestoredwiththedatabase,youdonotneedtodefinethe
encryptionalgorithmwhenyouopenthedatabase,justtheencryptionkey.
db.setProperty(OGlobalConfiguration.STORAGE_ENCRYPTION_KEY.getKey(),"T1JJRU5UREJfSVNfQ09PTA==");
db.open("admin","my_admin_password");
Intheeventthatyoupassanullorinvalidkeywhenyouopenthedatabase,OrientDBraisesan OSecurityExceptionexception.
360
SecureSSLconnections
SSL
Beginningwithversion1.7,OrientDBprovidessupportforsecuringitsHTTPandBINARYprotocolsthroughSSL.Fordistributed
SSL,seetheHazelCastdocumentation.
FormoreinformationonsecuringOrientDB,seethefollowingpages:
Databasesecurity
Serversecurity
DatabaseEncryption
SettinguptheKeyandTrustStores
Inordertosetupandmanagecertificates,OrientDBusestheJavaKeytool.UsingcertificatessignedbyaCertificateAuthority(CA)is
beyondthescopeofthistutorial.FormoreinformationonusingtheJavaKeytool,seetheDocumentation.
Tocreatekeyandtruststoresthatreferenceaself-signedcertificate,usethefollowingguide:
1. UsingKeytool,createacertificatefortheserver:
#keytool-genkey-aliasserver-keystoreorientdb.ks\
-keyalgRSA-keysize2048-validity3650
2. Exporttheservercertificatetoshareitwithclient:
#keytool-export-aliasserver-keystoreorientdb.ks\
-fileorientdb.cert
3. Createacertificate/keystorefortheconsole/clients:
#keytool-genkey-aliasconsole-keystoreorientdb-console.ks\
-keyalgRSA-keysize2048-validity3650
4. Createatrust-storefortheclient,thenimporttheservercertificate.
#keytool-import-aliasserver-keystoreorientdb-console.ts\
-fileorientdb.cert
Thisestablishesthattheclienttruststheserver.
Younowhaveaself-signedcertificatetousewithOrientDB.BearinmindthatforeachremoteclientJVM youwanttoconnecttothe
server,youneedtorepeatstepsthreeandfour.Remembertochangethealias,keystoreandtrust-storefilenamesaccordingly.
ConfiguringOrientDBforSSL
ServerConfiguration
Theserverconfigurationfile, $ORIENTDB_HOME/config/orientdb-server-config.xml,doesnotuseSSLbydefault.ToenableSSLona
protocollistener,youmustchangethe socketattributetothe <listener>valuefrom defaulttooneofyourconfigured <socket>
definitions.
Therearetwodefaultdefinitionsavailable: ssland https.Formostusecasesthisissufficient,howeveryoucandefinemoreifyou
wanttosecuredifferentlistenerswiththeirowncertificatesorwouldliketouseacustomfactoryimplementations.Whenusingthe
sslimplementation,bearinmindthatthedefaultportforOrientDBSSLis 2434.Youneedtochangeyourportrangeto 2434-
361
SecureSSLconnections
2440.
Bydefault,theOrientDBserverlooksforitskeysandtrust-storesin $ORIENTDB_HOME/config/cert.Youcanconfigureitusingthe
<socket>parameters.Besurethatallthekeyandtrust-storescreatedintheprevioussetupareinthecorrectdirectoryandthatthe
passwordsusedarecorrect.
NOTE:Pathsarerelativeto $ORIENTDB_HOME.OrientDBalsosupportsabsolutepaths.
<sockets>
<socketimplementation="com.orientechnologies.orient.server.network.OServerSSLSocketFactory"name="ssl">
<parameters>
<parametervalue="false"name="network.ssl.clientAuth"/>
<parametervalue="config/cert/orientdb.ks"name="network.ssl.keyStore"/>
<parametervalue="password"name="network.ssl.keyStorePassword"/>
<!--NOTE:Weareusingthesamestoreforkeysandtrust.
Thiswillchangeifclientauthenticationisenabled.SeeConfiguringClientsection-->
<parametervalue="config/cert/orientdb.ks"name="network.ssl.trustStore"/>
<parametervalue="password"name="network.ssl.trustStorePassword"/>
</parameters>
</socket>
...
<listenerprotocol="binary"ip-address="0.0.0.0"port-range="2424-2430"socket="default"/>
<listenerprotocol="binary"ip-address="0.0.0.0"port-range="2434-2440"socket="ssl"/>
ConsoleConfiguration
Forremoteconnectionsusingtheconsole,youneedtomakeafewchangestoto console.sh,enableSSL:
1. Confirmthatyour KEYSTORE, TRUSTSTOREandrespective PASSWORDvariablesarecorrectlyset.
2. Inthe SSL_OPTSdefinition,set client.ssl.enabledsystempropertyto true.
ClientConfiguration
Toconfigureremoteclients,usethestandardJavasystempropertypatterns:
client.ssl.enabled:Usethistoenable/disableSSL.Thepropertyaccepts trueor false.Youonlyneedtodefinethiswhen
usingremotebinaryclientconnections.
javax.net.ssl.keyStore:Definethepathtothekeystore.
javax.net.ssl.keyStorePassword:Definesthepasswordtothekeystore.
javax.net.ssl.trustStore:Definesthepathtothetrust-store.
javax.net.ssl.trustStorePassword:Definesthepasswordtothetrust-store.
UsethethirdandfourthstepsfromSettinguptheKeyandTrustStoressectionabovetocreatetheclientcertificatesandservertrust.
Thepathstothestoresareclientspecific,butdonotneedtobethesameastheserver.
Note,ifyouwouldliketousekeyand/oretrust-storesotherthanthatofthedefaultJVN,youneedtodefinethefollowingvariablesas
well:
client.ssl.keyStore:Definesthepathtothekeystore.
client.ssl.keyStorePass:Definesthekeystorepassword.
client.ssl.trustStore:Definesthepathtothetrust-store.
client.ssl.trustStorePass:Definesthepasswordtothetrust-store.
Considerthefollowingexample,configuringSSLfromthecommand-linethroughJava:
$java-Dclient.ssl.enabled=false\
-Djavax.net.ssl.keyStore=\
-Djavax.net.ssl.keyStorePassword=\
-Djavax.net.ssl.trustStore=\
-Djavax.net.ssl.trustStorePassword=
362
SecureSSLconnections
Asanalternative,youcandefinethesevariablesthroughtheJavaAPI:
System.setProperty("client.ssl.enabled",<"true"|"false">);#Thiswillonlybeneededforremotebinaryclients
System.setProperty("javax.net.ssl.keyStore",</path/to/keystore>);
System.setProperty("javax.net.ssl.keyStorePassword",<keystorepass>);
System.setProperty("javax.net.ssl.trustStore",</path/to/truststore>);
System.setProperty("javax.net.ssl.trustStorePassword",<truststorepass>);
Toverifyorauthenticateclientcertificates,youneedtotakeafewadditionalstepsontheserver:
1. Exporttheclientcertificate,sothatyoucanshareitwiththeserver:
#keytool-export-alias\
-keystore-fileclient_cert
Alternatively,youcandothisthroughtheconsole:
#keytool-export-aliasconsole-keystoreorientdb-console.ks\
-fileorientdb-console.cert
2. Ifyoudonothaveatrust-storefortheserver,createoneandimporttheclientcertificate.Thisestablishesthattheservertruststhe
client:
#keytool-import-alias-keystoreorientdb.ts\
-fileclient_cert
Alternatively,youcanmanagethesamethroughtheconsole:
#keytool-import-aliasconsole-keystoreorientdb.ts\
-fileorientdb-console.cert
Intheserverconfigurationfile,ensurethatyouhaveclientauthenticationenabledforthe <socket>andthatthetrust-storepathand
passwordarecorrect:
<sockets>
<socketimplementation="com.orientechnologies.orient.server.network.OServerSSLSocketFactory"name="ssl">
<parameters>
<parametervalue="true"name="network.ssl.clientAuth"/>
<parametervalue="config/cert/orientdb.ks"name="network.ssl.keyStore"/>
<parametervalue="password"name="network.ssl.keyStorePassword"/>
<!--NOTE:Weareusingthetruststorewiththeimportedclientcert.Youcanimportasmanyclientasyouwouldlike
-->
<parametervalue="config/cert/orientdb.ts"name="network.ssl.trustStore"/>
<parametervalue="password"name="network.ssl.trustStorePassword"/>
</parameters>
</socket>
...
</sockets>
363
ServerM anagement
ManagearemoteServerinstance
Introduction
AremoteservercanbemanagedviaAPIusingtheOServerAdminclass.CreateitusingtheURLoftheremoteserverasfirstparameter
oftheconstructor.
OServerAdminserverAdmin=newOServerAdmin("remote:localhost:2480");
YoucanalsousetheURLoftheremotedatabase:
OServerAdminserverAdmin=newOServerAdmin("remote:localhost:2480/GratefulDeadConcerts");
Connecttoaremoteserver
OServerAdminserverAdmin=newOServerAdmin("remote:localhost:2480").connect("admin","admin");
Userandpasswordarenotthedatabaseaccountsbuttheserverusersconfiguredinorientdb-server-config.xmlfile.
Whenfinishedcallthe OServerAdmin.close()methodtoreleasethenetworkconnection.
Createadatabase
Tocreateanewdatabaseinaremoteserveryoucanusetheconsole'screatedatabasecommandorviaAPIusingthe
OServerAdmin.createDatabase()method.
//ANYVERSION:CREATEASERVERADMINCLIENTAGAINSTAREMOTESERVER
OServerAdminserverAdmin=newOServerAdmin("remote:localhost/GratefulDeadConcerts").connect("admin","admin");
serverAdmin.createDatabase("graph","local");
//VERSION>=1.4:CREATEASERVERADMINCLIENTAGAINSTAREMOTESERVER
OServerAdminserverAdmin=newOServerAdmin("remote:localhost").connect("admin","admin");
serverAdmin.createDatabase("GratefulDeadConcerts","graph","local");
TheiStorageM odecanbememoryorplocal.
Dropadatabase
Todropadatabasefromaserveryoucanusetheconsole'sdropdatabasecommandorviaAPIusingthe OServerAdmin.dropDatabase()
method.
//CREATEASERVERADMINCLIENTAGAINSTAREMOTESERVER
OServerAdminserverAdmin=newOServerAdmin("remote:localhost/GratefulDeadConcerts").connect("admin","admin");
serverAdmin.dropDatabase("GratefulDeadConcerts");
Checkifadatabaseexists
TocheckifadatabaseexistsinaserverviaAPIusethe OServerAdmin.existsDatabase()method.
364
ServerM anagement
//CREATEASERVERADMINCLIENTAGAINSTAREMOTESERVER
OServerAdminserverAdmin=newOServerAdmin("remote:localhost/GratefulDeadConcerts").connect("admin","admin");
serverAdmin.existsDatabase("local");
365
APIsandDrivers
API
OrientDBsupports3kindsofdrivers:
Nativebinaryremote,thattalksdirectlyagainsttheTCP/IPsocketusingthebinaryprotocol
HTTPRES T/JS ON,thattalksdirectlyagainsttheTCP/IPsocketusingtheHTTPprotocol
Javawrapped,asalayerthatlinksinsomewaythenativeJavadriver.ThisisprettyeasyforlanguagesthatrunintotheJVM like
Scala,GroovyandJRuby
LookalsoattheavailableintegrationwithPluginsandFrameworks.
ThisisthelistoftheknowndriverstouseOrientDBthroughdifferentlanguages:
Language
Name
Type
Description
Java(native)API
Native
Nativeimplementation.
JDBCdriver
Native
Forlegacyandreporting/BusinessIntelligenceapplications
andJCAintegrationforJ2EEcontainers
OrientJS
Native
Binaryprotocol,newbranchthathasbeenupdatedwith
thelatestfunctionality.Testedon1.7.0,2.0.xand2.1-rc*.
node-orientdb-http
HTTP
RESTfulHTTPprotocol.Testedon1.6.1
ToexecuteGremlinqueriesagainstaremoteOrientDB
server
Gremlin-Node
PhpOrient
Binary
OfficialDriver
OrientDB-PHP
Binary
ThiswasthefirstPHPdriverforOrientDB,butdoesn't
supportallOrientDBfeaturesandit'sslowtosupport
newversionsofdriverprotocol.
DoctrineODM
Uses
OrientDBPHP
HighlevelframeworktouseOrientDBfromPHP
.NETdriverfor
OrientDB
Binary
OfficialDriver
PyOrient
Binary
CommunitydriverforPython,compatiblewithOrientDB
1.7andfurther.
Bulbflowproject
HTTP
UsesRexterGraphHTTPServertoaccesstoOrientDB
database
ConfigureRexsterforOrientDB
Compass
HTTP
OrientDB-C
Binary
BinaryprotocolcompatibleswithC++andother
languagesthatsupportsCcalls
LibOrient
Binary
AsanotherBinaryprotocoldriver
JavascriptDriver
HTTP
ThisdriveristhesimplerwaytouseOrientDBfromJS
JavascriptGraph
Driver
HTTP
Thisdrivermimicsthe[Blueprints]
(https://github.com/orientechnologies/orientdb/wiki/GraphDatabase-Tinkerpop)interface.Usethisdriverifyou're
workingagainstgraphs.
Active-Orient
HTTP
UseOrientDBtopersistentlystoredynamicRubyObjectsandusedatabasequeriestomanageevenverylarge
366
APIsandDrivers
datasets.
OrientDB-JRuby
Native
OrientDBClient
Binary
OrientDB4R
HTTP
ThroughJavadriver
OrientDBGroovy
Java
wrapper
ThisprojectcontainsGroovyASTTransformations
tryingtomimicgrails-entitystyle.Allusefulinformation
youcanfindinSpocktestsdir.DocumentAPIandGraph
APIwithgremlinaresupported.BuiltwithOrientDB
2.1.0andApacheGroovy2.4.4.
AnyJavadriver
Native
ScalarunsontopofJVM andit'sfullycompatiblewith
JavaapplicationslikeOrientDB
ScalaPage
Native
Offerssuggestionsandexamplestouseitwithoutpains
Scalautilitiesandtests
Native
TohelpScaladevelopersusingOrientDB
Rdriver
HTTP
RBridgetoexecutequeriesagainstOrientDBServer
M arcoPoloElixir
driver
Binary
ThisdriverallowsElixirapplicationtointeractwith
OrientDB.ElixirlanguageleveragestheErlangVM ,known
forrunninglow-latency,distributedandfault-tolerant
systems,whilealsobeingsuccessfullyusedinweb
developmentandtheembeddedsoftwaredomain.
Clojurebinding
Native
ThroughJavadriver
OrientDBAndroid
Porting
OrientDB-Androidisaport/forkofOrientDBforthe
AndroidplatformbyDavidWu
OrientDBPerldriver
Binary
PlOrientisaPerlbinaryinterfaceforOrientDB
Clojurebindingof
BlueprintsAPI
Supportedstandards
ThisisthelistofthelibrarytouseOrientDBbyusingsuchstandard:
TinkerPopBlueprints
TinkerPopBlueprints,thestandardforGraphDatabases.OrientDBis100%compliantwiththelatestversion.
Allthetrademarksarepropertyoftheirlegalowners.
367
Functions
Functions
AFunctionisanexecutableunitofcodethatcantakeparametersandreturnaresult.UsingFunctionsyoucanperformFunctional
programmingwherelogicanddataarealltogetherinacentralplace.FunctionsaresimilartotheStoredProceduresofRDBM S.
NOTE:ThisguidereferstothelastavailablereleaseofOrientDB.ForpastrevisionslookatCompatibility.
OrientDBFunctionsfeatures:
arepersistent
canbewritteninSQLorJavascript(Ruby,Scala,Javaandotherlanguagesarecoming)
canbeexecutedviaSQL,Java,RESTandStudio
cancalleachother
supportsrecursion
haveautomaticmappingofparametersbypositionandname
pluginscaninjectnewobjectstobeingusedbyfunctions
Createyourfirstfunction
TostartusingFunctionsthesimplestwayisusingtheStudio.Openthedatabaseandgotothe"Functions"panel.Thenwriteasname
"sum",add2parametersnamed"a"and"b"andnowwritethefollowingcodeinthetextarea:
returnparseInt(a)+parseInt(b);
Clickonthe"Save"button.Yourfunctionhasbeensavedandwillappearontheleftbetweentheavailablefunctions.
Nowlet'sgototestit.Onthebottomyouwillfind2emptyboxes.Thisiswhereyoucaninserttheparameterswheninvokingthe
function.Write3and5asparametersandclick"Execute"toseetheresult."8.0"willappearintheoutputboxbelow.
WhyusingparseInt()andnotjust a+b?becauseHTTPprotocolpassesparametersasstrings.
368
Functions
Wherearemyfunctionssaved?
Functionsaresavedinthedatabaseusingthe OFunctionclassandthefollowingproperties:
name,asthenameofthefunction
code,asthecodetoexecute
parameters,asanoptional EMBEDDEDLISTofStringcontainingtheparameternamesifany
idempotent,tellsifthefunctionis idempotent,namelyifitchangesthedatabase.Read-onlyfunctionsare idempotent.Thisis
neededtoavoidcallingnon- idempotentfunctionsusingtheHTTPGETmethod
Concurrentediting
SinceOrientDBuses1recordperfunction,theM VCCmechanismisusedtoprotectagainstconcurrentrecordupdates.
Usage
UsageviaJavaAPI
UsingOrientDB'sfunctionsfromJavaisstraightforward.FirstgetthereferencetotheFunctionM anager,gettherightfunctionand
executeitpassingtheparameters(ifany).Inthisexampleparametersarepassedbyposition:
ODatabaseDocumentTxdb=newODatabaseDocumentTx("local:/tmp/db");
db.open("admin","admin");
OFunctionsum=db.getMetadata().getFunctionLibrary().getFunction("sum");
Numberresult=sum.execute(3,5);
Ifyou'reusingtheBlueprintsGraphAPIgetthereferencetotheFunctioninthisway:
OFunctionsum=graph.getRawGraph().getMetadata().getFunctionLibrary().getFunction("sum");
Youcanexecutefunctionspassingparametersbyname:
Map<String,Object>params=newHashMap<String,Object>();
params.put("a",3);
params.put("b",5);
Numberresult=sum.execute(params);
UsageviaHTTPREST
EachfunctionisexposedasaRESTserviceallowingthereceivingofparameters.ParameterscanbepassedbypositionintheURL,or
startingfrom2.1canbepassedintherequestpayloadasJSON.Inthiscasethemappingisnotpositional,butbyname.
Exampletoexecutethe sumfunctioncreatedbeforepassing3and5asparametersintheURL,sopositional:
http://localhost:2480/function/demo/sum/3/5
Since2.1,parameterscanbepassedalsointherequest'spayloadinaJSON,sobyname:
{"a":3,"b":5}
BothcallswillreturnanHTTP202OKwithanenvelopecontainingtheresultofthecalculation:
{"result":[{"@type":"d","@version":0,"value":2}]}
YoucancallwithHTTPGETmethodonlyfunctionsdeclaredas"idempotent".UseHTTPPOSTtocallanyfunctions.
369
Functions
Ifyou'reexecutingthefunctionusingHTTPPOSTmethod,encodethecontentandsettheHTTPrequestheaderto: "Content-Type:
application/json".
Formoreinformation,seeHTTPRESTprotocol.Tolearnhowtowriteserver-sidefunctionforwebapplications,seeServer-Side
functions.
FunctionreturnvaluesinHTTPcalls
WhencallingafunctionasaRESTservice,OrientDBencapsulatestheresultinaJSONandsendsittotheclientviaHTTP.Theresult
canbeslightlydifferentdependingonthereturnvalueofthefunction.Herearesomedetailsaboutdifferentcases:
afunctionthatreturnsanumber:
return31;
result:
{"result":[{"@type":"d","@version":0,"value":31}]}
afunctionthatreturnsaJSobject
return{"a":1,"b":"foo"}
result:
{"result":[{"@type":"d","@version":0,"value":{"a":1,"b":"foo"}}]}
afunctionthatreturnsanarray
return[1,2,3]
result:
{"result":[{"@type":"d","@version":0,"value":[1,2,3]}]}
afunctionthatreturnsaqueryresult
returndb.query("selectfromOUser")
result:
370
Functions
{
"result":[
{
"@type":"d",
"@rid":"#6:0",
"@version":1,
"@class":"OUser",
"name":"admin",
"password":"...",
"status":"ACTIVE",
"roles":[
"#4:0"
],
"@fieldTypes":"roles=n"
},
{
"@type":"d",
"@rid":"#6:1",
"@version":1,
"@class":"OUser",
"name":"reader",
"password":"...",
"status":"ACTIVE",
"roles":[
"#4:1"
],
"@fieldTypes":"roles=n"
}
]
}
AccesstothedatabasesfromFunctions
OrientDBalwaysbindsaspecialvariable orienttouseOrientDBservicesfrominsidethefunctions.Themostimportantmethods
are:
orient.getGraph(),returnsthecurrenttransactionalgraphdatabaseinstance
orient.getGraphNoTx(),returnsthecurrentnon-transactionalgraphdatabaseinstance
orient.getDatabase(),returnsthecurrentdocumentdatabaseinstance
Executeaquery
Queryisanidempotentcommand.Toexecuteaqueryusethe query()method.Example:
returnorient.getDatabase().query("selectnamefromouser");
Executeaquerywithexternalparameters
Createanewfunctionwithname getyUserRoleswiththeparameter user.Thenwritethiscode:
returnorient.getDatabase().query("selectrolesfromouserwherename=?",name);
ThenameparameterisboundasvariableinJavascript.Youcanusethisvariabletobuildyourquery.
Executeacommand
CommandscanbewritteninanylanguagesupportedbyJVM .BydefaultOrientDBsupports"SQL"and"Javascript".
SQLCommand
vargdb=orient.getGraph();
varresults=gdb.command("sql","selectfromEmployeewherecompany=?",["OrientTechnologies"]);
371
Functions
Theresultofcommandisanarrayofobjects,whereobjectscanbe:
OrientVertexinstancesifverticesarereturned
OrientEdgeinstancesifedgesarereturned
OIdentifiable,oranysubclassesofit,instancesifrecordsarereturned
Writeyourownrepositoryclasses
Functionsaretheperfectplacetowritethelogicforyourapplicationtoaccesstothedatabase.YoucouldadoptaDDDapproach
allowingthefunctiontoworkasaRepositoryoraDAO.
Thismechanismprovidesathin(orthickifyouprefer)layerofencapsulationwhichmayprotectyoufromdatabasechanges.
FurthermoreeachfunctionispublishedandreachableviaHTTPRESTprotocolallowingtheautomaticcreationofaRESTfulservice.
Example
Belowanexampleoffunctionstobuildarepositoryfor OUserrecords.
functionuser_getAll(){
returnorient.getDatabase().query("selectfromouser");
}
functionuser_getByName(name){
returnorient.getDatabase().query("selectfromouserwherename=?",name);
}
functionuser_getAdmin(){
returnuser_getByName("admin");
}
functionuser_create(name,role){
vardb=orient.getDatabase();
varrole=db.query("selectfromORolewherename=?",roleName);
if(role==null){
response.send(404,"Rolenamenotfound","text/plain","Error:rolenamenotfound");
}else{
db.begin();
try{
varresult=db.save({"@class":"OUser",name:"Luca",password:"Luc4",status:"ACTIVE",roles:role});
db.commit();
returnresult;
}catch(err){
db.rollback();
response.send(500,"Erroroncreatingnewuser","text/plain",err.toString());
}
}
}
372
Functions
Recursivecalls
Createthenewfunctionwithname"factorial"withtheparameter"n".Thenwritethiscode:
if(num===0)
return1;
else
returnnum*factorial(num-1);
Thisfunctioncallsitselftofindthefactorialnumberfor <num>asparameter.Theresultis 3628800.0.
373
Functions
Server-Sidefunctions
Server-SidefunctionscanbeusedasServletreplacement.ToknowhowtocallaServer-Sidefunction,seeUsageviaHTTPREST.When
server-sidefunctionsarecalledviaHTTPRESTprotocol,OrientDBembedsafewadditionalvariables:
request,astheHTTPrequestandimplementedby OHttpRequestWrapperclass
response,astheHTTPrequestresponseimplementedby OHttpResponseWrapperclass
util,asanutilityclasswithhelperfunctionstouseinsidethefunctions.It'simplementedby OFunctionUtilWrapperclass
Requestobject
Refertothisobjectas"request".Example:
varparams=request.getParameters();
Methodsignature
Description
Returntype
getContent()
Returnstherequest'scontent
String
getUser()
Getstherequest'susername
String
getContentType()
Returnstherequest'scontenttype
String
getHttpVersion()
Returntherequest'sHTTPversion
String
getHttpMethod()
Returntherequest'sHTTPmethodcalled
String
getIfMatch()
Returntherequest'sIF-M ATCHheader
String
isMultipart()
Returnsiftherequestshasmultipart
boolean
getArguments()
Returnstherequest'sargumentspassedinRESTform.Example:/2012/10/26
String[]
getArgument(<position>)
Returnstherequest'sargumentbyposition,ornullifnotfound
String
getParameters()
Returnstherequest'sparameters
String
getParameter(<name>)
Returnstherequest'sparameterbynameornullifnotfound
String
hasParameters(<name>*)
Returnsthenumberofparametersfoundbetweenthosepassed
Integer
getSessionId()
Returnsthesession-id
String
getURL()
Returnstherequest'sURL
String
Responseobject
Refertothisobjectas"response".Example:
vardb=orient.getDatabase();
varroles=db.query("selectfromORolewherename=?",roleName);
if(roles==null||roles.length==0){
response.send(404,"Rolenamenotfound","text/plain","Error:rolenamenotfound");
}else{
db.begin();
try{
varresult=db.save({"@class":"OUser",name:"Luca",password:"Luc4","roles":roles});
db.commit();
returnresult;
}catch(err){
db.rollback();
response.send(500,"Erroroncreatingnewuser","text/plain",err.toString());
}
}
374
Functions
Methodsignature
Description
Return
type
getHeader()
Returnstheresponse'sadditionalheaders
String
setHeader(Stringheader)
Setstheresponse'sadditionalheaderstosendback.To
specifymultipleheadersusethelinebreaks
Request
object
getContentType()
Returnstheresponse'scontenttype.Ifnullwillbe
automaticallydetected
String
setContentType(StringcontentType)
Setstheresponse'scontenttype.Ifnullwillbe
automaticallydetected
Request
object
getCharacterSet()
Returnstheresponse'scharactersetused
String
setCharacterSet(StringcharacterSet)
Setstheresponse'scharacterset
Request
object
String
getHttpVersion()
writeStatus(inthttpCode,Stringreason)
Setstheresponse'sstatusasHTTPcodeandreason
Request
object
writeStatus(inthttpCode,Stringreason)
Setstheresponse'sstatusasHTTPcodeandreason
Request
object
writeHeaders(StringcontentType)
Setstheresponse'sheadersusingthekeep-alive
Request
object
writeHeaders(StringcontentType,boolean
keepAlive)
Setstheresponse'sheadersspecifyingwhenusingthe
keep-aliveornot
Request
object
writeLine(Stringcontent)
Writesalineintheresponse.Alinefeedwillbeappended
attheendofthecontent
Request
object
writeContent(Stringcontent)
Writescontentdirectlytotheresponse
Request
object
writeRecords(List<OIdentifiable>records)
Writesrecordsasresponse.Therecordsareserializedin
JSONformat
Request
object
writeRecords(List<OIdentifiable>records,String
fetchPlan)
Writesrecordsasresponsespecifyingafetch-planto
serializenestedrecords.Therecordsareserializedin
JSONformat
Request
object
writeRecord(ORecordrecord)
Writesarecordasresponse.Therecordisserializedin
JSONformat
Request
object
writeRecord(ORecordrecord,StringfetchPlan)
Writesarecordasresponse.Therecordisserializedin
JSONformat
Request
object
send(intcode,Stringreason,StringcontentType,
Objectcontent)
SendsthecompleteHTTPresponseinonecall
Request
object
send(intcode,Stringreason,StringcontentType,
Objectcontent,Stringheaders)
SendsthecompleteHTTPresponseinonecallspecifying
additionalheaders.Keep-aliveisset
Request
object
send(intcode,Stringreason,StringcontentType,
Objectcontent,Stringheaders,boolean
keepAlive)
SendsthecompleteHTTPresponseinonecallspecifying
additionalheaders
Request
object
sendStream(intcode,Stringreason,String
contentType,InputStreamcontent,longsize)
SendsthecompleteHTTPresponseinonecallspecifying
astreamascontent
Request
object
flush()
FlushesthecontenttotheTCP/IPsocket
Request
object
Utilobject
Refertothisobjectas util.Example:
if(util.exists(year)){
print("\nYes,theyearwaspassed!");
}
375
Functions
Methodsignature
exists(<variable>)
Description
Returnstruesifanyofthepassedvariablesaredefined.InJS,forexample,avariableis
definedifit'snotnullandnotequalsto"undefined"
Return
type
Boolean
Nativefunctions
OrientDB'sSQLdialectsupportsmanyfunctionswritteninnativelanguage.Toobtainbetterperformanceyoucanwriteyouown
nativefunctionsinJavalanguageandregisterthemtotheengine.
Compatibility
1.5.0andbefore
OrientDBbindsthefollowingvariables:
db,thatisthecurrentdocumentdatabaseinstance
gdb,thatisthecurrentgraphdatabaseinstance
376
AvailablePluginsandTools
Plugins
Ifyou'relookingfordriversorJDBCconnectorgotoProgramming-Language-Bindings.
PlayFramework2.1PLAY-WITH-ORIENTDBplugin
PlayFramework2.1ORIGAM Iplugin
PlayFramework1.xORIENTDBplugin
Frames-OrientDBPluginPlayFramework2.xFrames-OrientDBpluginisaJavaO/GmapperfortheOrientDBwiththePlay!
framework2.ItisusedwiththeTinkerPopFramesforO/Gmapping.
Withpropermark-up/logicseparation,aPOJOdatamodel,andarefreshinglackofXM L,ApacheWicketmakesdevelopingweb-apps
simpleandenjoyableagain.Swaptheboilerplate,complexdebuggingandbrittlecodeforpowerful,reusablecomponentswrittenwith
plainJavaandHTM L.
Guice(pronounced'juice')isalightweightdependencyinjectionframeworkforJava6andabove,broughttoyoubyGoogle.OrientDB
GuicepluginallowstointegrateOrientDBinsideGuice.Features:
Integrationthroughguice-persist(UnitOfWork,PersistService,@Transactional,dynamicfinderssupported)
Supportfordocument,objectandgraphdatabases
Databasetypessupportaccordingtoclasspath(objectandgraphdbsupportactivatedbyaddingjarstoclasspath)
377
AvailablePluginsandTools
Automappingentitiesinpackagetodbschemeorusingclasspathscanningtomapannotatedentities
Autodbcreation
Hooksforschemamigrationanddatainitializationextensions
Allthreedatabasetypesmaybeusedinsingleunitofwork(buteachtypewilluseitsowntransaction)
Vert.xisalightweight,highperformanceapplicationplatformfortheJVM that'sdesignedformodernmobile,web,andenterprise
applications.Vert.xPersistorM oduleforTinkerpop-compatibleGraphDatabaseslikeOrientDB.
GephiVisualtoolusagewithOrientDBandtheBlueprintsimporter
spring-orientdbisanattempttoprovideaPlatformTransactionM anagerforOrientDBusablewiththeSpringFramework,inparticular
with@Transactionalannotation.Apache2license
OrientDBsessionstoreforConnect
Puppetmodule
Chef
378
AvailablePluginsandTools
ApacheTomcatrealmpluginbyJonathanTellier
ShibbolethconnectorbyJonathanTellier.TheShibbolethSystemisastandardsbased,opensourcesoftwarepackageforwebsingle
sign-onacrossorwithinorganizationalboundaries.Itallowssitestomakeinformedauthorizationdecisionsforindividualaccessof
protectedonlineresourcesinaprivacy-preservingmanner
Griffonplugin,Apache2license
JCAconnectors
OPS4JOrientprovidesaJCAresourceadapterforintegratingOrientDBwithJavaEE6servers
OrientDBJCAconnectortoaccesstoOrientDBdatabaseviaJCAAPI+XATransactions
PacerpluginbyPaulDlug.PacerisaJRubygraphtraversalframeworkbuiltontheTinkerpopstack.ThispluginenablesfullOrientDB
graphsupportinPacer.
EventStoreforAxonframework,whichusesfullytransactional(fullACIDsupport)NoSQLdatabaseOrientDB.AxonFramework
helpsbuildscalable,extensibleandmaintainableapplicationsbysupportingdevelopersapplytheCommandQueryResponsibility
Segregation(CQRS)architecturalpattern
AccessingOrientDBusingSlick
379
AvailablePluginsandTools
JackrabbitmoduletouseOrientDBasbackend.
PluginforFuelPHPframework.
orientqb
orientqbisabuilderforOSQLquerylanguagewritteninJava.orientqbhasbeenthoughttohelpdevelopersinwritingcomplexqueries
dynamicallyandaimstobesimplebutpowerful.
380
JavaAPI
JavaAPI
OrientDBiswritten100%inJava.YoucanusethenativeJavaAPIswithoutanydriveroradapter.HereistheJavadocs.
Architectureofcomponents
OrientDBprovides3differentJavaAPIstoworkwithOrientDB.Eachonehasprosandcons.
WhichAPItochoosebetweenGraphandDocument?LookalsoatGraph-or-Document-API?.
GraphAPI
UseOrientDBasaGraphDatabaseworkingwithVerticesandEdges.GraphAPIis100%compliantwithTinkerPopstandard.
API:GraphAPI
DocumentAPI
Handlesrecordsasdocuments.Documentsarecomprisedoffields.Fieldscanbeanyofthetypessupported.DoesnotneedaJava
domainPOJO,asrequiredfortheObjectDatabase.Canbeusedasschema-lessorschema-basemodes.
API:DocumentAPI
ObjectAPI
It'stheJPAlikeinterfacewherePOJOareautomaticallyboundtothedatabaseasdocuments.Canbeusedinschema-lessorschemabasedmodes.ThisAPIhasn'tbeenimprovedsinceOrientDBv1.5.PleaseconsiderusingDocumentorGraphAPIbywritingan
additionallayerofmappingwithyourPOJO.WhileyoucanusebothGraphandDocumentAPIsatthesametime,theObjectAPIis
compatiblewithDocumentAPI,butitdoesn'tworkverywellwiththeGraphAPI.ThemainreasonisthatyoushouldcreatePOJOs
thatmimictheVertexandEdgeclasseswithsuboptimalperformanceincomparisonwithdirectGraphAPI.Forthisreasonwedon't
suggesttoworkwithObjectAPIwithaGraphdomain.YoucouldevaluateusingObjectM appingontopofOrientDBBlueprints
GraphAPI,suchasTinkerPopFrames,FermaandTotorom.
API:ObjectDatabase
381
JavaAPI
Whattouse?FeatureMatrix
Graph
Document
Object
API
GraphAPI
DocumentAPI
ObjectDatabase
Usethis
if
Youworkwithgraphsandwant
yourcodetobeportableacross
TinkerPopBlueprints
implementations
Yourdomainfitsbetterthe
DocumentDatabaseuse
casewithschema-less
structures
IfyouneedafullObjectOriented
abstractionthatbindsallthedatabase
entitiestoPOJO(PlainOldJava
Object)
Easyto
switch
from
OtherGraphDBslikeNeo4Jor
Titan.IfyouusedTinkerPop
standardOrientDBisadrop-in
replacement
OtherDocumentDBlike
M ongoDBandCouchDB
JPAapplications
Java
class
OrientGraph
ODatabaseDocumentTx
OObjectDatabaseTx
Query
Yes
Yes
Yes
Schema
Less
Yes
Yes
Yes
Schema
full
Yes
Yes
Yes
Speed *
90%
100%
50%
*SpeedcomparisonforgenericCRUDoperationssuchasquery,insertion,updateanddeletion.Largerisbetter.100%isfastest.In
generalthepriceofahighlevelofabstractionisaspeedpenalty,butrememberthatOrientisordersofmagnitudefasterthantheclassic
RDBM S.SousingtheObjectDatabasegivesyouahighlevelofabstractionwithmuchlesscodetodevelopandmaintain.
WhichlibrarydoIuse?
OrientDBcomeswithsomejarfilescontainedinthelibdirectory
JARname
orientdbcore-*.jar
Description
Corelibrary
Whenrequired
Always
Dependson3rdpartyjars
snappy-*.jarasoptional,
performancepack: orientdbnativeos-*.jar, jna-*.jarand
jna-platform-*.jar
orientdbclient*.jar
Remoteclient
Whenyourapplicationtalkswitha
remoteserver
orientdbenterprise*.jar
Deprecatedsincev2.2.Base
packagewiththeprotocoland
networkclassessharedby
clientandserver
Whenyourapplicationtalkswitha
remoteserver
orientdbserver*.jar
Servercomponent
It'susedbytheservercomponent.
Includeitonlyifyou'reembedding
aserver
orientdbtools-*.jar
Containtheconsoleand
consolecommands
Never,unlessyouwanttoexecute
consolecommanddirectlybyyour
application.Usedbytheconsole
application
orientdbobject*.jar
ContaintheObjectDatabase
interface
Includeitifyou'reusingthis
interface
javassist.jar, persistenceapi-1.0.jar
orientdbgraphdb*.jar
ContaintheGraphDB
interface
Includeitifyou'reusingthis
interface
blueprints-core-*.jar
orientdbdistributed*.jar
Containthedistributedplugin
Includeitifyou'reworkingwitha
servercluster
hazelcast-*.jar
382
JavaAPIIntroduction
JavaTutorial
IntheeventthatyouareusedonlytoRelationdatabasesystems,youmayfindOrientDBaveryunfamiliarsystemtoworkwith.
GiventhatitalsosupportsDocument,GraphandObject-Orientedmodes,itrequiresdifferentJavaAPI's.But,therearesome
similaritiesbetweenthemtoo.
SimilartoJDBC,aBlueprintsAPIexists,madebyTinkerpop,whichsupportsthebasicoperationsonagraphdatabase.Thereisan
OrientDBdriver,(or,tobemoreaccurate,anadapter),whichmakesitpossibletooperatewithouthavingtodealwithOrientDB
classes.Thismeansthattheresultingcodeismoreportable,giventhatBlueprintsoffersadapterstoothergraphingdatabasesystems.
Ifyouneedtotweakthedatabaseconfiguraiton,youneedtouseOrientDBAPI'sdirectly.Itisrecommendthatinthesesituationsyou
useamix:Bluepringtswhenyoucan,theOrientDBAPI'swherenecessary.
OrientDBJavaAPIs
TherearethreedifferentAPI'sthatOrientDBshipswith.Chooseonebasedonyourmode.
GraphAPI(suggested)
DocumentAPI
ObjectAPI
OrientDBcomeswith3differentAPIs.Pickyourbasedonyourmodel(formoreinformationlookatJavaAPI):
FormoreinformationontheAPI'singeneral,seeJavaAPI
GraphAPI
ConnectingtoaGraphDatabase
Thefirstobjectyouneedisa OrientGraph:
importcom.tinkerpop.blueprints.impls.orient.OrientGraph;
OrientGraphgraph=newOrientGraph("local:test","username","password");
InsertingVerticesandEdges
WhileOrientDBcanworkwiththegeneric Vclassforverticiesand Eclassforedges,yougainmuchmorepowerbydefiningcustom
typesforbothverticesandedges.
odb.createVertexType("Person");
odb.createVertexType("Address");
TheBlueprintadapterforOrientDBisthread-safeandautomaticallycreatesatransactionwherenecessary.Thatis,itcreatesa
transactionatthefirstoperation,intheeventthatatransactionhasnotyetexplicitlybeenstarted.Youhavetospecifywhere
transactionsend,forcommitsorrollbacks.
ToaddverticesintothedatabasewiththeBlueprintsAPI:
VertexvPerson=graph.addVertex("class:Person");
vPerson.setProperty("firstName","John");
vPerson.setProperty("lastName","Smith");
VertexvAddress=graph.addVertex("class:Address");
vAddress.setProperty("street","VanNessAve.");
vAddress.setProperty("city","SanFrancisco");
vAddress.setProperty("state","California");
383
JavaAPIIntroduction
Bearinmind,thespecificsyntaxwithBlueprintis class:<classname>.Youmustusethissyntaxincreatinganobjecttospecifyits
class.Thisisnotmandatory.Itisalsopossibletospecifya nullvalue,(whichmeansavertexiscreatedwiththeclass V,asitsthe
superclassforallverticesinOrientDB).
VertexvPerson=graph.addVertex(null);
Inconsequenceofthisisthatyoucannotdistinguish nullverticesfromotherverticesinaquery.
UseasimilarAPIinaddinganedge:
OrientEdgeeLives=graph.addEdge(null,vPerson,vAddress,"lives");
InOrientDB,theBlueprintslabelconceptisboundtoanedge'sclass.Youcancreateanedgeoftheclass livesbypassingitasalabel
orasaclassname.
OrientEdgeeLives=graph.addEdge("class:lives",vPerson,vAddress,null);
Youhavenowcreated:
[JohnSmith:Person]--[lives]-->[VanNessAve:Address]
Bearinmindthat,inthisexample,youhaveusedapartiallyschema-fullmode,asyoudefinedthevertextypes,butnottheirproperties.
Bydefault,OrientDBdynamicallyacceptseverythingworkinginaschema-lessmode.
SQLqueries
TheTinkerpopinterfacesallowyoutoexecutefluentqueriesorGermlinqueries,butyoucanstillusethepowerofOrientDBSQL
throughthe .command()method.
for(Vertexv:(Iterable<Vertex>)graph.command(
newOCommandSQL("SELECTEXPAND(OUT('bough'))FROMCustomerWHEREname='Jay'")).execute()){
System.out.println("-Bought:"+v);
}
Inadditiontoqueries,youcanalsoexecuteanySQLcommand,suchasCREATEVERTEX,Update,orDELETEVERTEX.
Alongwithqueries,youcanexecuteanySQLcommandlikeCREATEVERTEX,UPDATE,orDELETEVERTEX.Forexample,
intmodified=graph.command(
newOCommandSQL("UPDATECustomerSETlocal=trueWHERE'Rome'INout('lives').name")).execute());
Thissetsanewpropertycalled localto trueonallinstancesinthe CustomerclassthatliveinRome.
384
GraphAPI
GraphAPI
OrientDBadherestotheTinkerPopBlueprintsstandardandusesitasdefaultGraphJavaAPI.
Requirements
TousetheGraphAPIincludethefollowingjarsinyourclasspath:
orientdb-core-*.jar
blueprints-core-*.jar
orientdb-graphdb-*.jar
Alsoincludethefollowing3rdpartyjars:
jna-*.jar
jna-platform-*.jar
concurrentlinkedhashmap-lru-*.jar
Ifyou'reconnectedtoaremoteserver(notlocal/plocal/memorymodes)includealso:
orientdb-client-*.jar
orientdb-enterprise-*.jar
ToalsousetheTinkerPopPipestoolincludealso:
pipes-*.jar
ToalsousetheTinkerPopGremlinlanguageincludealso:
gremlin-java-*.jar
gremlin-groovy-*.jar
groovy-*.jar
NOTE:Startingfromv2.0,LightweightEdgesaredisabledbydefaultwhennewdatabasearecreated.
Introduction
TinkerpopisacompletestackofprojectstohandleGraphs:
Blueprintsprovidesacollectionofinterfacesandimplementationstocommon,complexdatastructures.Inshort,Blueprints
providesaonestopshopforimplementedinterfacestohelpdeveloperscreatesoftwarewithoutbeingtiedtoparticularunderlying
datamanagementsystems.
Pipesisagraph-baseddataflowframeworkforJava1.6+.Aprocessgraphiscomposedofasetofprocessverticesconnectedto
oneanotherbyasetofcommunicationedges.Pipessupportsthesplitting,merging,andtransformationofdatafrominputto
output.
GremlinisaTuring-complete,graph-basedprogramminglanguagedesignedforkey/value-pairmulti-relationalgraphs.Gremlin
makesuseofanXPath-likesyntaxtosupportcomplexgraphtraversals.Thislanguagehasapplicationintheareasofgraphquery,
analysis,andmanipulation.
RexsterisaRESTfulgraphshellthatexposesanyBlueprintsgraphasastandaloneserver.Extensionssupportstandardtraversal
goalssuchassearch,score,rank,and,inconcert,recommendation.RexstermakesextensiveuseofBlueprints,Pipes,andGremlin.
InthiswayitspossibletorunRexsterovervariousgraphsystems.ToconfigureRexstertoworkwithOrientDBfollowthisguide:
configuration.
S ailOuplementationtouseOrientDBasaRDFTripleStore.
385
GraphAPI
GetstartedwithBlueprints
OrientDBsupportsdifferentkindofstoragesanddependsbytheDatabaseURLused:
PersistentembeddedGraphDB.OrientDBislinkedtotheapplicationasJAR(Nonetworktransfer).Useplocalasprefix.
Example"plocal:/tmp/graph/test"
In-MemoryembeddedGraphDB.Keepsallthedataonlyinmemory.Usememoryasprefix.Example"memory:test"
PersistentremoteGraphDB.UsesabinaryprotocoltosendandreceivedatafromaremoteOrientDBserver.Useremoteas
prefix.Example"remote:localhost/test".ItrequiresaOrientDBServerinstanceisupandrunningatthespecifiedaddress(localhost
inthiscase).Remotedatabasecanbepersistentorin-memoryaswell.
WorkingwiththeGraphDB
BeforeworkingwithagraphyouneedaninstanceofOrientGraphclass.TheconstructorgetsaURLthatisthelocationofthedatabase.
Ifthedatabasealreadyexists,itwillbeopened,otherwiseitwillbecreated.Howeveranewdatabasecanonlybecreatedinplocalor
memorymode,notinremotemode.Inmulti-threadedapplicationsuseoneOrientGraphinstanceperthread.Alsoallthegraph
components(VerticesandEdges)arenotthread-safe,sosharingthembetweenthreadscouldcauseunpredictableerrors.
Remembertoalwaysclosethegraphoncedoneusingthe .shutdown()method.
Example:
OrientGraphgraph=newOrientGraph("plocal:C:/temp/graph/db");
try{
...
}finally{
graph.shutdown();
}
Usethefactory
Startingfromv1.7thebestwaytogetaGraphinstanceisthroughtheOrientGraphFactory.Toknowmore:UsetheGraphFactory.
Example:
//ATTHEBEGINNING
OrientGraphFactoryfactory=newOrientGraphFactory("plocal:C:/temp/graph/db").setupPool(1,10);
//EVERYTIMEYOUNEEDAGRAPHINSTANCE
OrientGraphgraph=factory.getTx();
try{
...
}finally{
graph.shutdown();
}
Transactions
Beforev2.1.7,everytimethegraphismodifiedanimplicittransactionisstartedautomaticallyifnoprevioustransactionwasrunning.
Transactionsarecommittedautomaticallywhenthegraphisclosedbycallingthe shutdown()methodorbyexplicit commit().To
rollbackchangescallthe rollback()method.
Afterv2.1.7,youcansetuptheconsistencylevel.
Changesinsideatransactionwillbetemporaryuntilthecommitorthecloseofthegraphinstance.Concurrentthreadsorexternalclients
canseethechangesonlywhenthetransactionhasbeenfullycommitted.
Fullexample:
386
GraphAPI
try{
Vertexluca=graph.addVertex(null);//1stOPERATION:IMPLICITLYBEGINATRANSACTION
luca.setProperty("name","Luca");
Vertexmarko=graph.addVertex(null);
marko.setProperty("name","Marko");
EdgelucaKnowsMarko=graph.addEdge(null,luca,marko,"knows");
graph.commit();
}catch(Exceptione){
graph.rollback();
}
Surroundingthetransactionbetweenatry/catchassuresthatanyerrorswillrollbackthetransactiontothepreviousstatusforallthe
involvedelements.Formoreinformation,lookatConcurrency.
NOTE:Beforev2.1.7,toworkagainstagraphalwaysusetransactionalOrientGraphinstancesandnevernon-transactionalonestoavoid
graphcorruptionfrommulti-threadedchanges.Anon-transactionalgraphinstancecreatedwith OrientGraphNoTxgraph=
factory.getNoTx();isonlyusefulifyoudon'tworkwithdatabutwanttodefinethedatabaseschemaorforbulkinserts.
Optimisticapproach
OrientDBsupportsoptimistictransactions,sonolockiskeptwhenatransactionisrunning,butatcommittimeeachgraphelement
versionischeckedtoseeiftherehasbeenanupdatebyanotherclient.Thisisthereasonwhyyoushouldwriteyourcodetobe
concurrency-proofbyhandlingtheconcurrentupdatingcase:
for(intretry=0;retry<maxRetries;++retry){
try{
//LOOKUPFORTHEINVOICEVERTEX
Iterable<Vertex>invoices=graph.getVertices("invoiceId",2323);
Vertexinvoice=invoices.iterator().next();
//CREATEANEWITEM
VertexinvoiceItem=graph.addVertex("class:InvoiceItem");
invoiceItem.field("price",1000);
//ADDITTOTHEINVOICE
invoice.addEdge(invoiceItem);
graph.commit();
//OK,EXITFROMRETRYLOOP
break;
}catch(ONeedRetryExceptione){
//SOMEONEHAVEUPDATETHEINVOICEVERTEXATTHESAMETIME,RETRYIT
}
}
WorkingwithVerticesandEdges
Createavertex
TocreateanewVertexinthecurrentGraphcalltheVertexOrientGraph.addVertex(Objectid))method.Notethattheidparameteris
ignoredsinceOrientDBimplementationassignsaunique-idoncethevertexiscreated.ToreturnituseVertex.getId()).Example:
Vertexv=graph.addVertex(null);
System.out.println("Createdvertex:"+v.getId());
Createanedge
AnEdgelinkstwoverticespreviouslycreated.TocreateanewEdgeinthecurrentGraphcalltheEdgeOrientGraph.addEdge(Objectid,
VertexoutVertex,VertexinVertex,Stringlabel))method.NotethattheidparameterisignoredsinceOrientDBimplementationassignsa
unique-idoncetheEdgeiscreated.ToreturnituseEdge.getId()). outVertexistheVertexinstancewheretheEdgestartsand inVertex
istheVertexinstancewheretheEdgeends. labelistheEdge'slabel.Specifynulltonotassignit.Example:
387
GraphAPI
Vertexluca=graph.addVertex(null);
luca.setProperty("name","Luca");
Vertexmarko=graph.addVertex(null);
marko.setProperty("name","Marko");
EdgelucaKnowsMarko=graph.addEdge(null,luca,marko,"knows");
System.out.println("Creatededge:"+lucaKnowsMarko.getId());
Ifyou'reinterestedonoptimizingcreationofedgesbyconcurrentthreads/clients,lookatConcurrencyonaddingedges.
RetrievealltheVertices
Toretrievealltheverticesusethe getVertices()method:
for(Vertexv:graph.getVertices()){
System.out.println(v.getProperty("name"));
}
RetrievealltheEdges
ToretrievealltheverticesusethegetEdges())method:
for(Edgee:graph.getEdges()){
System.out.println(e.getProperty("age"));
}
NOTE:WhenLightweightEdgesareenabled(startingfromv2.0aredisabledbydefault),edgesarestoredaslinksnotasrecords.Thisis
toimproveperformance.Asaconsequence, getEdges()willonlyretrieverecordsofclassE.WithuseLightweightEdges=true,records
ofclassEareonlycreatedundercertaincircumstances(e.g.iftheEdgehasproperties)otherwisetheywillbelinksontheinandout
vertices.Ifyoureallywant getEdges()toreturnalledges,disabletheLightweightEdgesfeaturebyexecutingthiscommandonce:
alterdatabasecustomuseLightweightEdges=false.Thiswillonlytakeeffectfornewedgessoyou'llhavetoconvertthelinkstoactual
edgesbeforegetEdgeswillreturnalledges.Formoreinformationlookat:Troubleshooting:Whycan'tIseealltheedges.
RemovingaVertex
ToremoveavertexfromthecurrentGraphcalltheOrientGraph.removeVertex(Vertexvertex))method.Thevertexwillbedisconnected
fromthegraphandthenremoved.Disconnectionmeansthatallthevertex'sedgeswillbedeletedaswell.Example:
graph.removeVertex(luca);
RemovinganEdge
ToremoveanedgefromthecurrentGraphcalltheOrientGraph.removeEdge(Edgeedge))method.Theedgewillberemovedandthetwo
verticeswillnotbeconnectedanymore.Example:
graph.removeEdge(lucaKnowsMarko);
Setandgetproperties
VerticesandEdgescanhavemultiplepropertieswherethekeyisaStringandthevaluecanbeanysupportedOrientDBtypes.
TosetapropertyusethemethodsetProperty(Stringkey,Objectvalue)).
TogetapropertyusethemethodObjectgetProperty(Stringkey)).
TogetallthepropertiesusethemethodSet<String>getPropertyKeys()).
ToremoveapropertyusethemethodvoidremoveProperty(Stringkey)).
Example:
388
GraphAPI
vertex2.setProperty("x",30.0f);
vertex2.setProperty("y",((float)vertex1.getProperty("y"))/2);
for(Stringproperty:vertex2.getPropertyKeys()){
System.out.println("Property:"+property+"="+vertex2.getProperty(property));
}
vertex1.removeProperty("y");
SettingMultipleProperties
BlueprintsExtensionOrientDBBlueprintsimplementationsupportssettingofmultiplepropertiesinoneshotagainstVerticesand
Edges.Thisimprovesperformanceavoidingtosavethegraphelementateverypropertyset:setProperties(Object...)).Example:
vertex.setProperties("name","Jill","age",33,"city","Rome","born","Victoria,TX");
YoucanalsopassaM apofvaluesasfirstargument.Inthiscaseallthemapentrieswillbesetaselementproperties:
Map<String,Object>props=newHashMap<String,Object>();
props.put("name","Jill");
props.put("age",33);
props.put("city","Rome");
props.put("born","Victoria,TX");
vertex.setProperties(props);
CreatingElementandPropertiesalltogether
Ifyouwanttocreateavertexoranedgewhilesettingtheinitialproperties,theOrientDBBlueprintsimplementationoffersnew
methodstodoit:
graph.addVertex("class:Customer","name","Jill","age",33,"city","Rome","born","Victoria,TX");
ThiscreatesanewVertexofclass Customerwiththeproperties: name, age, city,and born.ThesameisforEdges:
person1.addEdge("class:Friend",person2,null,null,"since","2013-07-30");
ThiscreatesanewEdgeofclass Friendbetweenvertices person1and person2withtheproperty since.
Bothmethodsaccepta Map<String,Object>asaparametertosetonepropertypermapentry(seeabovefortheexample).
Thesemethodsareespeciallyusefulifyou'vedeclaredconstraintsintheschema.Forexample,apropertycannotbenull,andonlyusing
thesemethodswillthevalidationcheckssucceed.
UsingIndices
OrientDBallowsexecutionofqueriesagainstanyfieldofverticesandedges,indexedandnot-indexed.Thefirstruletospeedupqueries
istosetupindicesonthekeypropertiesyouuseinthequery.Forexample,ifyouhaveaquerythatislookingforalltheverticeswith
thename'OrientDB'youdothis:
graph.getVertices("name","OrientDB");
Withoutanindexagainsttheproperty"name"thisexecutioncouldtakealotoftime.Solet'screateanewindexagainstthe"name"
property:
graph.createKeyIndex("name",Vertex.class);
IfthenameM USTbeuniqueyoucanenforcethisconstraintbysettingtheindexas"UNIQUE"(thisisanOrientDBonlyfeature):
graph.createKeyIndex("name",Vertex.class,newParameter("type","UNIQUE"));
389
GraphAPI
ThisconstraintwillbeappliedtoalltheVertexandsub-typeinstances.Tospecifyanindexagainstacustomtypelikethe"Customer"
verticesusetheadditionalparameter"class":
graph.createKeyIndex("name",Vertex.class,newParameter("class","Customer"));
YoucanalsohavebothUNIQUEindexagainstcustomtypes:
graph.createKeyIndex("name",Vertex.class,newParameter("type","UNIQUE"),newParameter("class","Customer"));
Tocreateacaseinsensitiveindexusetheadditionalparameter"collate":
graph.createKeyIndex("name",Vertex.class,newParameter("type","UNIQUE"),newParameter("class","Customer"),newParameter("
collate","ci"));
Togetavertexoranedgebykeyprefixusetheclassnamebeforetheproperty.Fortheexampleaboveuse Customer.nameinplaceof
only nametousetheindexcreatedagainstthefield nameofclass Customer:
for(Vertexv:graph.getVertices("Customer.name","Jay")){
System.out.println("Foundvertex:"+v);
}
Iftheclassnameisnotpassed,then"V"istakenforverticesand"E"foredges:
graph.getVertices("name","Jay");
graph.getEdges("age",20);
FormoreinformationaboutindiceslookatIndexguide.
UsingNon-TransactionalGraphs
TospeedupoperationslikeonmassiveinsertionsyoucanavoidtransactionsbyusingadifferentclassthanOrientGraph:
OrientGraphNoTx.Inthiscaseeachoperationisatomicanddataisupdatedateachoperation.Whenthemethodreturns,the
underlyingstorageisupdated.Usethisforbulkinsertsandmassiveoperationsorforschemadefinition.
NOTE:Usingnon-transactionalgraphscouldcreatecorruptioninthegraphifchangesaremadeinmultiplethreadsatthesametime.So
usenon-transactionalgraphinstancesonlyfornonmulti-threadedoperations.
ConfiguretheGraph
Startingfromv1.6OrientDBsupportsconfigurationofthegraphbysettingallthepropertiesduringconstruction:
390
GraphAPI
Name
Description
Default
value
blueprints.orientdb.url
DatabaseURL
-
blueprints.orientdb.username
Username
admin
blueprints.orientdb.password
Userpassword
admin
blueprints.orientdb.saveOriginalIds
SavestheoriginalelementIDsbyusingthepropertyid.
Thiscouldbeusefulonimportofagraphtopreserve
originalids.
false
blueprints.orientdb.keepInM emoryReferences
AvoidskeepingrecordsinmemorybyusingonlyRIDs
false
blueprints.orientdb.useCustomClassesForEdges
UsestheEdge'slabelasOrientDBclass.Ifitdoesn'texist
createitunderthehood.
true
blueprints.orientdb.useCustomClassesForVertex
UsesVertex'slabelasOrientDBclass.Ifitdoesn'texist
createitunderthehood.
true
blueprints.orientdb.useVertexFieldsForEdgeLabels
StorestheEdge'srelationshipsintheVertexbyusingthe
Edge'sclass.Thisallowsusingmultiplefieldsandmakes
fastertraversalbyedge'slabel(class).
true
blueprints.orientdb.lightweightEdges
UsesLightweightEdges.Thisavoidscreatingaphysical
documentperedge.Documentsarecreatedonlywhenthe
Edgeshaveproperties.
false
blueprints.orientdb.autoStartTx
Autostartsatransactionassoonasthegraphischangedby
adding/remoteverticesandedgesandproperties.
true
Gremlinusage
IfyouuseGREM LINlanguagewithOrientDBremembertoinitializeitwith:
OGremlinHelper.global().create()
LookatthesepagesaboutGREM LINusage:
HowtousetheGremlinlanguagewithOrientDB
GettingstartedwithGremlin
UsageofGremlinthroughHTTP/RESTfulAPIusingtheRexterproject.
Multi-ThreadedApplications
M ulti-threadedapplicationsmustuseoneOrientGraphinstanceperthread.Formoreinformationaboutmulti-threadinglookatJava
M ultiThreading.Alsoallthegraphcomponents(VerticesandEdges)arenotthread-safe,sosharingthembetweenthreadscouldcause
unpredictableerrors.
BlueprintsExtensions
OrientDBisaGraphDatabaseonsteroidsbecauseitmergesthegraph,document,andobject-orientedworldstogether.Belowaresome
ofthefeaturesexclusivetoOrientDB.
Customtypes
OrientDBsupportscustomtypesforverticesandedgesinanObjectOrientedmanner.Evenifthisisn'tsupporteddirectlyby
Blueprintstherearesometrickstousethem.LookattheGraphSchemapagetoknowhowtocreateaschemaandworkagainsttypes.
OrientDBaddedafewvariantstotheBlueprintsmethodstoworkwithtypes.
Creatingverticesandedgesinspecificclusters
391
GraphAPI
Bydefaulteachclasshasoneclusterwiththesamename.YoucanaddmultipleclusterstotheclasstoallowOrientDBtowritevertices
andedgesonmultiplefiles.FurthermoreworkinginDistributedM odeeachclustercanbeconfiguredtobemanagedbyadifferentserver.
Example:
//SAVETHEVERTEXINTOTHECLUSTER'PERSON_USA'ASSIGNEDTOTHENODE'USA'
graph.addVertex("class:Person,cluster:Person_usa");
Retrieveverticesandedgesbytype
Toretrievealltheverticesof Personclassusethespecial getVerticesOfClass(StringclassName)method:
for(Vertexv:graph.getVerticesOfClass("Person")){
System.out.println(v.getProperty("name"));
}
AlltheverticesofclassPersonandallsubclasseswillberetrieved.Thisisbecausebydefaultpolymorphismisused.Ifyou'reinterested
ONLYinto Personvertices(excludinganysub-types)usethe getVerticesOfClass(StringclassName,booleanpolymorphic)method
specifying falseinthesecondargument polymorphic:
for(Vertexv:graph.getVerticesOfClass("Person",false)){
System.out.println(v.getProperty("name"));
}
Thesamevariantsalsoapplytothe getEdges()methodas:
getEdgesOfClass(StringclassName)and
getEdgesOfClass(StringclassName,booleanpolymorphic)
OrderedEdges
OrientDB,bydefault,usesasettohandletheedgecollection.Sometimesit'sbetterhavinganorderedlisttoaccesstheedgebyan
offset.Example:
person.createEdgeProperty(Direction.OUT,"Photos").setOrdered(true);
Everytimeyouaccesstheedgecollectiontheedgesareordered.Belowisanexampletoprintallthephotosinanorderedway.
for(Edgee:loadedPerson.getEdges(Direction.OUT,"Photos")){
System.out.println("Photoname:"+e.getVertex(Direction.IN).getProperty("name"));
}
ToaccesstheunderlyingedgelistyouhavetousetheDocumentDatabaseAPI.Here'sanexampletoswapthe10thphotowiththelast.
//REPLACEEDGEPhotos
List<ODocument>photos=loadedPerson.getRecord().field("out_Photos");
photos.add(photos.remove(9));
TohavethesameresultbyusingSQL,executethefollowingcommands:
createpropertyout_PhotosLINKLIST
alterpropertyUser.out_Photoscustomordered=true
Workingondetachedelements
Whenyouworkwithwebapplications,it’sverycommontoqueryelementsandrenderthemtotheusertolethimapplysomechanges.
Oncetheuserupdatessomefieldsandpressesthe“save”button,whathappens?
392
GraphAPI
Beforenowthedeveloperhadtotrackthechangesinaseparatestructure,loadthevertex/edgefromthedatabase,andapplythechanges
totheelement.
StartingwithOrientDBv1.7weaddedtwonewmethodstotheGraphAPIontheOrientElementandOrientBaseGraphclasses:
OrientElement.detach()
OrientElement.attach()
OrientBaseGraph.detach(OrientElement)
OrientBaseGraph.attach(OrientElement)
Detach
DetachmethodsfetchalltherecordcontentinRAM andresettheconnectiontotheGraphinstance.Thisallowsyoutomodifythe
elementoff-lineandtore-attachitoncefinished.
Attach
Oncethedetachedelementhasbeenmodified,tosaveitbacktothedatabaseyouneedtocallthe attach()method.Itrestoresthe
connectionbetweentheGraphElementandtheGraphInstance.
Example
Thefirststepisloadavertexanddetachit.
OrientGraphg=OrientGraph("plocal:/temp/db");
try{
Iterable<OrientVertex>results=g.query().has("name",EQUALS,"fast");
for(OrientVertexv:results)
v.detach();
}finally{
g.shutdown();
}
Afterawhiletheelementisupdated(fromGUIorbyapplication)
v.setProperty("name","superfast!");
On“save”re-attachtheelementandsaveittothedatabase.
OrientGraphg=OrientGraph("plocal:/temp/db");
try{
v.attach(g);
v.save();
}finally{
g.shutdown();
}
FAQ
Doesdetachgorecursivelytodetachallconnectedelements?No,itworksonlyatthecurrentelementlevel.
CanIaddanedgeagainstdetachedelements?No,youcanonlyget/set/removeapropertywhileisdetached.Anyotheroperation
thatrequiresthedatabasewillthrowanIllegalStateException.
Executecommands
TheOrientDBBlueprintsimplementationallowsyoutoexecutecommandsusingSQL,Javascript,andalltheothersupported
languages.
SQLqueries
393
GraphAPI
for(Vertexv:(Iterable<Vertex>)graph.command(
newOCommandSQL("SELECTEXPAND(out('bought'))FROMCustomerWHEREname='Jay'")).execute()){
System.out.println("-Bought:"+v);
}
Itispossibletohaveparametersinaqueryusingpreparedqueries.
Toexecuteanasynchronousquery:
graph.command(
newOSQLAsynchQuery<Vertex>("SELECTFROMMember",
newOCommandResultListener(){
intresultCount=0;
@Override
publicbooleanresult(ObjectiRecord){
resultCount++;
Vertexdoc=graph.getVertex(iRecord);
returnresultCount<100;
}
}).execute();
SQLcommands
Alongwithqueries,youcanexecuteanySQLcommandlike CREATEVERTEX, UPDATE,or DELETEVERTEX.Intheexamplebelowitsets
anewpropertycalled"local"totrueonalltheCustomersthatliveinRome:
intmodified=graph.command(
newOCommandSQL("UPDATECustomerSETlocal=trueWHERE'Rome'INout('lives').name")).execute());
Ifthecommandmodifiestheschema(like create/alter/dropclassand create/alter/droppropertycommands),remembertoforce
updatingoftheschemaofthedatabaseinstanceyou'reusingbycalling reload():
graph.getRawGraph().getMetadata().getSchema().reload();
FormoreinformationlookattheavailableSQLcommands.
SQLbatch
ToexecutemultipleSQLcommandsinabatch,usetheOCommandScriptandSQLasthelanguage.Thisisrecommendedwhencreating
edgesontheserverside,tominimizethenetworkroundtrip:
Stringcmd="BEGIN\n";
cmd+="LETa=CREATEVERTEXSETscript=true\n";
cmd+="LETb=SELECTFROMVLIMIT1\n";
cmd+="LETe=CREATEEDGEFROM$aTO$bRETRY100\n";
cmd+="COMMIT\n";
cmd+="return$e";
OIdentifiableedge=graph.command(newOCommandScript("sql",cmd)).execute();
FormoreinformationlookatSQLBatch.
Databasefunctions
ToexecuteadatabasefunctionitmustbewritteninJavascriptoranyothersupportedlanguages.Intheexamplebelowweimagine
havingwrittenthefunction updateAllTheCustomersInCity(cityName)thatexecutesthesameupdatelikeabove.Notethe'Rome'attribute
passedinthe execute()method:
graph.command(
newOCommandFunction("updateAllTheCustomersInCity")).execute("Rome"));
394
GraphAPI
Code
Toexecutecodeontheserversideyoucanselectbetweenthesupportedlanguage(bydefaultJavascript):
graph.command(
newOCommandScript("javascript","for(vari=0;i<10;++i){print('\nHelloWorld!');}")).execute());
Thisprintstheline"HelloWorld!"tentimesintheserverconsoleorinthelocalconsoleifthedatabasehasbeenopenedin"plocal"
mode.
AccesstotheunderlyingGraph
SincetheTinkerPopBlueprintsAPIisquiterawanddoesn'tprovidead-hocmethodsforverycommonusecases,youmightneedto
accesstheunderlyingODatabaseGraphTxobjecttobetterusethegraph-engineunderthehood.Commonsoperationsare:
Countincomingandoutgoingedgeswithoutbrowsingthemall
Getincomingandoutgoingverticeswithoutbrowsingtheedges
ExecuteaqueryusingSQL-likelanguageintegratedintheengine
TheOrientGraphclassprovidesthemethod .getRawGraph()toreturntheunderlyingdatabase:[DocumentDatabase].
Example:
finalOrientGraphgraph=newOrientGraph("plocal:C:/temp/graph/db");
try{
List<ODocument>result=graph.getRawGraph().query(
newOSQLSynchQuery("SELECTFROMVWHEREcolor='red'"));
}finally{
graph.shutdown();
}
Security
IfyouwanttouseOrientDBsecurity,usetheconstructorthatretrievestheURL,userandpassword.ToknowmoreaboutOrientDB
securityvisitSecurity.Bydefaultthe"admin"userisused.
Tuning
LookatthePerformanceTuningBlueprintspage.
395
GraphAPI
GraphFactory
TinkerPopBlueprintsstandarddoesn’tdefineaproper"Factory"togetgraphinstances.ForthisreasonOrientDBusersthatwantedto
useapoolofinstanceshadtomix2differentAPI:GraphandDocumentone.Example:
ODatabaseDocumentPoolpool=newODatabaseDocumentPool("plocal:/temp/mydb");
OrientGraphg=newOrientGraph(pool.acquire());
Noweverythingissimpler,thankstothenewOrientGraphFactoryclasstomanagegraphsineasyway.Thesearethemainfeatures:
bydefaultactsasafactorybycreatingnewdatabaseinstanceseverytime
canbeconfiguredtoworkasapool,byrecyclingdatabaseinstances
ifthedatabasedoesn’texist,it’screatedautomatically(butin"remote"mode)
returnstransactionalandnon-transactionalinstances
on graph.shutdown()thepooledinstanceisreturnedtothepooltobereused
Thisisthebasicwaytocreatethefactory,byusingthedefault"admin"user(with"admin"passwordbydefault):
OrientGraphFactoryfactory=newOrientGraphFactory("plocal:/temp/mydb");
Butyoucanalsopassuserandpassword:
OrientGraphFactoryfactory=newOrientGraphFactory("plocal:/temp/mydb","jayminer","amigarocks");
Toworkwitharecyclablepoolofinstanceswithminimum1,maximum10instances:
OrientGraphFactoryfactory=newOrientGraphFactory("plocal:/temp/mydb").setupPool(1,10);
OncethefactoryisconfiguredyoucangetaGraphinstancetostartworking.OrientGraphFactoryhas2methodstoretrievea
TransactionalandNon-Transactionalinstance:
OrientGraphtxGraph=factory.getTx();
OrientGraphNoTxnoTxGraph=factory.getNoTx();
Oragainyoucanconfigureinthefactorytheinstancesyouwantandusetheget()methodeverytime:
factory.setTransactional(false);
OrientGraphNoTxnoTxGraph=(OrientGraphNoTx)factory.get();
ToreturntheGraphinstancetothepool,calltheshutdownmethodongraphinstance. shutdown()willnotclosethegraphinstance,
butwillkeepopenandavailableforthenextrequester:
graph.shutdown();
Toreleasealltheinstancesandfreealltheresources(incaseofpoolusage),calltheclose():
factory.close();
396
GraphAPI
GraphSchema
AlthoughOrientDBcanworkinschema-lessmode,sometimesyouneedtoenforceyourdatamodelusingaschema.OrientDBsupports
schema-fullorschema-hybridsolutionswherethesecondonemeanstosetsuchconstraintsonlyforcertainfieldsandleavetheuserto
addcustomfieldstotherecords.Thismodeisatclasslevel,soyoucanhavethe"Employee"classasschema-fulland
"EmployeeInformation"classasschema-less.
S chema-Full:enablethestrict-modeatclasslevelandsetallthefieldsasmandatory
S chema-Less:createclasseswithnoproperties.Defaultmodeisnonstrict-modesorecordscanhavearbitraryfields
S chema-Hybrid,calledalsoSchema-Mixedisthemostused:createclassesanddefinesomefieldsbutleavetherecordtodefine
owncustomfields
NOTE:Changestotheschemaarenottransactional,soexecutethemoutsideatransaction.
Toaccesstotheschema,youcanuseSQLorAPI.WillfollowexamplesusingJavaAPI.
Foratutoriallookatthefollowinglinks:
OrientTechnologies'sBlogpostaboutUsingSchemawithGraphs
Class
AClass,ortype,isaconcepttakenfromtheObjectOrientedparadigm.InOrientDBdefinesatypeofrecord.It'stheclosestconceptto
aRelationalDBM STable.Classcanbeschema-less,schema-fullormixed.Aclasscaninheritfromanothershapingatreeofclasses.
Inheritancemeansthatthesub-classextendstheparentoneinheritingalltheattributesastheywasown.
Aclassmusthaveatleastoneclusterdefined(asitsdefaultcluster),butcansupportmultipleones.InthiscaseBydefaultOrientDB
willwritenewrecordsinthedefaultcluster,butreadswillalwaysinvolveallthedefinedclusters.Whenyoucreateanewclassby
defaultanewphysicalclusteriscreatedwiththesamenameoftheclassinlower-case.
TheGraphstructureisbasedontwoclasses:"V"forVerticesand"E"forEdges.Theseclassareautomaticallybuiltonceadatabaseis
builtusingthemode"graph".Ifyoudon'thavetheseclassesjustcreatethem(seebelow).
YoucanbuildagraphusingVandEinstancesbutit'sstronglysuggestedtousecustomtypesforverticesandedges.
Workingwithcustomvertexandedgetypes
TocreateacustomVertexclass(ortype)usethe createVertexType(<name>):
OrientGraphgraph=newOrientGraph("local:/temp/db");
OrientVertexTypeaccount=graph.createVertexType("Account");
Tocreateavertexoftype"Account"passastringwiththeformat "class:<name>"asvertexid:
Vertexv=graph.addVertex("class:Account");
SinceclassesarepolymorphicifyoulookforgenericVerticesalso"Account"instancesarereturned:
Iterable<Vertex>allVertices=graph.getVertices();
Toretrieveonlytheverticesof"Account"class:
Iterable<Vertex>accountVertices=graph.getVerticesOfClass("Account");
InBlueprintsEdgeshastheconceptof"label"todistinguishbetweenedgetypes.InOrientDBwebindstheconceptofEdgelabelto
Edgeclass.TocreateanEdgecustomtypeusethesimilarmethod createEdgeType(<name>):
397
GraphAPI
OrientGraphgraph=newOrientGraph("local:/temp/db");
OrientVertexTypeaccountVertex=graph.createVertexType("Account");
OrientVertexTypeaddressVertex=graph.createVertexType("Address");
//CREATETHEEDGETYPE
OrientEdgeTypelivesEdge=graph.createEdgeType("Lives");
Vertexaccount=graph.addVertex("class:Account");
Vertexaddress=graph.addVertex("class:Address");
//CREATETHEEDGE
Edgee=account.addEdge("Lives",address);
Inheritancetree
Classescanextendsotherclasses.Startingfrom2.1OrientDBsupportsalsomultipleinheritance.Tocreateaclassthatextendsaclass
differentby"V"(Vertex)andE(Edge)types,passtheclassnameonconstruction:
graph.createVertexType(<class-name>,<super-class>);//VERTEXTYPE
graph.createEdgeType(<class-name>,<super-class>);//EDGETYPE
Exampletocreateabaseclass"Account"andtwosub-classes"Provider"and"Customer":
graph.createVertexType("Account");
graph.createVertexType("Customer","Account");
graph.createVertexType("Provider","Account");
Getcustomtypes
Toretrievesuchcustomclassesusethemethods graph.getVertexType(<name>)and graph.getEdgeType(<name>).Example:
OrientVertexTypeaccountVertex=graph.getVertexType("Account");
OrientEdgeTypelivesEdge=graph.getEdgeType("Lives");
Droppersistenttypes
Todropapersistentclassusethe dropVertexType(<name>)and dropVertexType(<name>)methods.
graph.dropVertexType("Address");
graph.dropEdgeType("Lives");
Property
Propertiesarethefieldsoftheclass.InthisguidePropertyissynonymofField.
Createaproperty
Oncetheclasshasbeencreated,youcandefinefields(properties).Belowanexample:
OrientVertexTypeaccountVertex=graph.getVertexType("Account");
accountVertex.createProperty("id",OType.INTEGER);
accountVertex.createProperty("birthDate",OType.DATE);
Pleasenotethateachfieldmustbelongtooneof[Typessupportedtypes].
DroptheClassproperty
Todropapersistentclasspropertyusethe OClass.dropProperty(String)method.
398
GraphAPI
accountVertex.dropProperty("name");
Thedroppedpropertywillnotberemovedfromrecordsunlessyouexplicitlydeletethemusingthe[SQLUpdateSQLUPDATE+
REM OVEstatement].Example:
accountVertex.dropProperty("name");
database.command(newOCommandSQL("UPDATEAccountREMOVEname")).execute();
Constraints
Constraintswithdistributeddatabasescouldcauseproblemsbecausesomeoperationsareexecutedat2steps:create+
update.Forexampleinsomecircumstanceedgescouldbefirstcreated,thenupdated,butconstraintslike
M ANDATORYandNOTNULLagainstfieldswouldfailatthefirststepmakingthecreationofedgesnotpossibleon
distributedmode.
OrientDBsupportsanumberofconstrainsforeachfield:
Minimumvalue,acceptsastringbecauseworksalsofordateranges setMin()
Maximumvalue,acceptsastringbecauseworksalsofordateranges setMax()
Mandatory,itmustbespecified setMandatory()
Readonly,itmaynotbeupdatedafterrecordiscreated setReadonly()
NotNull,can'tbeNULL setNotNull()
Unique,doesn'tallowduplicatesandspeedupsearches.
Regexp,itmustsatisfytheRegularexpression.
Ordered,specifyifedgelistmustbeordered,soaListwillbeusedinplaceofSet.Themethodis setOrdered()
Example:
profile.createProperty("nick",OType.STRING).setMin("3").setMax("30").setMandatory(true).setNotNull(true);
profile.createIndex("nickIdx",OClass.INDEX_TYPE.UNIQUE,"nick");//Createsuniqueconstraint
profile.createProperty("name",OType.STRING).setMin("3").setMax("30");
profile.createProperty("surname",OType.STRING).setMin("3").setMax("30");
profile.createProperty("registeredOn",OType.DATE).setMin("2010-01-0100:00:00");
profile.createProperty("lastAccessOn",OType.DATE).setMin("2010-01-0100:00:00");
Indexesasconstrains
TolettoapropertyvaluetobeUNIQUEusetheUNIQUEindexasconstraintbypassingaParameterobjectwithkey"type":
graph.createKeyIndex("id",Vertex.class,newParameter("type","UNIQUE"));
ThisconstraintwillbeappliedtoalltheVertexandsub-typesinstances.Tospecifyanindexagainstacustomtypeusetheadditional
parameter"class":
graph.createKeyIndex("name",Vertex.class,newParameter("class","Member"));
YoucanalsohavebothUNIQUEindexagainstcustomtypes:
graph.createKeyIndex("id",Vertex.class,newParameter("type","UNIQUE"),newParameter("class","Member"));
Togetavertexoranedgebykeyprefixtheclassnametothefield.Fortheexampleaboveuse"M ember.name"inplaceofonly"name"
tousetheindexcreatedagainstthefield"name"ofclass"M ember":
for(Vertexv:graph.getVertices("Member.name","Jay")){
System.out.println("Foundvertex:"+v);
}
399
GraphAPI
Iftheclassnameisnotpassed,then"V"istakenforverticesand"E"foredges:
graph.getVertices("name","Jay");
graph.getEdges("age",20);
FormoreinformationaboutindexeslookatIndexguide.
(GobacktoGraph-Database-Tinkerpop)
400
GraphAPI
Partitionedgraphs
Thistutorialexplainsstep-by-stephowtocreatepartitionedgraphsusingtheRecordLevelSecurityfeatureintroducedinOrientDB
1.2.0.Thisfeatureissopowerfulwecantotallyseparatedatabase'srecordsassand-boxeswhereeach"Restricted"recordscan'tbe
accessedbynonauthorizedusers.Thistutorialdemonstratesthissand-boxesworkswellalsowiththeGraphDBAPIandthe
TinkerPopstack.PartitioninggraphsallowstobuildrealM ulti-tenantapplicationsinabreeze.
Requirements:
OrientDB1.2.0-SNAPSHOTorhigher
TinkerPopBlueprints2.2.0orhigher.
Createanewemptygraphdatabase
FirstopentheconsoleoftheGraphDBEditionandcreatethenewdatabase"blog"oftype"graph"againstthelocalfile-system:
$cd$ORIENTDB_HOME/bin
$console.sh
OrientDBconsolev.1.2.0-SNAPSHOTwww.orientechnologies.com
Type'help'todisplayallthecommandssupported.
InstallingextensionsforGREMLINlanguagev.2.2.0-SNAPSHOT
orientdb>CREATEDATABASElocal::../databases/blogadminadminlocalgraph
Creatingdatabase[local:../databases/blog]usingthestoragetype[local]...
Databasecreatedsuccessfully.
Currentdatabaseis:local:../databases/blog
Enablegraphpartitioning
NowturnonpartitioningagainstgraphbylettingclassesV(Vertex)andE(Edge)toextendtheéORestricted*class.Inthiswayany
accesstoVertexandEdgeinstancescanberestricted:
ALTERCLASSVsuperclassorestricted
Classupdatedsuccessfully
ALTERCLASSEsuperclassorestricted
Classupdatedsuccessfully
Create2users
Nowlet'sgocreating2users:"luca"and"steve".Firstaskthecurrentrolesindatabasetoknowthe"writer"role'srid:
401
GraphAPI
SELECTFROMorole
---+------+--------+------+---------------------------------------------------------------+---------------#|RID|name|mode|rules|inheritedRole
---+------+--------+------+---------------------------------------------------------------+----------------0|#4:0|admin|1|{}|null
1|#4:1|reader|0|{database=2,database.schema=2,database.cluster.internal=2,|null
||||{database.cluster.orole=2,database.cluster.ouser=2,|
||||database.class.*=2,database.cluster.*=2,database.command=2,|
||||database.hook.record=2|
2|#4:2|writer|0|{database=2,database.schema=7,database.cluster.internal=2,|null
||||database.cluster.orole=2,database.cluster.ouser=2,|
||||database.class.*=15,database.cluster.*=15,|
||||database.command=15,database.hook.record=15}|
---+------+--------+------+---------------------------------------------------------------+-----------------3item(s)found.Queryexecutedin0.045sec(s).
Foundit,it'sthe#4:2.Notcreate2userswithasfirstrole#4:2(writer):
INSERTINTOouserSETname='luca',status='ACTIVE',password='luca',roles=[#4:2]
Insertedrecord'OUser#5:4{name:luca,password:{SHA-256}D70F47790F689414789EEFF231703429C7F88A10210775906460EDBF38589D90,roles:
[1]}v1'in0,001000sec(s).
INSERTINTOouserSETname='steve',status='ACTIVE',password='steve',roles=[#4:2]
Insertedrecord'OUser#5:3{name:steve,password:{SHA-256}F148389D080CFE85952998A8A367E2F7EAF35F2D72D2599A5B0412FE4094D65C,roles
:[1]}v1'in0,001000sec(s).
Createasimplegraphasuser'Luca'
Nowit'stimetodisconnectandreconnecttotheblogdatabaseusingthenew"luca"user:
DISCONNECT
Disconnectingfromthedatabase[blog]...OK
CONNECTlocal:../databases/bloglucaluca
Connectingtodatabase[local:../databases/blog]withuser'luca'...OK
Nowcreate2vertices:aRestaurantandaPizza:
CREATEVERTEXSETlabel='food',name='Pizza'
Createdvertex'V#9:0{label:food,name:Pizza,_allow:[1]}v0'in0,001000sec(s).
CREATEVERTEXSETlabel='restaurant',name="Dante'sPizza"
Createdvertex'V#9:1{label:restaurant,name:Dante'sPizza,_allow:[1]}v0'in0,000000sec(s).
Nowconnectthese2verticeswithanedgelabelled"menu":
CREATEEDGEFROM#9:0TO#9:1SETlabel='menu'
Creatededge'[E#10:0{out:#9:0,in:#9:1,label:menu,_allow:[1]}v1]'in0,003000sec(s).
Tocheckifeverythingisokexecuteaselectagainstvertices:
402
GraphAPI
SELECTFROMV
---+------+------------+---------------+----------------#|RID|label|name|_allow|out
---+------+------------+---------------+--------+-------0|#9:0|food|Pizza|[1]|[1]
1|#9:1|restaurant|Dante'sPizza|[1]|null
---+------+------------+---------------+--------+-------2item(s)found.Queryexecutedin0.034sec(s).
Createasimplegraphasuser'Steve'
Nowlet'sconnecttothedatabaseusingthe'Steve'userandcheckiftherearevertices:
DISCONNECT
Disconnectingfromthedatabase[blog]...OK
CONNECTlocal:../databases/blogstevesteve
Connectingtodatabase[local:../databases/blog]withuser'steve'...OK
SELECTFROMV
0item(s)found.Queryexecutedin0.0sec(s).
Ok,noverticesfound.Trytocreatesomething:
CREATEVERTEXSETlabel='car',name='FerrariModena'
Createdvertex'V#9:2{label:car,name:FerrariModena,_allow:[1]}v0'in0,000000sec(s).
CREATEVERTEXSETlabel='driver',name='steve'
Createdvertex'V#9:3{label:driver,name:steve,_allow:[1]}v0'in0,000000sec(s).
CREATEEDGEFROM#9:2TO#9:3SETlabel='drive'
Creatededge'[E#10:1{out:#9:2,in:#9:3,label:drive,_allow:[1]}v1]'in0,002000sec(s).
Nowcheckthegraphjustcreated:
SELECTFROMV
---+------+--------+----------------+--------+-----#|RID|label|name|_allow|out
---+------+--------+----------------+--------+-----0|#9:2|car|FerrariModena|[1]|[1]
1|#9:3|driver|steve|[1]|null
---+------+--------+----------------+--------+-----2item(s)found.Queryexecutedin0.034sec(s).
The"Steve"userdoesn'tseetheverticesandedgescreatesbyotherusers!
Whathappenifwetrytoconnect2verticesofdifferentusers?
CREATEEDGEFROM#9:2TO#9:0SETlabel='security-test'
Error:com.orientechnologies.orient.core.exception.OCommandExecutionException:Erroronexecutionofcommand:OCommandSQL[text
=createedgefrom#9:2to#9:0setlabel='security-test']
Error:java.lang.IllegalArgumentException:Sourcevertex'#9:0'doesnotexist
ThepartitionistotallyisolatedandOrientDBthinksthevertexdoesn'texistwhileit'spresent,butinvisibletothecurrentuser.
403
GraphAPI
TinkerPopStack
RecordLevelSecurityfeatureisverypowerfulbecauseactsatlowlevelinsidetheOrientDBengine.Thisiswhyeverythingworkslike
acharm,eventheTinkerPopstack.
NowtrytodisplayalltheverticesandedgesusingGremlin:
gremling.V
[v[#9:2],v[#9:3]]
Scriptexecutedin0,448000sec(s).
gremling.E
e[#10:1][#9:2-drive->#9:3]
Scriptexecutedin0,123000sec(s).
Thesameisusingothertechnologiesthatusethe!TinkerPopBlueprints:TinkerPopRexter,TinkerPopPipes,TinkerPopFurnace,
TinkerPopFramesandThinkAureliusFaunus.
404
GraphAPI
GraphDatabaseComparison
ThisisacomparisonpagebetweenGraphDBprojects.ToknowmoreaboutthecomparisonofDocumentDBslookatthiscomparison.
Wewanttokeepitalwaysupdatedwiththenewproductsandmorefeaturesinthematrix.Ifanyinformationaboutanyproductisnot
updatedorwrong,pleasechangeitifyou'vethepermissionsorsendanemailtoanycontributorswiththelinkofthesourceoftheright
information.
Featurematrix
Feature
OrientDB
Neo4j
DEX
InfiniteGraph
Release
1.0-SNAPSHOT
1.7M 03
4.5.1
2.1
Product
WebSite
http://www.orientdb.org
http://www.neo4j.org
http://www.sparsitytechnologies.com
http://objectivity.com/INFINITEGRAPH
License
OpenSourceApache2
OpenSourceGPL,
OpenSourceAGPL
andCommercial
Commercial
Commercial
Query
languages
ExtendedSQL,Gremlin
CypherGremlin
Notavailable,only
viaAPI
Gremlin,JavaAPI
Transaction
support
ACID
ACID
ACID
Protocols
EmbeddedviaJavaAPI,
remoteasBinaryand
REST
EmbeddedviaJava
APIandremotevia
REST
?
Replication
M ulti-M aster
M aster-Slave
No
Custom
types
Supports
customtypesand
polymorphism
EmbeddedviaJavaAPI,Remotedatabase
accessviaTCP
Supportscustomtypesand
polymorphism
Selfloops
Blueprintssupport
TheproductsbelowallsupporttheTinkerPopBlueprintsAPIatdifferentlevelofcompliance.Belowthesupportedones.Asyoucan
seeOrientDBisthemostcompliantimplementationofTinkerPopBlueprints!
405
GraphAPI
Feature
OrientDB
Neo4j
DEX
Release
1.0-SNAPSHOT
1.7M 03
4.5.1
2.1
ProductWebSite
http://www.orientdb.org
http://www.neo4j.org
http://www.sparsitytechnologies.com
http://objectivity.com/INFINI
Implementationdetails
OrientDBimpl
Neo4jimpl
DEXimpl
InfiniteGraphimpl
allowsDuplicateEdges
?
allowsSelfLoops
?
isPersistent
?
supportsVertexIteration
?
supportsEdgeIteration
?
supportsVertexIndex
?
supportsEdgeIndex
?
ignoresSuppliedIds
?
supportsTransactions
?
allowSerializableObjectProperty
?
allowBooleanProperty
?
allowDoubleProperty
?
allowFloatProperty
?
allowIntegerProperty
?
allowPrimitiveArrayProperty
?
allowUniformListProperty
?
allowM ixedListProperty
?
allowLongProperty
?
allowM apProperty
?
allowStringProperty
?
406
GraphAPI
Microbenchmark
ThetablebelowreportsthetimetocompletetheBlueprintsTestSuite.ThisisnotabenchmarkbetweenGraphDBsand
unfortunatelydoesn'texistapublicbenchmarksharedbyallthevendors:-(
Sothistableisjusttogiveanideaabouttheperformanceofeachimplementationineverysinglemoduleitsupports.Thesupportis
basedonthecompliancelevelreportedinthetableabove.Forthetestdefaultsettingswereused.Torunthesetestsonyourown
machinefollowthesesimpleinstructions.
Lowermeansfaster.Inboldthefastestimplementationforeachmodule.
Module
OrientDB
Neo4j
DEX
InfiniteGraph
Release
1.4
1.9.M 05
4.8.0
2.1
ProductWebSite
http://www.orientdb.org
http://www.neo4j.org
http://www.sparsitytechnologies.com
http://objectivity.com/INFINITE
VertexTestSuite
1,524.06
1,595.27
4,488.28
?
EdgeTestSuite
1,252.21
1,253.73
3,865.85
?
GraphTestSuite
1,664.75
2,400.34
4,680.80
?
QueryTestSuite
306.58
188.52
612.73
?
IndexableGraphTestSuite
4,620.61
11,299.02
1070.75
?
IndexTestSuite
2,072.23
5,239.92
notsupported
?
TransactionalGraphTestSuite
1,573.93
3,579.50
notsupported
?
KeyIndexableGraphTestSuite
571.42
845.84
notsupported
?
GM LReaderTestSuite
778.08
682.83
notsupported
?
GraphM LReaderTestSuite
814.38
864.70
2,316.79
?
GraphSONReaderTestSuite
424.77
480.81
1223.24
?
AllthetestsareexecutedagainstthesameHW/SWconfiguration:MacBookPro(Retina)2013-16GBRam-MacOSX12.3.0-SDD
7200rpm.SimilarresultsexecutedonLinuxCentOS.
Runthetests
ToruntheBlueprintsTestSuiteyouneedjava6+,ApacheM avenandGit.Followthesesimplesteps:
1.
>gitclonegit://github.com/tinkerpop/blueprints.git
2.
>mvncleaninstall
407
GraphAPI
LightweightEdges
OrientDBsupportsLightweightEdgesasregularedges,butwithoutanidentityondatabase.Lightweightedgescanbeusedonlywhen
nopropertiesaredefinedonedge.
ByavoidingthecreationoftheunderlyingDocument,LightweightEdgeshavethesameimpactonspeedandspaceaswithDocument
LINKs,butwiththeadditionalbonustohavebidirectionalconnections.ThismeansyoucanusetheM OVEVERTEXcommandto
refactoryourgraphwithnobrokenLINKs.
RegularEdgerepresentation
Lookatthefigurebelow.WithRegularEdgesbothvertices(#10:33and#10:12)areconnectedthroughanEdgeDocument(#17:11).The
outgoing out_Friendpropertyin#10:33documentisasetofLINKswith#17:11asitem.Instead,indocument#10:12therelationship
isasincoming,sotheproperty in_FriendisusedwiththeLINKtothesameEdge#17:11.
Whenyoucrossthisrelationship,OrientDBloadstheEdgedocument#17:11toresolvetheotherpartoftherelationship.
+---------------------++---------------------++---------------------+
|AccountVertex||FriendEdge||AccountVertex|
|#10:33||#17:11||#10:12|
+---------------------++---------------------++---------------------+
|out_Friend:[#17:11]|<-->|out:[#10:33]|||
+---------------------+|in:[#10:12]|<-->|in_Friend:[#17:11]|
+---------------------++---------------------+
LightweightEdgerepresentation
WithLightweightEdge,instead,thereisnoEdgedocument,butbothvertices(#10:33and#10:12)areconnecteddirectlytoeachother.
Theoutgoing out_Friendpropertyin#10:33documentcontainsthedirectLINKtothevertex#10:12.ThesamehappensonVertex
document#10:12,wheretherelationshipisasincomingandtheproperty in_FriendcontainsthedirectLINKtovertex#10:33.
Whenyoucrossthisrelationship,OrientDBdoesn'tneedtoloadanyedgetoresolvetheotherpartoftherelationship.Furthermoreno
edgedocumentiscreated.
+---------------------++---------------------+
|AccountVertex||AccountVertex|
|#10:33||#10:12|
+---------------------++---------------------+
|out_Friend:[#10:12]|<-->|in_Friend:[#10:33]|
+---------------------++---------------------+
StartingfromOrientDBv2.0,LightweightEdgesaredisabledbydefaultwithnewdatabases.Thisisbecausehavingregularedges
makeseasiertoactonedgesfromSQL.M anyissuesfrombeginneruserswereonLightweightEdges.IfyouwanttouseLightweight
Edges,enableitviaAPI:
OrientGraphg=newOrientGraph("mygraph");
g.setUseLightweightEdges(true);
OrviaSQL:
ALTERDATABASEcustomuseLightweightEdges=true
Changing useLightweightEdgessettingto true,willnottransformpreviousedges,butallnewedgescouldbeLightweightEdgesif
theymeettherequirements.
WhenuseLightweightEdges?
408
GraphAPI
ThesearethePROSandCONSofLightweightEdgesvsRegularEdges:
PROS:
fasterincreationandtraversing,becausedon'tneedanadditionaldocumenttokeeptherelationshipsbetween2vertices
CONS:
cannotstoreproperties
harderworkingwithLightweightedgesfromSQL,becausethereisnoaregulardocumentundertheedge
409
DocumentAPI
DocumentAPI
TousetheDocumentAPIincludethefollowingjarsinyourclasspath:
orientdb-core-*.jar
Ifyou'reusingtheDocumentDatabaseinterfaceconnectedtoaremoteserver(notlocal/embeddedmode)includealso:
orientdb-client-*.jar
orientdb-enterprise-*.jar
Introduction
TheOrientDocumentDBisthebaseofhigher-levelimplementationlikeObject-DatabaseandGraph-Database.TheDocument
DatabaseAPIhasthefollowingfeatures:
supportsM ultithreadsaccess
supportsTransactions
supportsQueries
supportsTraverse
veryflexible:canbeusedinschema-full,schema-lessorschema-hybridmode.
Thisisanexampletostore2linkeddocumentsinthedatabase:
//OPENTHEDATABASE
ODatabaseDocumentTxdb=newODatabaseDocumentTx("remote:localhost/petshop").open("admin","admin");
//CREATEANEWDOCUMENTANDFILLIT
ODocumentdoc=newODocument("Person");
doc.field("name","Luke");
doc.field("surname","Skywalker");
doc.field("city",newODocument("City").field("name","Rome").field("country","Italy"));
//SAVETHEDOCUMENT
doc.save();
db.close();
Thisistheveryfirstexample.Whilethecodeisprettyclearandeasytounderstandpleasenotethatwehaven'tdeclaredthetype
"Person"beforenow.WhenanODocumentinstanceissaved,thedeclaredtype"Person"willbecreatedwithoutconstraints.Todeclare
persistentclasseslookattheSchemamanagement.
Usethedatabase
Beforetoexecuteanyoperationyouneedanopeneddatabaseinstance.Youcanopenanexistentdatabaseorcreateanewone.
Databasesinstancesaren'tthreadsafe,souseonedatabaseperthread.
BeforetoopenorcreateadatabaseinstanceyouneedavalidURL.URLiswherethedatabaseisavailable.URLsayswhatkindof
databasewillbeused.Forexamplememory:meansin-memoryonlydatabase,plocal:isforembeddedonesandremote:tousearemote
databasehostedonanup&runningDBServerOrientDBServerinstance.FormoreinformationlookatDatabaseURL.
Databaseinstancesmustbeclosedoncefinishedtoreleasepreciousresources.Toassureitthemostcommonusageistoencloseallthe
databaseoperationsinsideatry/finallyblock:
410
DocumentAPI
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/temp/test");
db.open("admin","admin");
try{
//YOURCODE
}finally{
db.close();
}
Ifyouareusingaremotestorage(urlstartswith"remote:")assuretheserverisup&runningandincludetheorientdb-client.jarfile
inyourclasspath.
Multi-threading
TheODatabaseDocumentTxclassisnonthread-safe.ForthisreasonusedifferentODatabaseDocumentTxinstancesbymultiple
threads.TheywillsharethesameStorageinstance(withthesameURL)andthesamelevel-2cache.FormoreinformationlookatM ultiThreadingwithJava.
Createanewdatabase
Inlocalfilesystem
ODatabaseDocumentTxdb=newODatabaseDocumentTx("plocal:/tmp/databases/petshop").create();
Onaremoteserver
Tocreateadatabaseinaremoteserveryouneedtheuser/passwordoftheremoteOrientDBServerinstance.Bydefaultthe"root"user
iscreatedonfirststartupoftheserver.Checkthisinthefileconfig/orientdb-server-config.xml,whereyouwillalsofindthepassword.
Tocreateanewdocumentdatabasecalleddbnameondbhostusingfilesystemstorage(asopposedtoin-memorystorage):
newOServerAdmin("remote:dbhost")
.connect("root","kjhsdjfsdh128438ejhj")
.createDatabase("dbname","document","local").close();
Tocreateagraphdatabasereplace"document"with"graph".
Tostorethedatabaseinmemoryreplace"local"with"memory".
Openadatabase
ODatabaseDocumentTxdb=newODatabaseDocumentTx("remote:localhost/petshop").open("admin","admin");
Thedatabaseinstancewillsharetheconnectionversusthestorage.ifit'sa"local"storage,thenallthedatabaseinstanceswillbe
synchronizedonit.Ifit'sa"remote"storagethenthenetworkconnectionwillbesharedamongallthedatabaseinstances.
UsetheconnectionPool
Oneofmostcommonusecasesistoreusethedatabase,avoidingtocreateiteverytime.It'salsothetypicalscenariooftheWeb
applications.InsteadofcreatinganewODatabaseDocumentTxinstanceallthetimes,getanavailableinstancefromthepool:
411
DocumentAPI
//OPENTHEDATABASE
ODatabaseDocumentTxdb=ODatabaseDocumentPool.global().acquire("remote:localhost/petshop","admin","admin");
try{
//YOURCODE
...
}finally{
db.close();
}
Remembertoalwaysclosethedatabaseinstanceusingthe close()databasemethodlikeaclassicnon-pooleddatabase.Inthiscasethe
databasewillbenotclosedforreal,buttheinstancewillbereleasedtothepool,readytobereusedbyfuturerequests.Thebestistouse
atry/finallyblocktoavoidcaseswherethedatabaseinstanceremainsopen,justliketheexampleabove.
Globalpool
BydefaultOrientDBprovideaglobalpooldeclaredwithmaximum20instances.Useitwith: ODatabaseDocumentPool.global().
Useyourpool
Tocreateyourownpoolbuilditandcallthe setup(min,max)methodtodefineminimumandmaximummanagedinstances.Remember
tocloseitwhenthepoolisnotmoreused.Example:
//CREATEANEWPOOLWITH1-10INSTANCES
ODatabaseDocumentPoolpool=newODatabaseDocumentPool();
pool.setup(1,10);
...
pool.close();
Schema
OrientDBcanworkinschema-full(likeRDBM S),schema-less(likemanyNoSQLDocumentdatabases)andinschema-hybridmode.
FormoreinformationabouttheSchemalookattheSchemapage.
TousetheschemawithdocumentscreatetheODocumentinstanceusingthe ODocument(StringclassName)constructorpassingthe
classname.Iftheclasshasn'tbeendeclared,it'screatedautomaticallywithnofields.Thiscan'tworkduringtransactionbecauseschema
changescan'tbeappliedintransactionalcontext.
Security
FewNoSQLsolutionssupportssecurity.OrientDBdoesit.ToknowmoreaboutitlookatSecurity.
TomanagethesecuritygettheSecurityM anageranduseittoworkwithusersandroles.Example:
OSecuritysm=db.getMetadata().getSecurity();
OUseruser=sm.createUser("god","god",newString[]{"admin"});
Togetthereferencetothecurrentuseruse:
OUseruser=db.getUser();
Createanewdocument
ODocumentinstancescanbesavedbycallingthesave()methodagainsttheobjectitself.Notethatthebehaviourdependsontherunning
transaction,ifany.SeeTransactions.
412
DocumentAPI
ODocumentanimal=newODocument("Animal");
animal.field("name","Gaudi");
animal.field("location","Madrid");
animal.save();
Retrievedocuments
Browseallthedocumentsinacluster
for(ODocumentdoc:database.browseCluster("CityCars")){
System.out.println(doc.field("model"));
Browsealltherecordsofaclass
for(ODocumentanimal:database.browseClass("Animal")){
System.out.println(animal.field("name"));
Countrecordsofaclass
longcars=database.countClass("Car");
v=Countrecordsofacluster==
longcityCars=database.countCluster("CityCar");
Executeaquery
AlthoughOrientDBispartoftheNoSQLdatabasecommunity,itsupportsasubsetofSQLthatallowsittoprocesslinkstodocuments
andgraphs.
ToknowmoreabouttheSQLsyntaxsupportedgoto:SQL-Query.
ExampleofaSQLquery:
List<ODocument>result=db.query(
newOSQLSynchQuery<ODocument>("select*fromAnimalwhereID=10andnamelike'G%'"));
Asynchronousquery
OrientDBsupportsasynchronousqueries.Theresultisnotcollectedandreturnedlikesynchronousones(seeabove)butacallbackis
calledeverytimearecordsatisfythepredicates:
413
DocumentAPI
database.command(
newOSQLAsynchQuery<ODocument>("select*fromanimalwherename='Gipsy'",
newOCommandResultListener(){
resultCount=0;
@Override
publicbooleanresult(ObjectiRecord){
resultCount++;
ODocumentdoc=(ODocument)iRecord;
//DOSOMETHINGWITHTHEDOCUMENT
returnresultCount>20?false:true;
}
@Override
publicvoidend(){
}
})).execute();
Asynchronousqueriesareusefultomanagebigresultsetsbecausedon'tallocatememorytocollectresults.
Non-Blockingquery(sincev2.1)
BothSynchronousandAsynchronousqueriesareblocking,thatmeansthatthefirstinstructionyouhaveafterdb.query()or
db.command().execute()willbeexecutedonlyafteryoureceivedalltheresult-setorlastcallbackwasinvoked.OrientDBalsosupports
non-blockingqueries.TheAPIisverysimilartoasynchronousqueries(youhaveacallbackthatisinvokedforeveryrecordinthe
result-set),butthebehavioriscompletelydifferent:theexecutionofyourcurrentthreadcontinueswithoutblockingonthedb.query()
ordb.command().execute(),andthecallbackisinvokedbyadifferentthread.Thatmeansthatinthemeantimeyoucancloseyourdb
instanceandkeeponreceivingcallbacksfromthequeryresult.
Futurefuture=database.command(newOSQLNonBlockingQuery<Object>("select*fromanimalwherename='Gipsy'",
newOCommandResultListener(){
resultCount=0;
@Override
publicbooleanresult(ObjectiRecord){
resultCount++;
ODocumentdoc=(ODocument)iRecord;
//DOSOMETHINGWITHTHEDOCUMENT
System.out.println("callback"+resultCount+"invoked");
returnresultCount>20?false:true;
}
@Override
publicvoidend(){
}
})).execute();
System.out.println("queryexecuted");
future.get();
theresultofthissnippetofcodewillbesomethinglike
queryexecuted
callback0invoked
callback1invoked
callback2invoked
callback3invoked
callback4invoked
butitcouldalsobe
414
DocumentAPI
callback0invoked
callback1invoked
queryexecuted
callback2invoked
callback3invoked
callback4invoked
dependingonraceconditionsonthetwoparallelthreads(theonethatfiresqueryexecutionandthencontinueswith"queryexecuted",
andtheotheronethatinvokescallbacks).
future.get();isablockingcallthatreturnsonlyafterlastcallbackinvocation(youcanavoidthisifyoudon'tneedtoknowwhenthe
queryterminates).
Preparedquery
PreparedqueryarequitesimilartothePreparedStatementofJDBC.Preparedqueriesarepre-parsedsoonmultipleexecutionofthe
samequeryarefasterthanclassicSQLqueries.Furthermorethepre-parsingdoesn'tallowSQLInjection.Note:preparedqueries
(parametersubstition)onlyworkswithselectstatements(butnotselectstatementswithinothertypesofqueriessuchas"create
vertex").
Preparedqueryusestwokindsofmarkerstosubstituteparametersonexecution:
?ispositionalparameter
:<par>isnamedparameter
Exampleofpositionalparameters:
OSQLSynchQuery<ODocument>query=newOSQLSynchQuery<ODocument>("selectfromProfilewherename=?andsurname=?");
List<ODocument>result=database.command(query).execute("Barack","Obama");
Exampleofnamedparameters:
OSQLSynchQuery<ODocument>query=newOSQLSynchQuery<ODocument>("selectfromProfilewherename=:nameand
surname=:surname");
Map<String,Object>params=newHashMap<String,Object>();
params.put("name","Barack");
params.put("surname","Obama");
List<ODocument>result=database.command(query).execute(params);
Rightusageofthegraph
OrientDBisagraphdatabase.Thismeansthattraversingisveryefficient.Youcanusethisfeaturetooptimizequeries.Acommon
techniqueisthePivoting.
SQLCommands
ToexecuteSQLcommandsusethe command()methodpassingaOCommandSQLobject:
intrecordsUpdated=db.command(
newOCommandSQL("updateAnimalsetsold=false")).execute();
Ifthecommandmodifiestheschema(like create/alter/dropclassand create/alter/droppropertycommands),remembertoforce
updatingoftheschemaofthedatabaseinstanceyou'reusing:
db.getMetadata().getSchema().reload();
FormoreinformationlookattheavailableSQLcommands.
415
DocumentAPI
Traverserecords
Traversingistheoperationtocrossdocumentsbylinks(relationships).OrientDBisagraphdatabasesothisoperationismuchmuch
moreefficientthanexecutingaJOINintherelationaldatabases.ToknowmoreabouttraversinglookattheJavatraverseAPI.
Theexamplebelowtraverses,foreachmovie,alltheconnectedrecordsuptothe5thdepthlevel.
for(OIdentifiableid:newOTraverse()
.field("in").field("out")
.target(database.browseClass("Movie").iterator())
.predicate(newOCommandPredicate(){
publicbooleanevaluate(ORecord<?>iRecord,OCommandContextiContext){
return((Integer)iContext.getVariable("depth"))<=5;
}
})){
System.out.println(id);
}
Updateadocument
AnypersistentdocumentcanbeupdatedbyusingtheJavaAPIandthenbycallingthedb.save()method.Alternatively,youcancallthe
document'ssave()methodtosynchronizethechangestothedatabase.Thebehaviourdependsonthetransactionbegun,ifany.See
Transactions.
animal.field("location","Nairobi");
animal.save();
OrientDBwillupdateonlythefieldsreallychanged.
Exampleofhowtoincreasethepriceofalltheanimalsby5%:
for(ODocumentanimal:database.browseClass("Animal")){
animal.field("price",animal.field("price")*105/100);
animal.save();
}
Deleteadocument
Todeleteadocumentcallthedelete()methodonthedocumentinstancethat'sloaded.Thebehaviourdependsonthetransactionbegun,
ifany.SeeTransactions.
animal.delete();
Exampleofdeletionofallthedocumentsofclass"Animal".
for(ODocumentanimal:database.browseClass("Animal"))
animal.delete();
Transactions
Transactionsareapracticalwaytogroupasetofoperationstogether.OrientDBsupportsACIDtransactionssothatallornoneofthe
operationssucceed.Thedatabasealwaysremainsconsistent.FormoreinformationlookatTransactions.
Transactionsaremanagedatthedatabaselevel.Nestedtransactionsarecurrentlynotsupported.Adatabaseinstancecanonlyhaveone
transactionrunning.Thedatabase'smethodstohandletransactionsare:
416
DocumentAPI
begin()tostartanewtransaction.Ifatransactionwasalreadyrunning,it'srolledbackandanewoneisbegun.
commit()makeschangespersistent.IfanerroroccursduringcommitthetransactionisrolledbackandanOTransactionException
exceptionisraised.
rollback()abortsatransaction.Allthechangeswillbelost.
Optimisticapproach
ThecurrentreleaseofOrientDBonlysupportsOPTIM ISTICtransactionswherenolockiskeptandalloperationsarecheckedat
committime.Thisimprovesconcurrencybutcanthrowan OConcurrentModificationExceptionexceptioninthecasewhererecordsare
modifiedbyconcurrentclientsorthreads.Inthisscenario,theclientcodecanreloadtheupdatedrecordsandrepeatthetransaction.
Optimistictransactionskeepallthechangesinmemoryintheclient.Ifyou'reusingremotestoragenochangesaresenttotheserver
until commit()iscalled.Allthechangeswillbetransferredinablock.Thisreducesnetworklatency,speeds-uptheexecution,and
increasesconcurrency.ThisisabigdifferencecomparedtomostRelationalDBM Swhere,duringatransaction,changesaresent
immediatelytotheserver.
Usage
Transactionsarecommittedonlywhenthe commit()methodiscalledandnoerrorsoccur.Themostcommonusageoftransactionsis
toencloseallthedatabaseoperationsinsidea try/finallyblock.Onclosingofthedatabase("finally"block)ifapendingtransactionis
runningitwillberolledbackautomatically.Lookatthisexample:
ODatabaseDocumentTxdb=newODatabaseDocumentTx(url);
db.open("admin","admin");
try{
db.begin();
//YOURCODE
db.commit();
}finally{
db.close();
}
IndexAPI
EventhoughyoucanuseIndicesviaSQL,thebestandmostefficientwayistousetheJavaAPI.
ThemainclasstousetoworkwithindicesistheIndexM anager.TogettheimplementationoftheIndexM anageruse:
OIndexManageridxManager=database.getMetadata().getIndexManager();
TheIndexM anagerallowsyoutomanagetheindexlife-cycleforcreating,deleting,andretrievinganindexinstance.Themostcommon
usageiswithasingleindex.Youcangetthereferencetoanindexbyusing:
OIndex<?>idx=database.getMetadata().getIndexManager().getIndex("Profile.name");
Where"Profile.name"istheindexname.NotethatbydefaultOrientDBassignsthenameas <class>.<property>forautomaticindices
createdagainstaclass'sproperty.
TheOIndexinterfaceissimilartoaJavaM apandprovidesmethodstoget,put,remove,andcountitems.Thefollowingareexamplesof
retrievingrecordsusingaUNIQUEindexagainstanamefieldandaNOTUNIQUEindexagainstagenderfield:
417
DocumentAPI
OIndex<?>nameIdx=database.getMetadata().getIndexManager().getIndex("Profile.name");
//THISISAUNIQUEINDEX,SOITRETRIEVESAOIdentifiable
OIdentifiableluke=nameIdx.get("Luke");
if(luke!=null)
printRecord((ODocument)luke.getRecord());
OIndex<?>genderIdx=database.getMetadata().getIndexManager().getIndex("Profile.gender");
//THISISANOTUNIQUEINDEX,SOITRETRIEVESASet<OIdentifiable>
Set<OIdentifiable>males=genderIdx.get("male");
for(OIdentifiablemale:males)
printRecord((ODocument)male.getRecord());
WhileautomaticindicesaremanagedautomaticallybyOrientDBhooks,themanualindicescanbeusedtostoreanyvalue.Tocreatea
newentryusethe put():
OIndex<?>addressbook=database.getMetadata().getIndexManager().getIndex("addressbook");
addressbook.put("Luke",newODocument("Contact").field("name","Luke");
Resources
Javadoc:JavaDoc
OrientDBStudioWebtool.
418
DocumentAPI
Schema
AlthoughOrientDBcanworkinschema-lessmode,sometimesyouneedtoenforceyourdatamodelusingaschema.OrientDBsupports
schema-fullorschema-hybridsolutionswherethelattermeanstosetsuchconstraintsonlyforcertainfieldsandtoleavetheusertoadd
customfieldsontherecords.Thismodeisataclasslevel,soyoucanhavean"Employee"classasschema-fullandan
"EmployeeInformation"classasschema-less.
S chema-Full:enablesthestrict-modeatclasslevelandsetsallthefieldsasmandatory.
S chema-Less:createsclasseswithnoproperties.Defaultmodeisnonstrict-modesorecordscanhavearbitraryfields.
S chema-Hybrid,alsocalledSchema-Mixedisthemostused:createsclassesanddefinesomefieldsbutallowstheusertodefine
customfields.
NOTE:Changestotheschemaarenottransactional,soexecutethemoutsideatransaction.
Toaccesstotheschema,youcanuseSQLorAPI.WillfollowexamplesusingJavaAPI.
TogainaccesstotheschemaAPIsyougettheOM etadataobjectfromdatabaseinstanceyou'reusingandthencallits getSchema()
method.
OSchemaschema=database.getMetadata().getSchema();
Class
AClassisaconcepttakenfromtheObjectOrientedparadigm.InOrientDBaclassdefinesatypeofrecord.It'stheclosestconcepttoa
relationaldatabasetable.AClasscanbeschema-less,schema-full,ormixed.
AClasscaninheritfromanotherclass.This[#Inheritance]meansthatthesub-classextendstheparentclass,inheritingallitsattributes
asiftheywereitsown.
Eachclasshasitsownclustersthatcanbelogical(bydefault)orphysical.Aclassmusthaveatleastoneclusterdefined(asitsdefault
cluster),butcansupportmultipleones.InthiscaseBydefaultOrientDBwillwritenewrecordsinthedefaultcluster,butreadswill
alwaysinvolveallthedefinedclusters.
Whenyoucreateanewclass,bydefault,anewphysicalclusteriscreatedwiththesamenameastheclass(inlowercase).
Createapersistentclass
Eachclasscontainsoneormoreproperties(alsocalledfields).ThismodeissimilartotheclassicrelationalDBM Sapproachwhereyou
definetablesbeforestoringrecords.
Here'sanexampleofcreatinganAccountclass.Bydefaultanew[Concepts#Physical_ClusterPhysicalCluster]willbecreatedtokeep
theclassinstances:
OClassaccount=database.getMetadata().getSchema().createClass("Account");
TocreateanewVertexorEdgetypeyouhavetoextendthe"V"and"E"classes,respectively.Example:
OClassperson=database.getMetadata().getSchema().createClass("Account",
database.getMetadata().getSchema().getClass("V"));
LookatGraphSchemaformoreinformation.
Getapersistentclass
Toretrieveapersistentclassusethe getClass(String)method.Iftheclassdoesnotexistthennullisreturned.
419
DocumentAPI
OClassaccount=database.getMetadata().getSchema().getClass("Account");
Dropapersistentclass
Todropapersistentclassusethe OSchema.dropClass(String)method.
database.getMetadata().getSchema().dropClass("Account");
Therecordsoftheremovedclasswillnotbedeletedunlessyouexplicitlydeletethembeforedroppingtheclass.Example:
database.command(newOCommandSQL("DELETEFROMAccount")).execute();
database.getMetadata().getSchema().dropClass("Account");
Constraints
Toworkinschema-fullmodesetthestrictmodeattheclasslevelbycallingthe setStrictMode(true)method.Inthiscase,allthe
propertiesoftherecordmustbepredefined.
Property
Propertiesarethefieldsoftheclass.Inthisguideapropertyissynonymouswithafield.
CreatetheClassproperty
Oncetheclasshasbeencreated,youcandefinefields(properties).Belowisanexample:
OClassaccount=database.getMetadata().getSchema().createClass("Account");
account.createProperty("id",OType.INTEGER);
account.createProperty("birthDate",OType.DATE);
PleasenotethateachfieldmustbelongtooneoftheseTypes.
DroptheClassproperty
Todropapersistentclasspropertyusethe OClass.dropProperty(String)method.
database.getMetadata().getSchema().getClass("Account").dropProperty("name");
Thedroppedpropertywillnotberemovedfromrecordsunlessyouexplicitlydeletethemusingthe[SQLUpdateSQLUPDATE+
REM OVEstatement].Example:
database.getMetadata().getSchema().getClass("Account").dropProperty("name");
database.command(newOCommandSQL("UPDATEAccountREMOVEname")).execute();
Definerelationships
OrientDBsupportstwotypesofrelationships:referencedandembedded.
Referencedrelationships
OrientDBusesadirectlinktothereferencedrecord(s)withouttheneedofacostlyJOINasdoestherelationalworld.Example:
420
DocumentAPI
customer
RecordA------------->RecordB
CLASS=InvoiceCLASS=Customer
RID=5:23RID=10:2
RecordAwillcontainthereferencetotheRecordBinthepropertycalled"customer".Notethatbothrecordsarereachablebyanyother
recordssincetheyhavea[Concepts#RecordIDRecordID].
1-1andN-1referencedrelationships
1-1andN-1referencedrelationshipsareexpressedusingtheLINKtype.
OClasscustomer=database.getMetadata().getSchema().createClass("Customer");
customer.createProperty("name",OType.STRING);
OClassinvoice=database.getMetadata().getSchema().createClass("Invoice");
invoice.createProperty("id",OType.INTEGER);
invoice.createProperty("date",OType.DATE);
invoice.createProperty("customer",OType.LINK,customer);
Inthiscaserecordsofclass"Invoice"willlinktoarecordofclass"Customer"usingthefield"customer".
1-NandN-Mreferencedrelationships
1-NandN-M referencedrelationshipsareexpressedusingthecollectionoflinkssuchas:
LINKLIS Tasanorderedlistoflinks
LINKS ETasanunorderedsetoflinks.Itdoesn'tacceptduplicates
LINKMAPasanorderedmapoflinkswithStringkey.Itdoesn'tacceptduplicatedkeys
Exampleofa1-NrelationshipbetweentheclassesOrderandOrderItem:
OClassorderItem=db.getMetadata().getSchema().createClass("OrderItem");
orderItem.createProperty("id",OType.INTEGER);
orderItem.createProperty("animal",OType.LINK,animal);
OClassorder=db.getMetadata().getSchema().createClass("Order");
order.createProperty("id",OType.INTEGER);
order.createProperty("date",OType.DATE);
order.createProperty("items",OType.LINKLIST,orderItem);
db.getMetadata().getSchema().save();
Embeddedrelationships
Embeddedrecords,instead,arecontainedinsidetherecordthatembedsthem.It'sakindofrelationshipstrongerthanthe
[#Referenced_relationshipsreference].Theembeddedrecordwillnothaveitsown[Concepts#RecordIDRecordID]sinceitcan'tbe
directlyreferencedbyotherrecords.It'sonlyaccessibleviathecontainerrecord.Ifthecontainerrecordisdeleted,thentheembedded
recordwillbedeletedtoo.Example:
address
RecordA<>---------->RecordB
CLASS=AccountCLASS=Address
RID=5:23NORID!
RecordAwillcontaintheentireRecordBinthepropertycalled"address".RecordBcanbereachedonlybytraversingthecontainer
record.
Example:
SELECTFROMaccountWHEREaddress.city='Rome'
421
DocumentAPI
1-1andN-1embeddedrelationships
1-1andN-1embeddedrelationshipsareexpressedusingtheEMBEDDEDtype.
OClassaddress=database.getMetadata().getSchema().createClass("Address");
OClassaccount=database.getMetadata().getSchema().createClass("Account");
account.createProperty("id",OType.INTEGER);
account.createProperty("birthDate",OType.DATE);
account.createProperty("address",OType.EMBEDDED,address);
Inthiscase,recordsofclass"Account"willembedarecordofclass"Address".
1-NandN-Membeddedrelationships
1-NandN-M embeddedrelationshipsareexpressedusingthecollectionoflinkssuchas:
EMBEDDEDLIS T,asanorderedlistofrecords.
EMBEDDEDS ET,asanunorderedsetofrecords.Itdoesn'tacceptsduplicates.
EMBEDDEDMAP,asanorderedmapwithrecordsasthevalueandStringasthekey.Itdoesn'tacceptduplicatekeys.
Exampleofa1-NrelationshipbetweentheclassOrderandOrderItem:
OClassorderItem=db.getMetadata().getSchema().createClass("OrderItem");
orderItem.createProperty("id",OType.INTEGER);
orderItem.createProperty("animal",OType.LINK,animal);
OClassorder=db.getMetadata().getSchema().createClass("Order");
order.createProperty("id",OType.INTEGER);
order.createProperty("date",OType.DATE);
order.createProperty("items",OType.EMBEDDEDLIST,orderItem);
Constraints
OrientDBsupportsanumberofconstraintsforeachfield:
Minimumvalue,acceptsastringbecauseitalsoworksfordateranges setMin()
Maximumvalue,acceptsastringbecauseitalsoworksfordateranges setMax()
Mandatory,mustbespecified setMandatory()
Readonly,maynotbeupdatedafterrecordiscreated setReadonly()
NotNull,cannotbeNULL setNotNull()
Unique,doesn'tallowduplicatesandspeedsupsearches.
Regexp,mustsatisfytheRegularexpression.
Example:
profile.createProperty("nick",OType.STRING).setMin("3").setMax("30").setMandatory(true).setNotNull(true);
profile.createIndex("nickIdx",OClass.INDEX_TYPE.UNIQUE,"nick");//Createsuniqueconstraint
profile.createProperty("name",OType.STRING).setMin("3").setMax("30");
profile.createProperty("surname",OType.STRING).setMin("3").setMax("30");
profile.createProperty("registeredOn",OType.DATE).setMin("2010-01-0100:00:00");
profile.createProperty("lastAccessOn",OType.DATE).setMin("2010-01-0100:00:00");
Indexesasconstraints
ToensurethatapropertyvalueisUNIQUEusetheUNIQUEindexasaconstraint:
profile.createIndex("EmployeeId",OClass.INDEX_TYPE.UNIQUE,"id");
422
DocumentAPI
ToensurethatagroupofpropertiesisUNIQUEcreateacompositeindexmadeofmultiplefields:Exampleofcreatingacomposite
index:
profile.createIndex("compositeIdx",OClass.INDEX_TYPE.NOTUNIQUE,"name","surname");
FormoreinformationaboutindexeslookatIndexes.
423
DocumentAPI
WorkingwithFields
OrientDBhasapowerfulwaytoextractpartsofaDocumentfield.ThisappliestotheJavaAPI,SQLWhereconditions,andSQL
projections.
Toextractpartsyouhavetousethesquarebrackets.
Extractpunctualitems
Singleitem
Example:tagsisanEM BEDDEDSETofStringscontainingthevalues['Smart','Geek','Cool'].
Theexpressiontags[0]willreturn'Smart'.
Singleitems
Insidesquarebracketsputtheitemsseparatedbycomma",".
Followingthetagsexampleabove,theexpressiontags[0,2]willreturnalistwith[Smart,'Cool'].
Rangeitems
Insidesquarebracketsputthelowerandupperboundsofanitem,separatedby"-".
Followingthetagsexampleabove,theexpressiontags[1-2]returns['Geek','Cool'].
UsageinSQLquery
Example:
SELECT*FROMprofileWHEREphones['home']LIKE'+39%'
Worksthesamewithdoublequotes.
Youcangoinachain(contactsisamapofmap):
SELECT*FROMprofileWHEREcontacts[phones][home]LIKE'+39%'
Withlistsandarraysyoucanpickanitemelementfromarange:
SELECT*FROMprofileWHEREtags[0]='smart'
andsingleitems:
SELECT*FROMprofileWHEREtags[0,3,5]CONTAINSALL['smart','new','crazy']
andarangeofitems:
SELECT*FROMprofileWHEREtags[0-5]CONTAINSALL['smart','new','crazy']
Condition
Insidethesquarebracketsyoucanspecifyacondition.Todayonlytheequalsconditionissupported.
Example:
424
DocumentAPI
employees[label='Ferrari']
Useingraphs
Youcancrossagraphusingaprojection.Thisanexampleoftraversingalltheretrievednodeswithname"Tom"."out"isoutEdgesand
it'sacollection.Previously,acollectioncouldn'tbetraversedwiththe.notation.Example:
SELECTout.inFROMvWHEREname='Tom'
ThisretrievesalltheverticesconnectedtotheoutgoingedgesfromtheVertexwithname='Tom'.
Acollectioncanbefilteredwiththeequalsoperator.Thisanexampleoftraversingalltheretrievednodeswithname"Tom".The
traversalcrossestheoutedgesbutonlywherethelinked(in)Vertexhasthelabel"Ferrari"andthenforwardtothe:
SELECTout[in.label='Ferrari']FROMvWHEREname='Tom'
Orselectingvertexnodesbasedonclass:
SELECTout[in.@class='Car']FROMvWHEREname='Tom'
Orboth:
SELECTout[label='drives'][in.@class='Car']FROMvWHEREname='Tom'
Asyoucanseewherebrackets([])followbrackets,theresultsetisfilteredineachsteplikeaPipeline.
NOTE:Thisdoesn'treplacethesupportofGREM LIN.GREM LINismuchmorepowerfulbecauseitdoesthousandsofthingsmore,
butit'sasimpleand,atthesametime,powerfultooltotraverserelationships.
Futuredirections
InthefutureyouwillbeabletousethefullexpressionoftheOrientDBSQLlanguageinsidethesquarebrackets[],like:
SELECTout[in.label.trim()='Ferrari'ANDin.@class='Vehicle']FROMvWHEREname='Tom'
Butforthisyouhavetowaityet:-)M onitortheissue:https://github.com/nuvolabase/orientdb/issues/513
425
DocumentAPI
DocumentDatabaseComparison
ThisisacomparisonpagebetweenOrientDBandotherDocumentDBprojects.ToknowmoreaboutthecomparisonofOrientDB
againstGraphDBslookatthiscomparison.
NOTE:Ifanyinformationaboutanyproductisoutdatedorwrong,pleasesendanemailtothecommitterswiththelinkofthe
sourceoftherightinformation.Thanks!
Featuresmatrix
Feature
OrientDB
MongoDB
CouchDB
WebSite
http://www.orientdb.org
http://www.mongodb.org
http://www.couchdb.org
Supportedmodels
DocumentandGraph
Document
Document
Transactions
Yes,ACID
No
Yes,ACID
Querylanguages
ExtendedSQL,Gremlin
M ongoQueryLanguage
Nonsupported,JSAPI
426
ObjectAPI
ObjectAPI
ObjectAPIallowstoworkwithPOJOsthatbindOrientDBdocuments.ThisAPIisnotableworkontopof
Graph-API.IfyouareinterestedonusingaObject-Graphmappingframework,lookattheavailableones
thatworkontopofGraph-APIlayer:Object-GraphMapping.
Requirements
TousetheObjectAPiincludethefollowingjarsinyourclasspath:
orientdb-core-*.jar
orientdb-object-*.jar
Ifyou'reusingtheObjectDatabaseinterfaceconnectedtoaremoteserver(notlocal/embeddedmode)includealso:
orientdb-client-*.jar
orientdb-enterprise-*.jar
Introduction
TheOrientDBObjectInterfaceworksontopoftheDocument-DatabaseandworkslikeanObjectDatabase:managesJavaobjects
directly.ItusestheJavaReflectiontoregistertheclassesandJavassisttooltomanagetheObject-to-Documentconversion.Please
considerthattheJavaReflectioninmodernJavaVirtualM achinesisreallyfastandthediscoveringofJavametadataismadeonlyat
firsttime.
Futureimplementationcouldusealsothebyte-codeenhancementtechniquesinaddition.
TheproxiedobjectshaveaODocumentboundedtothemandtransparentlyreplicateobjectmodifications.Italsoallowslazyloadingof
thefields:theywon'tbeloadedfromthedocumentuntilthefirstaccess.TodosotheobjectM USTimplementgettersandsetterssince
theJavassistProxyisboundedtothem.Incaseofobjectload,editanupdateallnonloadedfieldswon'tbelost.
ThedatabaseinstancehasanAPItogeneratenewobjectsalreadyproxied,incaseanon-proxiedinstanceispasseditwillbeserialized,
wrappedaroundaproxiedinstanceandreturned.
ReadmoreabouttheBindingbetweenJavaObjectsandRecords.
Quickexampleofusage:
427
ObjectAPI
//OPENTHEDATABASE
OObjectDatabaseTxdb=newOObjectDatabaseTx("remote:localhost/petshop").open("admin","admin");
//REGISTERTHECLASSONLYONCEAFTERTHEDBISOPEN/CREATED
db.getEntityManager().registerEntityClasses("foo.domain");
//CREATEANEWPROXIEDOBJECTANDFILLIT
Accountaccount=db.newInstance(Account.class);
account.setName("Luke");
account.setSurname("Skywalker");
Cityrome=db.newInstance(City.class,"Rome",db.newInstance(Country.class,"Italy"));
account.getAddresses().add(newAddress("Residence",rome,"PiazzaNavona,1"));
db.save(account);
//CREATEANEWOBJECTANDFILLIT
Accountaccount=newAccount();
account.setName("Luke");
account.setSurname("Skywalker");
Cityrome=newCity("Rome",newCountry("Italy"));
account.getAddresses().add(newAddress("Residence",rome,"PiazzaNavona,1"));
//SAVETHEACCOUNT:THEDATABASEWILLSERIALIZETHEOBJECTANDGIVETHEPROXIEDINSTANCE
account=db.save(account);
ConnectionPool
Oneofmostcommonusecaseistoreusethedatabaseavoidingtocreateiteverytime.It'salsothetypicalscenariooftheWeb
applications.
//OPENTHEDATABASE
OObjectDatabaseTxdb=OObjectDatabasePool.global().acquire("remote:localhost/petshop","admin","admin");
//REGISTERTHECLASSONLYONCEAFTERTHEDBISOPEN/CREATED
db.getEntityManager().registerEntityClass("org.petshop.domain");
try{
...
}finally{
db.close();
}
Theclose()methoddoesn'tclosethedatabasebutreleaseittotheownerpool.Itcouldbereusedinthefuture.
DatabaseURL
IntheexampleaboveadatabaseoftypeDatabaseObjectTransactionalhasbeencreatedusingthestorage:remote:localhost/petshop.
ThisaddressisaURL.ToknowmoreaboutdatabaseandstoragetypesgotoDatabaseURL.
Inthiscasethestorageresidesinthesamecomputeroftheclient,butwe'reusingtheremotestoragetype.Forthisreasonweneeda
OrientDBServerinstanceupandrunning.Ifwewouldopenthedatabasedirectlybypassingtheserverwehadtousethelocalstorage
typesuchas"plocal:/usr/local/database/petshop/petshop"where,inthiscase,thestoragewaslocatedinthe/usr/local/database/petshop
folderonthelocalfilesystem.
Multi-threading
TheOObjectDatabaseTxclassisnonthread-safe.ForthisreasonusedifferentOObjectDatabaseTxinstancesbymultiplethreads.They
willsharelocalcacheoncetransactionsarecommitted.
Inheritance
428
ObjectAPI
Startingfromtherelease0.9.19OrientDBsupportstheInheritance.UsingtheObjectDatabasetheinheritanceofDocumentsfully
matchestheJavainheritance.
WhenregisteringanewclassOrientwillalsogeneratethecorrectinheritanceschemaifnotalreadygenerated.
Example:
publicclassAccount{
privateStringname;
//gettersandsetters
}
publicclassCompanyextendsAccount{
privateintemployees;
//gettersandsetters
}
WhenyousaveaCompanyobject,OrientDBwillsavetheobjectasuniqueDocumentintheclusterspecifiedforCompanyclass.When
yousearchbetweenalltheAccountinstanceswith:
SELECTFROMaccount
ThesearchwillfindalltheAccountandCompanydocumentsthatsatisfythequery.
Usethedatabase
Beforetouseadatabaseyouneedtoopenorcreateit:
//CREATEANINMEMORYDATABASE
OObjectDatabaseTxdb1=newOObjectDatabaseTx("memory:petshop").create();
//OPENAREMOTEDATABASE
OObjectDatabaseTxdb2=newOObjectDatabaseTx("remote:localhost/petshop").open("admin","admin");
Thedatabaseinstancewillsharetheconnectionversusthestorage.ifit'salocalstorage,thenallthedatabaseinstanceswillbe
synchronizedonit.Ifit'saremotestoragethenthenetworkconnectionwillbesharedamongallthedatabaseinstances.
Togetthereferencetothecurrentuseruse:
OUseruser=db.getUser();
Oncefinishedremembertoclosethedatabasetofreepreciousresources.
db.close();
WorkingwithPOJO
PleasereadthePOJObindingguidecontainingalltheinformationaboutthemanagementofPOJO.
Workinschema-lessmode
TheObjectDatabasecanbeusedtotallyinschema-lessmodeaslongasthePOJObindingguiderequirementsarefollowed.Schemaless
meansthattheclassmustbecreatedbutevenwithoutproperties.Takealooktothisexample:
429
ObjectAPI
OObjectDatabaseTxdb=newOObjectDatabaseTx("remote:localhost/petshop").open("admin","admin");
db.getEntityManager().registerEntityClass(Person.class);
Personp=db.newInstance(Person.class);
p.setName("Luca");
p.setSurname("Garulli");
p.setCity(newCity("Rome","Italy"));
db.save(p);
db.close();
Thisistheveryfirstexample.Whilethecodeit'sprettyclearandeasytounderstandpleasenotethatwedidn'tdeclared"Person"
structurebeforenow.HoweverOrienthasbeenabletorecognizethenewobjectandsaveitinpersistentway.
Workinschema-fullmode
Intheschema-fullmodeyouneedtodeclaretheclassesyou'reusing.Eachclasscontainsoneormultipleproperties.Thismodeis
similartotheclassicRelationalDBM Sapproachwhereyouneedtocreatetablesbeforestoringrecords.Toworkinschema-fullmode
takealookattheSchemaAPIspage.
Createanewobject
ThebestpracticetocreateaJavaobjectistousetheOObjectDatabaseTx.newInstance()API:
publicclassPerson{
privateStringname;
privateStringsurname;
publicPerson(){
}
publicPerson(Stringname){
this.name=name;
}
publicPerson(Stringname,Stringsurname){
this.name=name;
this.surname=surname;
}
//gettersandsetters
}
OObjectDatabaseTxdb=newOObjectDatabaseTx("remote:localhost/petshop").open("admin","admin");
db.getEntityManager().registerEntityClass(Person.class);
//CREATESANEWPERSONFROMTHEEMPTYCONSTRUCTOR
Personperson=db.newInstance(Person.class);
person.setName("Antoni");
person.setSurname("Gaudi");
db.save(person);
//CREATESANEWPERSONFROMAPARAMETRIZEDCONSTRUCTOR
Personperson=db.newInstance(Person.class,"Antoni");
person.setSurname("Gaudi");
db.save(person);
//CREATESANEWPERSONFROMAPARAMETRIZEDCONSTRUCTOR
Personperson=db.newInstance(Person.class,"Antoni","Gaudi");
db.save(person);
HoweveranyJavaobjectcanbesavedbycallingthedb.save()method,ifnotcreatedwiththedatabaseAPIwillbeserializedandsaved.
Inthiscasetheuserhavetoassigntheresultofthedb.save()methodinordertogettheproxiedinstance,ifnotthedatabasewillalways
treattheobjectasanewone.Example:
430
ObjectAPI
//REGISTERTHECLASSONLYONCEAFTERTHEDBISOPEN/CREATED
db.getEntityManager().registerEntityClass(Animal.class);
Animalanimal=newAnimal();
animal.setName("Gaudi");
animal.setLocation("Madrid");
animal=db.save(animal);
Notethatthebehaviourdependsbythetransactionbegunifany.SeeTransactions.
Browsealltherecordsinacluster
for(Objecto:database.browseCluster("CityCars")){
System.out.println(((Car)o).getModel());
Browsealltherecordsofaclass
for(Animalanimal:database.browseClass(Animal.class)){
System.out.println(animal.getName());
Countrecordsofaclass
longcars=database.countClass("Car");
Countrecordsofacluster
longcityCars=database.countCluster("CityCar");
Updateanobject
AnyproxiedobjectcanbeupdatedusingtheJavalanguageandthencallingthedb.save()methodtosynchronizethechangestothe
repository.Behaviourdependsbythetransactionbegunifany.SeeTransactions.
animal.setLocation("Nairobi");
db.save(animal);
Orientwillupdateonlythefieldsreallychanged.
Exampleofhowtoupdatethepriceofalltheanimalsby5%more:
for(Animalanimal:database.browseClass(Animal.class)){
animal.setPrice(animal.getPrice()*105/100);
database.save(animal);
}
Ifthedb.save()methodiscalledwithanon-proxiedobjectthedatabasewillcreateanewdocument,evenifsaidobjectwerealready
saved
Deleteanobject
431
ObjectAPI
Todeleteanobjectcallthedb.delete()methodonaproxiedobject.Ifcalledonanon-proxiedobjectthedatabasewon'tdoanything.
Behaviouralsodependsbythetransactionbegunifany.SeeTransactions.
db.delete(animal);
Exampleofdeletionofalltheobjectsofclass"Animal".
for(Animalanimal:database.browseClass(Animal.class))
database.delete(animal);
Cascadedeleting
ObjectDatabaseusesJPAannotationstomanagecascadedeleting.Itcanbedoneexpliciting(orphanRemoval=true)orusingthe
CascadeType.Thefirstmodeworksonlywith@OneToOneand@OneToM anyannotations,theCascadeTypeworksalsowith
@M anyToM anyannotation.
Example:
publicclassJavaCascadeDeleteTestClass{
...
@OneToOne(orphanRemoval=true)
privateJavaSimpleTestClasssimpleClass;
@ManyToMany(cascade={CascadeType.REMOVE})
privateMap<String,Child>children=newHashMap<String,Child>();
@OneToMany(orphanRemoval=true)
privateList<Child>list=newArrayList<Child>();
@OneToMany(orphanRemoval=true)
privateSet<Child>set=newHashSet<Child>();
...
//GETTERSANDSETTERS
}
socalling
database.delete(testClass);
or
for(JavaCascadeDeleteTestClasstestClass:database.browseClass(JavaCascadeDeleteTestClass.class))
database.delete(testClass);
willalsodeleteJavaSimpleTestClassinstancescontainedin"simpleClass"fieldandalltheotherdocumentscontainedin"children","list"
and"test"
AttachingandDetaching
Sinceversion1.1.0theObjectDatabaseprovidesattach(Object)anddetach(Object)methodstomanuallymanageobjecttodocument
datatransfer.
Attach
Withtheattachmethodalldatacontainedintheobjectwillbecopiedintheassociateddocument,overwritingallexistinginformations.
432
ObjectAPI
Animalanimal=database.newInstance(Animal.class);
animal.name="Gaudi";
animal.location="Madrid";
database.attach(animal);
database.save(animal);
inthiswayallchangesdonewithintheobjectwithoutusingsetterswillbecopiedtothedocument.
There'salsoanattachAndSave(Object)methodsthatafterattachingdatasavestheobject.
Animalanimal=database.newInstance(Animal.class);
animal.name="Gaudi";
animal.location="Madrid";
database.attachAndSave(animal);
Thiswilldothesameastheexamplebefore
Detach
Withthedetachmethodalldatacontainedinthedocumentwillbecopiedintheassociatedobject,overwritingallexistinginformations.
Thedetach(Object)methodreturnsaproxiedobject,ifthere'saneedtogetanonproxieddetachedinstancethedetach(Object,boolean)
canbeused.
Animalanimal=database.load(rid);
database.detach(animal);
thiswillcopyalltheloadeddocumentinformationintheobject,withoutneedingtocallallgetters.Thismethodsreturnsaproxied
instance
Animalanimal=database.load(rid);
animal=database.detach(animal,true);
thisexampledoesthesameasbeforebutinthiscasethedetachwillreturnanonproxiedinstance.
Sinceversion1.2there'salsothedetachAll(Object,boolean)methodthatdetachesrecursivelytheentireobjecttree.Thismaythrowa
StackOverflowErrorwithbigtrees.Toavoiditincreasethestacksizewith-Xssjavaoption.Thebooleanparameterworksthesameas
withthedetach()method.
Animalanimal=database.load(rid);
animal=database.detachAll(animal,true);
LazydetachAll
(Since2.2)
WhencallingdetachAll(object,true)onalargeobjecttree,thecallmaybecomeslow,especiallywhenworkingwithremoteconnections.
Itwillrecursethrougheverylinkinthetreeandloadalldependencies.
Toonlyloadpartsoftheobjecttree,youcanaddthe@OneToOne(fetch=FetchType.LAZY)annotationlikeso:
433
ObjectAPI
publicclassLazyParent{
@Id
privateStringid;
@OneToOne(fetch=FetchType.LAZY)
privateLazyChildchild;
...
publicclassLazyChild{
@Id
privateORIDid;
privateStringname;
publicORIDgetId(){
returnid;
}
publicvoidsetId(ORIDid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
}
Intheaboveexample,whencallingdetachAll(lazyParent,true),thechildvariable(ifalinkisavailable)willcontainanormalLazyChild
object,butonlywiththeidloaded.Sothenamepropertywillbenull,aswillanyotherpropertythatisaddedtotheclass.Theidobject
canbeusedtoloadtheLazyChildobjectinalaterstage.
Executeaquery
AlthoughOrientDBispartofNoSQLdatabases,supportstheSQLengine,oratleastasubsetofitwithsuchextensionstoworkwith
objectsandgraphs.
ToknowmoreabouttheSQLsyntaxsupportedgoto:SQL-Query.
Example:
List<Animal>result=db.query(
newOSQLSynchQuery<Animal>("select*fromAnimalwhereID=10andnamelike'G%'"));
Rightusageofthegraph
OrientDBisagraphdatabase.Thismeansthattraversingisveryefficient.Youcanusethisfeaturetooptimizequeries.Acommon
techniqueisthePivoting.
SQLCommands
ToexecuteSQLcommandsusethe command()methodpassingaOCommandSQLobject:
intrecordsUpdated=db.command(
newOCommandSQL("UPDATEAnimalSETsold=false")).execute();
SeealltheSQLCommands.
GettheODocumentfromaPOJO
434
ObjectAPI
TheOObjectDatabaseTximplementationhasAPIstogetadocumentfromitsreferencingobject:
ODocumentdoc=db.getRecordByUserObject(animal);
Incaseofnon-proxiedobjectsthedocumentwillbeanewgeneratedonewithallobjectfieldserializedinit.
GetthePOJOfromaRecord
TheObjectDatabasecanalsocreateanObjectfromarecord.
Objectpojo=db.getUserObjectByRecord(record);
SchemaGeneration
Sinceversion1.5theObjectDatabasemanagesautomaticS chemagenerationbasedonregisteredentities.Thisoperationcanbe
manual
automatic
TheObjectDatabasewillgenerateclasspropertiesbasedonfieldsdeclarationifnotcreatedyet.
Changesinclassfields(asfortypechangingorrenaming)typeswon'tbeupdated,thisoperationhastobedonemanually
ManualSchemaGeneration
Schemacanbegeneratedmanuallyforsingleclassesorentirepackages:
Version1.6
db.getMetadata().getSchema().generateSchema(Foo.class);//GeneratestheschemaforFooclass
db.getMetadata().getSchema().generateSchema("com.mycompany.myapp.mydomainpackage");//Generatestheschemaforallclassesc
ontainedinthegivenpackage
Version1.5
db.generateSchema(Foo.class);//GeneratestheschemaforFooclass
db.generateSchema("com.mycompany.myapp.mydomainpackage");//Generatestheschemaforallclassescontainedinthegivenpacka
ge
AutomaticSchemaGeneration
Bysettingthe"automaticSchemaGeneration"propertytotruetheschemawillbegeneratedautomaticallyoneveryclassdeclaration.
db.setAutomaticSchemaGeneration(true);
db.getEntityManager().registerClass(Foo.class);//GeneratestheschemaforFooclassafterregistering.
db.getEntityManager().registerEntityClasses("com.mycompany.myapp.mydomainpackage");//Generatestheschemaforallclassesco
ntainedinthegivenpackageafterregistering.
classFoocouldlooklike,generatingonefieldwithanIntegerandignoringtheStringfield.
publicclassFoo{
privatetransientStringfield1;//ignorethisfield
privateIntegerfield2;//createaInteger
}
Standardschemamanagementequivalent
HavingtheFooclassdefinedasfollowing
435
ObjectAPI
publicclassFoo{
privateStringtext;
privateChildreference;
privateintnumber;
//gettersandsetters
}
schemagenerationwillcreate"text","reference"and"number"propertiesasrespectivelySTRING,LINKandINTEGERtypes.
ThedefaultschemamanagementAPIequivalentwouldbe
OClassfoo=db.getMetadata().getSchema().getClass(Foo.class);
OClasschild=db.getMetadata().getSchema().getClass(Child.class)
foo.createProperty("text",OType.STRING);
foo.createProperty("number",OType.INTEGER);
foo.createProperty("text",OType.LINK,child);
db.getMetadata().getSchema().save();
Schemasynchronizing
Sinceversion1.6there'sanAPItosynchronizeschemaofallregisteredentities.
db.getMetadata().getSchema().synchronizeSchema();
BycallingthisAPItheObjectDatabasewillcheckallregisteredentitiesandgeneratetheschemaifnotgeneratedyet.Thismanagement
isusefulonmulti-databaseenviroments
OldImplementationODatabaseObjectTx
Untiltherelease1.0rc9theObjectDatabasewasimplementedastheclass com.orientechnologies.orient.db.object.ODatabaseObjectTx.
Thisclassisdeprecated,butifyouwanttocontinuetouseitchangethepackageto: com.orientechnologies.orient.object.db.
Introduction
ThisimplementationanddocumentationreferstoallODatabaseObjectXXXdeprecatedclasses.
TheOrientObjectDBworksontopoftheDocument-Databaseandit'sabletotreatJavaobjectswithouttheuseofpre-processor,byte
enhancerorProxyclasses.Itusesthesimplerway:theJavaReflection.PleaseconsiderthattheJavareflectioninmodernJavaVirtual
M achinesisreallyfastandthediscoveringofJavametadataismadeatfirsttime.Futureimplementationcouldusethebyte-code
enhancementtechniquesinaddition.
ReadmoreabouttheBindingbetweenJavaObjectsandRecords.
Quickexampleofusage:
//OPENTHEDATABASE
ODatabaseObjectTxdb=newODatabaseObjectTx("remote:localhost/petshop").open("admin","admin");
db.getEntityManager().registerEntityClasses("foo.domain");
//CREATEANEWACCOUNTOBJECTANDFILLIT
Accountaccount=newAccount()
account.setName("Luke");
account.setSurname("Skywalker");
Cityrome=newCity("Rome",newCountry("Italy"));
account.getAddresses().add(newAddress("Residence",rome,"PiazzaNavona,1"));
db.save(account);
436
ObjectAPI
ConnectionPool
Oneofmostcommonusecaseistoreusethedatabaseavoidingtocreateiteverytime.It'salsothetypicalscenariooftheWeb
applications.
//OPENTHEDATABASE
ODatabaseObjectTxdb=ODatabaseObjectPool.global().acquire("remote:localhost/petshop","admin","admin");
...
db.close();
Theclose()methoddoesn'tclosethedatabasebutreleaseittotheownerpool.Itcouldbereusedinthefuture.
Inheritance
Startingfromtherelease0.9.19OrientDBsupportstheInheritance.UsingtheObjectDatabasetheinheritanceofDocumentsfully
matchestheJavainheritance.
Example:
publicclassAccount{
privateStringname;
}
publicclassCompanyextendsAccount{
privateintemployees;
}
WhenyousaveaCompanyobject,OrientDBwillsavetheobjectasuniqueDocumentintheclusterspecifiedforCompanyclass.When
yousearchbetweenalltheAccountinstanceswith:
SELECTFROMaccount
ThesearchwillfindalltheAccountandCompanydocumentsthatsatisfythequery.
437
ObjectAPI
ObjectBinding
TheObjectDatabaseimplementationmakesthingseasierfortheJavadevelopersincethebindingbetweenObjectstoRecordsis
transparent.
Howitworks?
OrientDBusesJavareflectionandJavassistProxytoboundPOJOstoRecordsdirectly.Thoseproxiedinstancestakecareaboutthe
synchronizationbetweenthePOJOandtheunderlyingrecord.EverytimeyouinvokeasettermethodagainstthePOJO,thevalueis
earlyboundintotherecord.EverytimeyoucallagettermethodthevalueisretrievedfromtherecordifthePOJO'sfieldvalueisnull.
Lazyloadingworksinthiswaytoo.
SotheObjectDatabaseclassworksaswrapperoftheunderlyingDocument-Database.
NOTE:Incaseanon-proxiedobjectisfounditwillbeserialized,proxiedandboundedtoacorrespondingRecord.
Requirements
Declarepersistentclasses
BeforetousepersistentPOJOsOrientDBneedstoknowwhichclassesarepersistent(betweenthousandsinyourclasspath)by
registeringthepersistentpackagesand/orclasses.Example:
database.getEntityManager().registerEntityClasses("com.orientechnologies.orient.test.domain");
Thismustbedoneonlyrightafterthedatabaseiscreatedoropened.
Namingconventions
OrientDBfollowssomenamingconventionstoavoidwritingtonsofconfigurationfilesbutjustapplyingtherule"Conventionover
Configuration".Belowthoseused:
1. JavaclasseswillbeboundtopersistentclassesdefinedintheOrientDBschemawiththesamename.InOrientDBclassnamesare
caseinsensitive.TheJavaclassnameistakenwithoutthefullpackage.Forexampleregisteringtheclass Accountinthepackage
com.orientechnologies.demo,theexpectedpersistentclasswillbe"Account"andnottheentire
com.orientechnologies.demo.Account.Thismeansthatclassnames,inthedatabase,arealwaysuniqueandcan'texisttwoclass
withthesamenameevenifdeclaredindifferentpackages.
2. Javaclass'sattributeswillbeboundtothefieldswiththesamenameinthepersistentclasses.Fieldnamesarecasesensitive.
Emptyconstructor
AlltheJavaclassesmusthaveanemptyconstructortolettoOrientDBtocreateinstances.
GettersandSetters
AllyourclassesmusthavegettersandsettersofeveryfieldthatneedstobepersistentinordertolettoOrientDBtomanageproxy
operations.GettersandSettersalsoneedtobenamedsameasthedeclaringfield:Example:
438
ObjectAPI
publicclassTest{
privateStringtextField;
privateintintField;
publicStringgetTextField(){
returntextField;
}
publicvoidsetTextField(StringiTextField){
textField=iTextField;
}
//THISDECLARATIONWON'TWORK,ORIENTDBWON'TBEABLETORECOGNIZETHEREALFIELDNAME
publicintgetInt(){
returnintField;
}
//THISDECLARATIONWON'TWORK,ORIENTDBWON'TBEABLETORECOGNIZETHEREALFIELDNAME
publicvoidsetInt(intiInt){
intField=iInt;
}
}
CollectionsandMaps
ToavoidClassCastExecptionwhentheJavaclasseshaveCollectionsandM aps,theinterfacemustbeusedratherthantheJava
implementation.TheclassicmistakeistodefineinapersistentclassthetypesArrayList,HashSet,HashM apinsteadofList,Setand
M ap.
Example:
publicclassMyClass{
//CORRECT
protectedList<MyElement>correctList;
//WRONG:WILLTHROWAClassCastException
protectedArrayList<MyElement>wrongList;
//CORRECT
protectedSet<MyElement>correctSet;
//WRONG:WILLTHROWAClassCastException
protectedTreeSet<MyElement>wrongSet;
//CORRECT
protectedMap<String,MyElement>correctMap;
//WRONG:WILLTHROWAClassCastException
protectedHashMap<String,MyElement>wrongMap;
}
POJObinding
OrientDBmanagesallthePOJOattributesinpersistentwayduringread/writefrom/totherecord,exceptforthefieldsthose:
havethetransientmodifier
havethestaticmodifier,
haven'tgettersandsetters
aresetwithanonymousclasstypes.
OrientDBusestheJavareflectiontodiscoverythePOJOclasses.Thisismadeonlyonceduringtheregistrationofthedomainclasses.
Defaultbinding
439
ObjectAPI
Thisisthedefault.Ittriestousethegetterandsettermethodsforthefieldiftheyexist,otherwisegoesinRAWmode(seebelow).The
conventionforthegetteristhesameasJava: get<field-name>wherefield-nameiscapitalized.Thesameisforsetterbutwith'set'as
prefixinsteadof'get': set<field-name>.Ifthegetterorsetterismissing,thentherawbindingwillbeused.
Example:Field' Stringname'-> getName()and setName(String)
Custombinding
Sincev1.2OrientprovidesthepossibilityofcustombindingextendingtheOObjectM ethodFilterclassandregisteringittothewanted
class.
Thecustomimplementationmustprovidethe publicbooleanisHandled(Methodm)toletOrientknowwhatmethodswillbe
managedbytheProxyHandlerandwhatmethodswon't.
Thecustomimplementationmustprovidethe publicStringgetFieldName(Methodm)toletorientknowhowtoparseafieldname
startingfromtheaccessingmethodname.Inthecasethosetwomethodsarenotprovidedthedefaultbindingwillbeused
ThecustomM ethodFiltercanberegisteredbycalling OObjectEntityEnhancer.getInstance().registerClassMethodFilter(Class<?>,
customMethodFilter);
Domainclassexample:
publicclassCustomMethodFilterTestClass{
protectedStringstandardField;
protectedStringUPPERCASEFIELD;
protectedStringtransientNotDefinedField;
//GETTERSANDSETTERS
...
}
M ethodfilterexample:
publicclassCustomMethodFilterextendsOObjectMethodFilter{
@Override
publicbooleanisHandled(Methodm){
if(m.getName().contains("UPPERCASE")){
returntrue;
}elseif(m.getName().contains("Transient")){
returnfalse;
}
returnsuper.isHandled(m);
}
@Override
publicStringgetFieldName(Methodm){
if(m.getName().startsWith("get")){
if(m.getName().contains("UPPERCASE")){
return"UPPERCASEFIELD";
}
returngetFieldName(m.getName(),"get");
}elseif(m.getName().startsWith("set")){
if(m.getName().contains("UPPERCASE")){
return"UPPERCASEFIELD";
}
returngetFieldName(m.getName(),"set");
}else
returngetFieldName(m.getName(),"is");
}
}
M ethodfilterregistrationexample:
OObjectEntityEnhancer.getInstance().registerClassMethodFilter(CustomMethodFilterTestClass.class,newCustomMethodFilter());
440
ObjectAPI
ReadaPOJO
YoucanreadaPOJOfromthedatabaseintwoways:
bycallingthemethod load(ORID)
byexecutingaquery query(q)
WhenOrientDBloadstherecord,itcreatesanewPOJObycallingtheemptyconstructorandfillingallthefieldsavailableinthesource
record.IfafieldispresentonlyintherecordandnotinthePOJOclass,thenitwillbeignored.EvenwhenthePOJOisupdated,any
fieldsintherecordthatarenotavailableinthePOJOclasswillbeuntouched.
SaveaPOJO
YoucansaveaPOJOtothedatabasebycallingthemethod save(pojo).IfthePOJOisalreadyaproxiedinstance,thenthedatabase
willjustsavetherecordboundedtoit.Incasetheobjectisnotproxiedthedatabasewillserializeitandsavethecorrespondedrecord:In
thiscasetheobjectMUS Tbereassingedwiththeonereturnedbythedatabase
Fetchingstrategies
Startingfromrelease0.9.20,OrientDBsupportsFetching-StrategiesbyusingtheFetchPlans.FetchPlansareusedtocustomizehow
OrientDBmustloadlinkedrecords.TheODatabaseObjectTxusestheFetchPlanalsotodeterminehowtobindthelinkedrecordstothe
POJObybuildinganobjecttree.
Customtypes
ToletOrientDBusenotsupportedtypesusethecustomtypes.TheyM USTBEregisteredbeforedomainclassesregistration,ifnotall
customtypefieldswillbetreatedasdomainclasses.Incaseofregisteringacustomtypethatisalreadyregisterasadomainclasssaid
classwillberemoved.
Important:java.langclassescannotbemanagedthisway
Exampletomanageanenumerationascustomtype:
Enumdeclaration
441
ObjectAPI
publicenumSecurityRole{
ADMIN("administrador"),LOGIN("login");
privateStringid;
privateSecurityRole(Stringid){
this.id=id;
}
publicStringgetId(){
returnid;
}
@Override
publicStringtoString(){
returnid;
}
publicstaticSecurityRolegetByName(Stringname){
if(ADMIN.name().equals(name)){
returnADMIN;
}elseif(LOGIN.name().equals(name)){
returnLOGIN;
}
returnnull;
}
publicstaticSecurityRole[]toArray(){
returnnewSecurityRole[]{ADMIN,LOGIN};
}
}
Customtypemanagement
OObjectSerializerContextserializerContext=newOObjectSerializerContext();
serializerContext.bind(newOObjectSerializer<SecurityRole,String>(){
publicObjectserializeFieldValue(Class<?>type,SecurityRolerole){
returnrole.name();
}
publicObjectunserializeFieldValue(Class<?>type,Stringstr){
returnSecurityRole.getByName(str);
}
});
OObjectSerializerHelper.bindSerializerContext(null,serializerContext);
//NOWYOUCANREGISTERYOURDOMAINCLASSES
database.getEntityManager().registerEntityClass(User.class);
OrientDBwillusethatcustomserializertomarshallandunmarshallspecialtypes.
ODatabaseObjectTx(olddeprecatedimplementation)
Availablesincev1.0rc9
TheObjectDatabaseimplementationmakesthingseasierfortheJavadevelopersincethebindingbetweenObjectstoRecordsis
transparent.
Howitworks?
OrientDBusesJavareflectionanddoesn'trequirethatthePOJOisenhancedinordertouseitaccordingtotheJDOstandardand
doesn'tuseProxiesasdomanyJPAimplementationssuchasHibernate.SohowcanyouworkwithplainPOJOs?
OrientDBworksintwoways:
Connectedmode
442
ObjectAPI
Detachedmode
Connectedmode
TheODatabaseObjectTximplementationisthegatewaybetweenthedeveloperandOrientDB.ODatabaseObjectTxkeepstrackofthe
relationshipbetweenthePOJOandtheRecord.
EachPOJOthat'sreadfromthedatabaseiscreatedandtrackedbyODatabaseObjectTx.IfyouchangethePOJOandcallthe
ODatabaseObjectTx.save(pojo)method,OrientDBrecognizesthePOJOboundwiththeunderlyingrecordand,beforesavingit,will
copythePOJOattributestotheloadedrecord.
ThisworkswithPOJOsthatbelongtothesameinstance.Forexample:
ODatabaseObjectTxdb=newODatabaseObjectTx("remote:localhost/demo");
db.open("admin","admin");
try{
List<Customer>result=db.query(newOSQLSynchQuery<Customer>(db,"selectfromcustomer"));
for(Customerc:result){
c.setAge(100);
db.save(c);//<-ATTHISPOINTTHEPOJOWILLBERECOGNIZEDASKNOWNBECAUSEIS
//ALWAYSLOADEDWITHTHISDBINSTANCE
}
}finally{
db.close;
}
Whenthe db.save(c)iscalled,theODatabaseObjectTxinstancealreadyknowsoboutitbecausehasbeenretrievedbyusingaquery
throughthesameinstance.
Detachedmode
InatypicalFront-Endapplicationyouneedtoloadobjects,displaythemtotheuser,capturethechangesandsavethembacktothe
database.Usuallythisisimplementedbyusingadatabasepoolinordertoavoidleavingadatabaseinstanceopenfortheentirelifecycle
oftheusersession.
Thedatabasepoolmanagesaconfigurablenumberofdatabaseinstances.Theseinstancesarerecycledforalldatabaseoperations,sothe
listofconnectedPOJOsisclearedateveryreleaseofthedatabasepoolinstance.Thisiswhythedatabaseinstancedoesn'tknowthe
POJOusedbytheapplicationandinthismodeifyousaveapreviouslyloadedPOJOitwillappearasaNEWoneandistherefore
createdasnewinstanceinthedatabasewithanewRecordID.
ThisiswhyOrientDBneedstostoretherecordinformationinsidethePOJOitself.ThisisretrievedwhenthePOJOissavedsoitis
knownifthePOJOalreadyhasownidentity(hasbeenpreviouslyloaded)ornot(it'snew).
TosavetheRecordIdentityyoucanusetheJPA@Idannotationabovethepropertyinterested.Youcandeclareitas:
Object,thesuggested,inthiscaseOrientDBwillstoretheORecordIdinstance
S tring,inthiscaseOrientDBwillstorethestringrepresentationoftheORecordId
Long,inthiscaseOrientDBwillstoretherightpartoftheRecordID.Thisworksonlyifyou'veaschemafortheclass.Theleft
sidewillberebuiltatsavetimebygettingtheclassid.
Example:
443
ObjectAPI
publicclassCustomer{
@Id
privateObjectid;//DON'TCREATEGETTER/SETTERFORITTOPREVENTTHECHANGINGBYTHEUSERAPPLICATION,
//UNLESSIT'SNEEDED
privateStringname;
privateStringsurname;
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetSurname(){
returnname;
}
publicvoidsetSurname(Stringsurname){
this.surname=surname;
}
}
OrientDBwillsavetheRecordIdentityintheidpropertyevenifgetter/settermethodsarenotcreated.
IfyouworkwithtransactionsyoualsoneedtostoretheRecordVersioninthePOJOtoallowM VCC.UsetheJPA@Version
annotationabovethepropertyinterested.Youcandeclareitas:
java.lang.Object(suggested)-acom.orientechnologies.orient.core.version.OS impleVersionisused
java.lang.Long
java.lang.S tring
Example:
publicclassCustomer{
@Id
privateObjectid;//DON'TCREATEGETTER/SETTERFORITTOPREVENTTHECHANGINGBYTHEUSERAPPLICATION,
//UNLESSIT'SNEEDED
@Version
privateObjectversion;//DON'TCREATEGETTER/SETTERFORITTOPREVENTTHECHANGINGBYTHEUSERAPPLICATION,
//UNLESSIT'SNEEDED
privateStringname;
privateStringsurname;
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetSurname(){
returnname;
}
publicvoidsetSurname(Stringsurname){
this.surname=surname;
}
}
SaveMode
SinceOrientDBdoesn'tknowwhatobjectischangedinatreeofconnectedobjects,bydefaultitsavesalltheobjects.Thiscouldbevery
expensiveforbigtrees.ThisisthereasonwhyyoucancontrolmanuallywhatischangedornotviaasettingintheODatabaseObjectTx
instance:
db.setSaveOnlyDirty(true);
444
ObjectAPI
orbysettingaglobalparameter(seeParameters):
OGlobalConfiguration.OBJECT_SAVE_ONLY_DIRTY.setValue(true);
Totrackwhatobjectisdirtyuse:
db.setDirty(pojo);
Tounsetthedirtystatusofanobjectuse:
db.unsetDirty(pojo);
Dirtymodedoesn'taffectinmemorystateofPOJOs,soifyouchangeanobjectwithoutmarkingitasdirty,OrientDBdoesn'tknow
thattheobjectischanged.Furthermoreifyouloadthesamechangedobjectusingthesamedatabaseinstance,themodifiedobjectis
returned.
Requirements
Declarepersistentclasses
Inordertoknowwhichclassesarepersistent(betweenthousandsinyourclasspath),youneedtotellOrientDB.UsingtheJavaAPIis:
database.getEntityManager().registerEntityClasses("com.orientechnologies.orient.test.domain");
OrientDBsavesonlythefinalpartoftheclassnamewithoutthepackage.Forexampleifyou'reusingtheclass Accountinthepackage
com.orientechnologies.demo,thepersistentclasswillbeonly"Account"andnottheentire com.orientechnologies.demo.Account.This
meansthatclassnames,inthedatabase,arealwaysuniqueandcan'texisttwoclasswiththesamenameevenifdeclaredindifferent
packages.
Emptyconstructor
AllyourclassesmusthaveanemptyconstructortolettoOrientDBtocreateinstances.
POJObinding
AllthePOJOattributeswillberead/storedfrom/intotherecordexceptforfieldswiththetransientmodifier.OrientDBusesJava
reflectionbutthediscoveryofPOJOclassesismadeonlythefirsttimeatstartup.JavaReflectioninformationisinspectedonlythe
firsttimetospeeduptheaccesstothefields/methods.
Thereare2kindsofbinding:
Defaultbindingand
Rawbinding
Defaultbinding
Thisisthedefault.Ittriestousethegetterandsettermethodsforthefieldiftheyexist,otherwisegoesinRAWmode(seebelow).The
conventionforthegetteristhesameasJava: get<field-name>wherefield-nameiscapitalized.Thesameisforsetterbutwith'set'as
prefixinsteadof'get': set<field-name>.Ifthegetterorsetterismissing,thentherawbindingwillbeused.
Example:Field' Stringname'-> getName()and setName(String)
Rawbinding
445
ObjectAPI
Thismodeactsatrawlevelbyaccessingthefielddirectly.Ifthefieldsignatureisprivateorprotected,thentheaccessibilitywillbe
forced.ThisworksgenerallyinallthescenariosexceptwhereacustomSecurityM anagerisdefinedthatdeniesthechangetothe
accessibilityofthefield.
Toforcethisbehaviour,usetheJPA2@AccessTypeannotationabovetherelevantproperty.Forexample:
publicclassCustomer{
@AccessType(FIELD)
privateStringname;
privateStringsurname;
publicStringgetSurname(){
returnname;
}
publicvoidsetSurname(Stringsurname){
this.surname=surname;
}
}
ReadaPOJO
YoucanreadaPOJOfromthedatabaseintwoways:
bycallingthemethod load(ORID)
byexecutingaquery query(q)
WhenOrientDBloadstherecord,itcreatesanewPOJObycallingtheemptyconstructorandfillingallthefieldsavailableinthesource
record.IfafieldispresentonlyintherecordandnotinthePOJOclass,thenitwillbeignored.EvenwhenthePOJOisupdated,any
fieldsintherecordthatarenotavailableinthePOJOclasswillbeuntouched.
Callbacks
YoucandefinesomemethodsinthePOJOclassthatarecalledascallbacksbeforetherecordisread:
@OBeforeDeserializationcalledjustBEFOREunmarshallingtheobjectfromthesourcerecord
@OAfterDeserializationcalledjustAFTERunmarshallingtheobjectfromthesourcerecord
Example:
publicclassAccount{
privateStringname;
transientprivateStringstatus;
@OAfterDeserialization
publicvoidinit(){
status="Loaded";
}
}
Callbacksareusefultoinitializetransientfields.
SaveaPOJO
YoucansaveaPOJOtothedatabasebycallingthemethod save(pojo).IfthePOJOisalreadyknowntotheODatabaseObjectTx
instance,thenitupdatestheunderlyingrecordbycopyingallthePOJOattributestotherecords(omittingthosewithtransient
modifier).
Callbacks
YoucandefineinthePOJOclasssomemethodscalledascallbackbeforetherecordiswritten:
@OBeforeSerializationcalledjustBEFOREmarshallingtheobjecttotherecord
446
ObjectAPI
@OAfterSerializationcalledjustAFTERmarshallingtheobjecttotherecord
Example:
publicclassAccount{
privateStringname;
transientprivateSockets;
@OAfterSerialization
publicvoidfree(){
s.close();
}
}
Callbacksareusefultofreetransientresources.
==Fetchingstrategies=v
Startingfromrelease0.9.20,OrientDBsupportsFetching-StrategiesbyusingtheFetchPlans.FetchPlansareusedtocustomizehow
OrientDBmustloadlinkedrecords.TheODatabaseObjectTxusestheFetchPlanalsotodeterminehowtobindthelinkedrecordstothe
POJObybuildinganobjecttree.
Customtypes
ToletOrientDBusenotsupportedtypesusethecustomtypes.Registerthembeforetoregisterdomainclasses.Exampletomanagea
BigInteger(thatit'snotnativelysupported):
OObjectSerializerContextserializerContext=newOObjectSerializerContext();
serializerContext.bind(newOObjectSerializer<BigInteger,Integer>(){
publicIntegerserializeFieldValue(Class<?>itype,BigIntegeriFieldValue){
returniFieldValue.intValue();
}
publicBigIntegerunserializeFieldValue(Class<?>itype,IntegeriFieldValue){
returnnewBigInteger(iFieldValue);
}
});
OObjectSerializerHelper.bindSerializerContext(null,serializerContext);
//NOWYOUCANREGISTERYOURDOMAINCLASSES
database.getEntityManager().registerEntityClass(Customer.class);
OrientDBwillusethatcustomserializertomarshallandunmarshallspecialtypes.
447
Traverse
Traverse
OrientDBisagraphdatabase.Thismeansthatthefocalpointisonrelationships(links)andhowtheyaremanaged.ThestandardSQL
languageisnotenoughtoworkwithtreesorgraphsbecauseitlackstherecursionconcept.ThisisthereasonwhyOrientDBprovidesa
newcommandtotraversetreesandgraphs:TRAVERSE.Traversingistheoperationthatcrossesrelationshipsbetweenrecords
(documents,vertexes,nodes,etc).ThisoperationismuchmuchfasterthanexecutingaJOINinaRelationaldatabase.
ThemainconceptsofTraversalare:
target,asthestartingpointwheretotraverserecords.Canbe:
class
cluster
setofrecords,specifyingitsRecordID
sub-commandthatreturnsan Iterable<OIdentifiable>.Youcannestmultipleselectandtraversealltogether
fields,thefieldstotraverse.Use *, any()or all()totraverseallfieldsinadocument
limit,themaximumnumberofrecordstoretrieve
predicate,asthepredicatetoexecuteagainsteachtraverseddocument.Ifthepredicatereturnstrue,thedocumentisreturned,
otherwiseitisskipped
strategy,indicateshowthegraphtraversed:
DEPTH_FIRST,thedefault,
BREADTH_FIRST,
Traversingstrategies
DEPTH_FIRSTstrategy
ThisisthedefaultstrategyusedbyOrientDBfortraversal.Itexploresasfaraspossiblealongeachbranchbeforebacktracking.It's
implementedusingrecursion.ToknowmorelookatDepth-Firstalgorithm.Belowtheorderedstepsexecutedwhiletraversingthegraph
usingDEPTH_FIRSTstrategy:
BREADTH_FIRSTstrategy
448
Traverse
Itinspectsalltheneighboringnodes,thenforeachofthoseneighbornodesinturn,itinspectstheirneighbornodeswhichwere
unvisited,andsoon.CompareBREADTH_FIRS Twiththeequivalent,butmorememory-efficientiterativedeepeningDEPTH_FIRS T
searchandcontrastwithDEPTH_FIRS Tsearch.ToknowmorelookatBreadth-Firstalgorithm.Belowtheorderedstepsexecuted
whiletraversingthegraphusingBREADTH_FIRSTstrategy:
Contextvariables
Duringtraversalsomecontextvariablesaremanagedandcanbeusedbythetraversecondition:
$depth,asanintegerthatcontainthedepthlevelofnestingintraversal.Firstlevelis0
$path,asastringrepresentationofthecurrentpositionasthesumoftraversednodes
$stack,asthestackcurrentnodetraversed
$history,astheentirecollectionofvisitednodes
Thefollowingsectionsdescribevarioustraversalmethods.
SQLTraverse
ThesimplestavailablewaytoexecuteatraversalisbyusingtheSQLTraversecommand.Forinstance,toretrieveallrecordsconnected
fromandtoMovierecordsuptothe5thlevelofdepth:
for(OIdentifiableid:newOSQLSynchQuery<ODocument>("traversein,outfromMoviewhile$depth<=5")){
System.out.println(id);
}
Lookatthecommandsyntaxformoreinformation.
NativeFluentAPI
NativeAPIsupportsfluentexecutionguaranteeingcompactandreadablesyntax.Themainclassis OTraverse:
target(<iter:Iterable<OIdentifiable>>),tospecifythetargetasanyiterableobjectlikecollectionsorarraysofOIdentifiable
objects.
target(<iter:Iterator<OIdentifiable>>),tospecifythetargetasanyiteratorobject.Tospecifyaclassuse
database.browseClass(<class-name>).iterator()
target(<record:OIdentifiable>,<record:OIdentifiable>,...),tospecifythetargetasavararsofOIterableobjects
449
Traverse
field(<field-name:string>),tospecifythedocument'sfieldtotraverse.Toaddmultiplefieldcallthismethodinchain.Example:
.field("in").field("out")
fields(<field-name:string>,<field-name:string>,...),tospecifymultiplefieldsinonecallpassingavarargsofStrings
fields(Collection<field-name:string>),tospecifymultiplefieldsinonecallpassingacollectionofString
limit(<max:int>),asthemaximumnumberofrecordreturned
predicate(<predicate:OCommandPredicate>),tospecifyapredicatetoexecuteagainsteachtraversedrecord.Ifthepredicatereturns
true,thentherecordisreturnedasresult,otherwisefalse.it'scommontocreateananonymousclassspecifyingthepredicateatthe
fly
predicate(<predicate:OSQLPredicate>),tospecifythepredicateusingtheSQLsyntax.
InthetraversecommandcontextiContextyoucanread/putanyvariable.Traversecommandupdatesthesevariables:
depth,asthecurrentdepthofnesting
path,asthestringrepresentationofthecurrentpath.Youcanalsodisplayit.Example: select$pathfrom(traverse*fromV)
stack,astheListofoperationinthestack.Useittoaccesstothehistoryofthetraversal.It'sa List<OTraverseAbstractProcess<?
>>whereprocessimplementationsare:
OTraverseRecordSetProcess,usuallythefirstoneit'sthebasetargetoftraverse
OTraverseRecordProcess,representatraversedrecord
OTraverseFieldProcess,representatraversalthrougharecord'sfield
OTraverseMultiValueProcess,useonfieldsthataremultivalue:arrays,collectionsandmaps
history,asthesetofrecordstraversedasa Set<ORID>.
ExampleusingananonymousOCommandPredicateaspredicate
for(OIdentifiableid:newOTraverse()
.field("in").field("out")
.target(database.browseClass("Movie").iterator())
.predicate(newOCommandPredicate(){
publicObjectevaluate(ORecordiRecord,ODocumentiCurrentResult,OCommandContextiContext){
return((Integer)iContext.getVariable("depth"))<=5;
}
})){
System.out.println(id);
}
ExampleusingtheOSQLPredicateaspredicate
for(OIdentifiableid:newOTraverse()
.field("in").field("out")
.target(database.browseClass("Movie").iterator())
.predicate(newOSQLPredicate("$depth<=5"))){
System.out.println(id);
}
Otherexamples
OTraversegetsanyIterable,IteratorandSingle/M ultiOIdentifiable.There'salsothelimit()clause.Tospecifymultiplefieldsuse
fields().Fullexample:
for(OIdentifiableid:newOTraverse()
.target(newORecordId("#6:0"),newORecordId("#6:1"))
.fields("out","int")
.limit(100)
.predicate(newOSQLPredicate("$depth<=10"))){
System.out.println(id);
}
450
LiveQuery
LiveQuery
(Since2.1)
Writingrealtime,reactiveapplicationsishardtaskwithtraditionalqueryparadigm.Thinkaboutasimpleusecaselikeupdatinga
webpagewithfreshdatacomingfromthedatabaseandkeepingitupdatedovertime;alsoconsiderthatupdatescanbemadeby
differentdatasources(multipleapplications,manualDBAoperations...).
Withatraditionalapproach,theclienthastopollthedatabasetoobtainfreshdata.Thisapproachhasthreefundamentalproblems:
theclientneverknowswhethersomethinghaschangedintheDB,soitwillexecutepollingqueriesevenwhennothinghaschanged.
Thiscanbeabigwasteofresources,especiallywhenthequeryisexpensive
ifyouneed(near)realtimedata,theclientwillhavetopollthedatabaseveryoften
resultsarrivetotheclientatfixedtimeintervals,soifachangehappensinthedatabaseatthemiddleofthattimeinterval,theresult
willarrivetotheclientonlyatthenextquery
Theimagebelowsummarizesthissituation
traditionalquerypollingapproach
Youhavetomakeachoicehere
youcandecidetohavelongpollingintervals,reducingexecutionoverhead,buthavingupdatedresultslater
youcandecinetohaveshortpollingintervals,havingupdatedresultssooner,butwithahighexecutionoverhead
WithLiveQueryyoucansubscribeforchangesonaparticularclass(oronasubsetofrecordsbasedonaWHEREcondition);
OrientDBwillpushchangestotheclientassoonastheyhappeninthedatabase.
LiveQueryapproach
451
LiveQuery
Advantagesareobvious:
youdonothavetopollthedatabase,sothereisnowasteofresourceswhendatadonotchange
yougetnotificationsassoonaschangeshappeninthedb(nomatterwhatthedatasourceis)
Traditionalqueriesvs.LiveQuery
WhenexecutingaSELECTstatement(synchronousorasynchronous),youexpectthesystemtoreturnresultsthatarecurrentlypresent
inthedatabaseandthatmatchyourselectioncriteria.Youexpectyourresultsettobefiniteandyourquerytoexecuteinagiventime.
Alivequeryactsinaslightlydifferentway:
itdoesnotreturndataastheyareatthemomentofthequeryexecution
itreturnschangesthathappentothedatabasefromthatmomentonandthatmatchyourcriteria
itneverends(unlessyouterminateitoranerroroccurs)
itisasynchronousandpushbased:theserverwillsendyoudataassoonastheyareavailable,youjusthavetoprovideacallback.
Tomakethedifferenceexplicit,hereisasimpleexample(justtheflowofresultsinameta-language,notaworkingexample)
Standardquery
AclientexecutesaqueryontheDB
SELECTFROMPERSON
Theclientwillreceivearesultthatrepresentsthecurrentsituationinthedatabase:
RID,NAME,SURNAME
#12:0,"John","Smith"
#12:1,"Foo","Bar"
Numberofresults:2
AnotherclientinsertsnewdataintheDB
INSERTINTOPERSONSETNAME='Jenny'
Thefirstclientwillnotreceivethisrecord,becausetheSELECTresultsetisclosed.Inshort,thisINSERToperationwillnotaffectthe
previousquery.
452
LiveQuery
LIVEquery
Theclientexecutesthisquery:
LIVESELECTFROMPERSON
theimmediateresultofthisqueryisjusttheuniqueidentifierofthequeryitself(nodataarereturned,evenifdataarepresentintheDB)
token:1234567//Uniqueidentifierofthislivequery,neededforunsubscribe
AnotherclientinsertsnewdataintheDB
INSERTINTOPERSONSETname='Jenny'
Thefirstclientwillreceiveamessagewiththefollowingcontent(schematic):
content:{@rid:#12:0,name:'Jenny'}
operation:insert
Anotherclientupdatesexistingdata
UPDATEPERSONSETNAME='Kerry'WHERENAME='Jenny'
Thefirstclientwillreceiveamessagewiththefollowingcontent(schematic):
content:{@rid:#12:0,name:'Kerry'}
operation:update
NowthefirstclientcandecidetounsubscribefromthisLiveQuery
LIVEUNSUBSCRIBE1234567
Fromnowon,thelivequerywillnotreturnanyotherresultstotheclient.
WhenshouldyouuseLiveQuery
LiveQueryisparticularlyusefulinthefollowingscenarios:
whenyouneedcontinuous(realtime)updatesandyouhavemultipleclientsaccessingdifferentdatasubsets:pollingisaan
expensiveoperation,havingthousandsofclientsthatexecutecontinuouspollingcouldcrashanyserver;inthebestcaseitwillbea
wasteofresources,especiallyifupdateshappenrarely
whenyouhavemultipledatasourcesthatinsert/updatedata:ifyouhaveasingledatasourcethatpopulatethedatabase,thenyou
caninterceptitandletitdirectlynotifytheclientsforchanges;unfortunatelyitalmostneverhappens,inthemajorityoftheuse
casesyouwillhavemultipledatasources,sometimesautomatic(eg.applications)sometimesmanual(yourDBAthatdoesdata
cleaning)andyouwantallthesechangestobeimmediatelynotifiedtotheclient.
whenyoudeveloponapush-based/reactiveinfrastructure:ifyouworkonamessage-driveninfrastructoureorwithareactive
framework,workingwithtraditional(synchronous,blocking)queriescanbearealpain;havingadatabasethatfollowsthesame
paradigmandthatprovidespushnotificationsfordatachangewillletyouwriteapplicationsinamoreconsistentway.
Supportedinterfaces
LiveQueryiscurrentlysupportedfromthefollowinginterfaces
Java
Node.js(OrientJS)
453
LiveQuery
EnablingLiveQuery
Sinceversion2.2thelivequeryareenabledbydefault,fromdisableitsettheproperty query.live.supporttofalse.
LiveQueryinJava
ToimplementLiveQueryinJavayouneedtwoelements:
astatement,tobeexecutedbyOLiveQuery
alistenerthatasynchronousreceivesresult
ThelistenerhastoimplementOLiveResultListener.Itjusthasacallbackmethodthattakesthelivequerytokenandtherecordthatwas
modified(withtheoperationthatoccurred,eg.insert,updateordelete)
classMyLiveQueryListenerimplementsOLiveResultListener{
publicList<ORecordOperation>ops=newArrayList<ORecordOperation>();
@Override
publicvoidonLiveResult(intiLiveToken,ORecordOperationiOp)throwsOException{
System.out.println("Newresultfromserverforlivequery"+iLiveToken);
System.out.println("operation:"+iOp.type);
System.out.println("content:"+iOp.record);
}
publicvoidonError(intiLiveToken){
System.out.println("Livequeryterminateduetoerror");
}
publicvoidonUnsubscribe(intiLiveToken){
System.out.println("Livequeryterminatewithunsubscribe");
}
}
Toactuallyexecutethelivequery,youcanusethe db.query()methodpassinga OLiveQueryobjectasanargument,etc.
ODatabaseDocumentTxdb=...//IsupposeyouhaveanactiveDBinstance
//Instantiatethequerylistener
MyLiveQueryListenerlistener=newMyLiveQueryListener();
//Executethequery
List<ODocument>result=db.query(newOLiveQuery<ODocument>("liveselectfromTest",listener));
//Getthequerytoken,itisneededforunsubscribe
Stringtoken=result.get(0).field("token");//1234567
//Fromnowyouwillreceiveresultsfromtheserverforeverychangethatmatchesyourquerycriteria.
//IfyouorsomeoneelseexecutesanINSERTontheserver
db.command(newOCommandSQL("insertintotestsetname='foo',surname='bar'")).execute();
//YourMyLiveQueryListener.onLiveResult()willbeinvoked.Inthiscasetheresultwillbe
//Newresultfromserverforlivequery1234567<-atokengeneratedbytheserver
//operation:3<-ORecordOperation.CREATED
//content:{@Rid:"#12:0",name:"foo",surname:"bar"}
db.command(newOCommandSQL("updatetestsetname='baz'wheresurname='bar'")).execute();
//Newresultfromserverforlivequery1234567
//operation:1<-ORecordOperation.UPDATED
//content:{@Rid:"#12:0",name:"baz",surname:"bar"}
db.command(newOCommandSQL("liveunsubscribe1234567")).execute();
//Fromnowyouwillnotreceiveanyotherresults
454
LiveQuery
LiveQueryinNode.js
TouseLiveQueryinNode.jsyoujusthavetoimport"orientjs"modulewith
npminstallorientjs
HereisasimpleexamplethatshowshowtouseLiveQuerywithOrientJS
varOrientDB=require('orientjs');
varserver=OrientDB({host:'localhost',port:2424});
vardb=server.use({name:'test',username:'admin',password:'admin'});
db.liveQuery("liveselectfromV")
.on('live-insert',function(data){
//newrecordinsertedinthedatabase,
varmyRecord=data.content;
//yourcodehere...
})
.on('live-delete',function(data){
//recordjustdeleted,receivingtheoldcontent
varmyRecord=data.content;
//yourcodehere...
})
.on('live-update',function(data){
//recordupdated,receivingthenewcontent
varmyRecord=data.content;
//yourcodehere...
})
What'snext
OrientDBteamisworkinghardtomakeitstableandtosupportitonalltheclients.TomakelivequerystableinOrientDB2.2,the
followingstepsareneeded:
addtestsforconnectionfailure
checkformemoryleaks
addtestsitindistributedmode
giveanadditionalchecktotheOrientJsimplementation
Wearealsoconsideringintegrationswithexistingframeworkslike(M eteor)
Startingfrom2.2LiveQuerywillbereleasedasStableandwillbecoveredbycommercialsupporttoo.
455
M ulti-Threading
Multi-Threading
OrientDBsupportsmulti-threadsaccesstothedatabase. ODatabase*and OrientGraph*instancesarenotthread-safe,soyou'vetoget
aninstanceperthreadandeachdatabaseinstancecanbeusedonlyinonethreadpertime.Formoreinformationabouthowconcurrency
ismanagedbyOrientDBlookatConcurrency.
S incev2.1OrientDBdoesn'tallowimplicitusageofmultipledatabaseinstancesfromthesamethread.Any
attempttomanagemultipleinstancesinthesamethreadmustexplicitlycallthemethod
db.activateOnCurrentThread()againstthedatabaseinstanceBEFOREyouuseit.
M ultipledatabaseinstancespointtothesamestoragebyusingthesameURL.InthiscaseStorageisthread-safeandorchestrates
requestsfromdifferent ODatabase*instances.
ODatabaseDocumentTx-1------+
+---->OStorage(url=plocal:/temp/db)
ODatabaseDocumentTx-2------+
ThesameasforGraphAPI:
OrientGraph-1------+
+---->OStorage(url=plocal:/temp/db)
OrientGraph-2------+
Databaseinstancessharethefollowingobjects:
schema
indexmanager
security
TheseobjectsaresynchronizedforconcurrentcontextsbystoringthecurrentdatabaseintheThreadLocalvariable.Everytimeyou
create,openoracquireadatabaseconnection,thedatabaseinstanceisautomaticallysetintothecurrentThreadLocalspace,soin
normalusethisishiddenfromthedeveloper.
Thecurrentdatabaseisalwaysresetforallcommonoperationslikeload,save,etc.
Exampleofusingtwodatabaseinthesamethread:
ODocumentrec1=database1.newInstance();
ODocumentrec2=database2.newInstance();
rec1.field("name","Luca");
database1.activateOnCurrentThread();//MANDATORYSINCE2.1
database1.save(rec1);//forcesavingindatabase1nomatterwheretherecordcamefrom
rec2.field("name","Luke");
database2.activateOnCurrentThread();//MANDATORYSINCE2.1
database2.save(rec2);//forcesavingindatabase2nomatterwheretherecordcamefrom
Inversion2.0.x,method activateOnCurrentThread()doesnotexist,youcanuse setCurrentDatabaseInThreadLocal()instead.
Getcurrentdatabase
TogetthecurrentdatabasefromtheThreadLocaluse:
ODatabaseDocumentdatabase=(ODatabaseDocument)ODatabaseRecordThreadLocal.INSTANCE.get();
Manualcontrol
456
M ulti-Threading
Bewarewhenyoureusedatabaseinstancesfromdifferentthreadsorthenathreadhandlemultipledatabases.Inthiscaseyoucan
overridethecurrentdatabasebycallingthismanually:
database.activateOnCurrentThread();//v2.1
//forOrientDBv.2.0.x:database.setCurrentDatabaseInThreadLocal();
Wheredatabaseisthecurrentdatabaseinstance.Example:
database1.activateOnCurrentThread();
ODocumentrec1=database1.newInstance();
rec1.field("name","Luca");
rec1.save();
database2.activateOnCurrentThread();
ODocumentrec2=database2.newInstance();
rec2.field("name","Luke");
rec2.save();
Customdatabasefactory
Sincev1.2OrientprovidesaninterfacetomanagecustomdatabasemanagementinM ultiThreadingcases:
publicinterfaceODatabaseThreadLocalFactory{
publicODatabaseRecordgetThreadDatabase();
}
Examples:
publicclassMyCustomRecordFactoryimplementsODatabaseThreadLocalFactory{
publicODatabaseRecordgetDb(){
returnODatabaseDocumentPool.global().acquire(url,"admin","admin");
}
}
publicclassMyCustomObjectFactoryimplementsODatabaseThreadLocalFactory{
publicODatabaseRecordgetThreadDatabase(){
returnOObjectDatabasePool.global().acquire(url,"admin","admin").getUnderlying().getUnderlying();
}
}
Registeringthefactory:
ODatabaseThreadLocalFactorycustomFactory=newMyCustomRecordFactory();
Orient.instance().registerThreadDatabaseFactory(customFactory);
WhenadatabaseisnotfoundincurrentthreaditwillbecalledthefactorygetDb()toretrievethedatabaseinstance.
Closeadatabase
Whathappensifyouareworkingwithtwodatabasesandclosejustone?TheThreadLocalisn'tastack,soyouloosetheprevious
databaseinuse.Example:
457
M ulti-Threading
ODatabaseDocumentTxdb1=newODatabaseDocumentTx("local:/temo/db1").create();
ODatabaseDocumentTxdb2=newODatabaseDocumentTx("local:/temo/db2").create();
...
db2.close();
//NOWNODATABASEISSETINTHREADLOCAL.TOWORKWITHDB1SETITINTHETHREADLOCAL
db1.activateOnCurrentThread();
...
MultiVersionConcurrencyControl
Iftwothreadsupdatethesamerecord,thenthelastonereceivethefollowingexception:"OConcurrentM odificationException:Cannot
updaterecord#X:Yinstorage'Z'becausetheversionisnotthelatest.Probablyyouareupdatinganoldrecordorithasbeenmodified
byanotheruser(db=vAyour=vB)"
Thisisbecauseeverytimeyouupdatearecord,theversionisincrementedby1.Sothesecondupdatefailscheckingthecurrentrecord
versionindatabaseishigherthantheversioncontainedintherecordtoupdate.
Thisisanexampleofcodetomanagetheconcurrencyproperly:
GraphAPI
for(intretry=0;retry<maxRetries;++retry){
try{
//APPLYCHANGES
vertex.setProperty("name","Luca");
vertex.addEdge("Buy",product);
break;
}catch(ONeedRetryExceptione){
//RELOADITTOGETLASTVERSION
vertex.reload();
product.reload();
}
}
DocumentAPI
for(intretry=0;retry<maxRetries;++retry){
try{
//APPLYCHANGES
document.field("name","Luca");
document.save();
break;
}catch(ONeedRetryExceptione){
//RELOADITTOGETLASTVERSION
document.reload();
}
}
Thesameintransactions:
458
M ulti-Threading
for(intretry=0;retry<maxRetries;++retry){
db.begin();
try{
//CREATEANEWITEM
ODocumentinvoiceItem=newODocument("InvoiceItem");
invoiceItem.field("price",213231);
invoiceItem.save();
//ADDITTOTHEINVOICE
Collection<ODocument>items=invoice.field(items);
items.add(invoiceItem);
invoice.save();
db.commit();
break;
}catch(OTransactionExceptione){
//RELOADITTOGETLASTVERSION
invoice.reload();
}
}
Where maxRetriesisthemaximumnumberofattemptofreloading.
Whataboutrunningtransaction?
Transactionsareboundtoadatabase,soifyouchangethecurrentdatabasewhileatxisrunning,thedeletedandsavedobjectsremain
attachedtotheoriginaldatabasetransaction.Whenitcommits,theobjectsarecommitted.
Example:
ODatabaseDocumentTxdb1=newODatabaseDocumentTx("local:/temo/db1").create();
db1.begin();
ODocumentdoc1=newODocument("Customer");
doc1.field("name","Luca");
doc1.save();//NOWIT'SBOUNDTODB1'STX
ODatabaseDocumentTxdb2=newODatabaseDocumentTx("local:/temo/db2").create();//THECURRENTDBNOWISDB2
ODocumentdoc2=newODocument("Provider");
doc2.field("name","Chuck");
doc2.save();//THISISBOUNDTODB2BECAUSEIT'STHECURRENTONE
db1.activateOnCurrentThread();
db1.commit();//WILLCOMMITDOC1ONLY
459
Transactions
TransactionPropagation
Duringapplicationdevelopmenttherearesituationswhenatransactionstartedinonemethodshouldbepropagatedtoothermethod.
Letssupposewehave2methods.
publicvoidmethod1(){
database.begin();
try{
method2();
database.commit();
}catch(Exceptione){
database.rollback();
}
}
publicvoidmethod2(){
database.begin();
try{
database.commit();
}catch(Exceptione){
database.rollback();
}
}
Asyoucanseetransactionisstartedinfirstmethodandthennewoneisstartedinsecondmethod.Sohowthesetransactionsshould
interactwitheachother.Prior1.7-rc2firsttransactionwasrolledbackandsecondwasstartedsowereriskthatallchangeswillbelost.
Since1.7-rc2westartnestedtransactionaspartofoutertransaction.Whatdoesitmeanonpractice?
Letsconsiderexampleabovewemayhavetwopossiblecaseshere:
Firstcase:
1. beginoutertransaction.
2. beginnestedtransaction.
3. commitnestedtransaction.
4. commitoutertransaction.
Whennestedtransactionisstartedallchangesofoutertransactionarevisibleinnestedtransactionandthenwhennestedtransactionis
committedchangesaredoneinnestedtransactionarenotcommittedtheywillbecommittedatthemomentwhenoutertransactionwill
becommitted.
Secondcase:
1. beginoutertransaction.
2. beginnestedtransaction.
3. rollbacknestedtransaction.
4. commitoutertransaction.
Whennestedtransactionisrolledback,changesaredoneinnestedtransactionarenotrolledback.Butwhenwecommitouter
transactionallchangeswillberolledbackandORollbackExceptionwillbethrown.
Sowhatinstancesofdatabaseshouldweusetogetadvantageoftransactionpropagationfeature:
1. Thesameinstanceofdatabaseshouldbeusedbetweenmethods.
2. Databasepoolcanbeused,insuchcaseallmethodswhichasksfordbconnectioninsamethreadwillhavethesamethesame
databaseinstance.
460
BinaryData
BinaryData
OrientDBnativelyhandlesbinarydata,namelyBLOB.However,therearesomeconsiderationstotakeintoaccountbasedonthetype
ofbinarydata,thesize,thekindofusage,etc.
Sometimesit'sbettertostorebinaryrecordsinadifferentpaththendefaultdatabasedirectorytobenefitoffasterHD(likeaSSD)or
justtogoinparalleliftheOSandHWconfigurationallowthis.
Inthiscasecreateanewclusterinadifferentpath:
db.addCluster("physical","binary","/mnt/ssd","binary");
Alltherecordsincluster binarywillresideinfilescreatedunderthedirectory /mnt/ssd.
Techniques
Storeonfilesystemandsavethepathinthedocument
Thisisthesimplerwaytohandlebinarydata:storethemtothefilesystemandjustkeepthepathtoretrievethem.
Example:
ODocumentdoc=newODocument();
doc.field("binary","/usr/local/orientdb/binary/test.pdf");
doc.save();
Pros:
Easytowrite
100%delegatedtotheFileSystem
Cons:
Binarydatacan'tbeautomaticallydistributedusingtheOrientDBcluster
StoreitasaDocumentfield
ODocumentclassisabletomanagebinarydatainformof byte[](bytearray).Example:
ODocumentdoc=newODocument();
doc.field("binary","Binarydata".getBytes());
doc.save();
Thisistheeasiestwaytokeepthebinarydatainsidethedatabase,butit'snotreallyefficientonlargeBLOBbecausethebinarycontent
isserializedinBase64.Thismeansawasteofspace(33%more)andarun-timecostinmarshalling/unmarshalling.
Alsobeawarethatoncethebinarydatareachesacertainsize(10M Binsomerecenttesting),thedatabase'sperformancecandecrease
significantly.Ifthisoccurs,thesolutionistousethe ORecordBytessolutiondescribedbelow.
Pros:
Easytowrite
Cons:
Wasteofspace+33%
Run-timecostofmarshalling/unmarshalling
Significantperformancedecreaseoncethebinaryreachesacertainlargesize
461
BinaryData
StoreitwithORecordBytes
The ORecordBytesclassisarecordimplementationabletostorebinarycontentwithoutconversions(seeabove).Thisisthefasterway
tohandlebinarydatawithOrientDBbutneedsaseparaterecordtohandleit.Thistechniquealsooffersthehighestperformancewhen
storingandretrievinglargebinarydatarecords.
Example:
ORecordBytesrecord=newORecordBytes("Binarydata".getBytes());
record.save();
Sincethisisaseparaterecord,thebestwaytoreferenceitistolinkittoaDocumentrecord.Example:
ORecordBytesrecord=newORecordBytes("Binarydata".getBytes());
ODocumentdoc=newODocument();
doc.field("id",12345);
doc.field("binary",record);
doc.save();
Inthiswayyoucanaccesstothebinarydatabytraversingthe binaryfieldoftheparent'sdocumentrecord.
ORecordBytesrecord=doc.field("binary");
byte[]content=record.toStream();
Youcanmanipulatedirectlythebufferandsaveitbackagainbycallingthe setDirty()againsttheobject:
byte[]content=record.toStream();
content[0]=0;
record.setDirty();
record.save();
Oryoucanworkagainstanother byte[]:
byte[]content=record.toStream();
byte[]newContent=newbyte[content*2];
System.arrayCopy(content,0,newContent,0,content.length);
record.fromStream(newContent);
record.setDirty();
record.save();
ORecordBytesclasscanworkwithJavaStreams:
ORecordBytesrecord=newORecordBytes().fromInputStream(in);
record.toOutputStream(out);
Pros:
Fastandcompactsolution
Cons:
Slightlycomplexmanagement
Largecontent:splitinmultipleORecordBytes
OrientDBcanstoreupto2Gbasrecordcontent.Butthereareotherlimitationsonnetworkbuffersandfilesizesyoushouldtuneto
reachthe2GBbarrier.
Howevermanagingbigchunksofbinarydatameanshavingbig byte[]structuresinRAM andthiscouldcauseaOutOfM emoryof
theJVM .M anyusersreportedthatsplittingthebinarydatainchunksit'sthebestsolution.
462
BinaryData
Continuingfromthelastexamplewecouldhandlenotasinglereferenceagainstone ORecordBytesrecordbutmultiplereferences.A
One-To-M anyrelationship.Forthispurposethe LINKLISTtypefitsperfectbecausemaintainstheorder.
ToavoidOrientDBcachesinmemorylargerecordsusethemassiveinsertintentandkeepinthecollectiontheRID,nottheentire
records.
ExampletostoreinOrientDBthefilecontent:
database.declareIntent(newOIntentMassiveInsert());
List<ORID>chunks=newArrayList<ORID>();
InputStreamin=newBufferedInputStream(newFileInputStream(file));
while(in.available()>0){
finalORecordByteschunk=newORecordBytes();
//READREMAININGDATA,BUTNOTMORETHAN8K
chunk.fromInputStream(in,8192);
//SAVETHECHUNKTOGETTHEREFERENCE(IDENTITY)ANDFREEFROMTHEMEMORY
database.save(chunk);
//SAVEITSREFERENCEINTOTHECOLLECTION
chunks.add(chunk.getIdentity());
}
//SAVETHECOLLECTIONOFREFERENCESINANEWDOCUMENT
ODocumentrecord=newODocument();
record.field("data",chunks);
database.save(record);
database.declareIntent(null);
Exampletoreadbackthefilecontent:
record.setLazyLoad(false);
for(OIdentifiableid:(List<OIdentifiable>)record.field("data")){
ORecordByteschunk=(ORecordBytes)id.getRecord();
chunk.toOutputStream(out);
chunk.unload();
}
Pros:
Fastestandcompactsolution
Cons:
M orecomplexmanagement
Conclusion
Whattouse?
Haveyoushortbinarydata?Storethemasdocument'sfield
Doyouwantthemaximumofperformanceandbetteruseofthespace?Storeitwith ORecordBytes
Haveyoulargebinaryobjects?Storeitwith ORecordBytesbutsplitthecontentinmultiplerecords
463
WebApps
WebApplications
Thedatabaseinstancesarenotthread-safe,soeachthreadneedsaowninstance.Allthedatabaseinstanceswillsharethesame
connectiontothestorageforthesameURL.FormoreinformationlookatJavaM ultithreadsanddatabases.
JavaWebApprunsinsideaServletcontainerwithapoolofthreadsthatworktherequests.
Therearemainly2solutions:
M anualcontrolofthedatabaseinstancesfromS ervlets(oranyotherserver-sidetechnologylikeApacheStrutsActions,Spring
M VC,etc.)
AutomaticcontrolusingS ervletFilters
Manualcontrol
GraphAPI
packagecom.orientechnologies.test;
importjavax.servlet.*;
publicclassExampleextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)
throwsIOException,ServletException
{
OrientBaseGraphgraph=newOrientGraph("plocal:/temp/db","admin","admin");
try{
//USERCODE
}finally{
graph.shutdown();
}
}
}
DocumentAPI
packagecom.orientechnologies.test;
importjavax.servlet.*;
publicclassExampleextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,
HttpServletResponseresponse)
throwsIOException,ServletException
{
ODatabaseDocumentTxdatabase=newODatabaseDocumentTx("plocal:/temp/db").open("admin","admin");
try{
//USERCODE
}finally{
database.close();
}
}
}
AutomaticcontrolusingServletFilters
ServletsarethebestwaytoautomatisedatabasecontrolinsideWebApps.ThetrickistocreateaFilterthatgetareferenceofthegraph
andbindsitinthecurrentThreadLocalbeforetoexecutetheServletcode.OncereturnedtheThreadLocalisclearedandgraphinstance
released.
464
WebApps
JaveEEServlets
CreateaFilterclass
FilterwithGraphAPI
Inthisexampleanewgraphinstanceiscreatedperrequest,openedandattheendclosed.
packagecom.orientechnologies.test;
importjavax.servlet.*;
publicclassOrientDBFilterimplementsFilter{
publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
FilterChainchain){
OrientBaseGraphgraph=newOrientGraph("plocal:/temp/db","admin","admin");
try{
chain.doFilter(request,response);
}finally{
graph.shutdown();
}
}
}
FilterwithDocumentAPI
Inthisexampleanewgraphinstanceiscreatedperrequest,openedandattheendclosed.
packagecom.orientechnologies.test;
importjavax.servlet.*;
publicclassOrientDBFilterimplementsFilter{
publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,
FilterChainchain){
ODatabaseDocumentTxdatabase=newODatabaseDocumentTx("plocal:/temp/db").open("admin","admin");
try{
chain.doFilter(request,response);
}finally{
database.close();
}
}
}
Registerthefilter
Nowwe'vecreatethefilterclassitneedstoberegisteredintheweb.xmlfile:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<filter>
<filter-name>OrientDB</filter-name>
<filter-class>com.orientechnologies.test.OrientDBFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OrientDB</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
465
JDBCDriver
JDBCDriver
TheJDBCdriverforOrientDBallowstoconnecttoaremoteserverusingthestandardandconsolidatedwayofinteractingwith
databaseintheJavaworld.
Includeinyourprojects
Tobeusedinsideyourproject,simplyaddthedependencytoyourpom:
<dependency>
<groupId>com.orientechnologies</groupId>
<artifactId>orientdb-jdbc</artifactId>
<version>ORIENTDB_VERSION</version>
</dependency>
NOTE:touseSNAPSHOTversionremembertoaddtheSnapshotrepositorytoyour pom.xml.
Howcanbeusedinmycode?
ThedriverisregisteredtotheJavaSQLDriverM anagerandcanbeusedtoworkwithalltheOrientDBdatabasetypes:
memory,
plocaland
remote
Thedriver'sclassis com.orientechnologies.orient.jdbc.OrientJdbcDriver.UseyourknowledgeofJDBCAPItoworkagainst
OrientDB.
Firstgetaconnection
Propertiesinfo=newProperties();
info.put("user","admin");
info.put("password","admin");
Connectionconn=(OrientJdbcConnection)DriverManager.getConnection("jdbc:orient:remote:localhost/test",info);
ThenexecuteaStatementandgettheResultSet:
Statementstmt=conn.createStatement();
ResultSetrs=stmt.executeQuery("SELECTstringKey,intKey,text,length,dateFROMItem");
rs.next();
rs.getInt("@version");
rs.getString("@class");
rs.getString("@rid");
rs.getString("stringKey");
rs.getInt("intKey");
rs.close();
stmt.close();
ThedriverretrievesOrientDBmetadata(@rid,@classand@version)onlyondirectqueries.Takealookattestscodetoseemore
detailedexamples.
466
JDBCDriver
Advancedfeatures
Connectionpool
BydefaultanewdatabaseinstanceiscreatedeverytimeyouaskforaJDBCconnection.OrientDBJDBCdriverprovidesaConnection
Pooloutofthebox.Settheconnectionpoolparametersbeforetoaskforaconnection:
Propertiesinfo=newProperties();
info.put("user","admin");
info.put("password","admin");
info.put("db.usePool","true");//USETHEPOOL
info.put("db.pool.min","3");//MINIMUMPOOLSIZE
info.put("db.pool.max","30");//MAXIMUMPOOLSIZE
Connectionconn=(OrientJdbcConnection)DriverManager.getConnection("jdbc:orient:remote:localhost/test",info);
Sparkcompatibility(from2.1.21)
ApacheSparkallowsreadingandwritingofDataFramesfromJDBCdatasources.Thedriveroffersacompatibilitymodetoenableload
ofdataframefromanOrientDb'sclassorquery.
Map<String,String>options=newHashMap<String,String>(){{
put("url","jdbc:orient:remote:localhost/sparkTest");
put("user","admin");
put("password","admin");
put("spark","true");//ENABLESparkcompatibility
put("dbtable","Item");
}};
SQLContextsqlCtx=newSQLContext(ctx);
DataFramejdbcDF=sqlCtx.read().format("jdbc").options(options).load();
467
JPA
JPA
TherearetwowaystoconfigureOrientDBJPA
Configuration
Thefirst-doitthrough/M ETA-INF/persistence.xmlFolowingOrientDBpropertiesaresupportedasfornow:
javax.persistence.jdbc.url,javax.persistence.jdbc.user,javax.persistence.jdbc.password,com.orientdb.entityClasses
Youcanalsouse<class>tag
Example:
<?xmlversion="1.0"encoding="UTF-8"?>
<persistenceversion="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistencehttp://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unitname="appJpaUnit">
<provider>com.orientechnologies.orient.object.jpa.OJPAPersistenceProvider</provider>
<!--JPAentitiesmustberegisteredhere-->
<class>com.example.domain.MyPOJO</class>
<properties>
<propertyname="javax.persistence.jdbc.url"value="remote:localhost/test.odb"/>
<propertyname="javax.persistence.jdbc.user"value="admin"/>
<propertyname="javax.persistence.jdbc.password"value="admin"/>
<!--Registerwholepackage.
Seecom.orientechnologies.orient.core.entity.OEntityManager.registerEntityClasses(String)formor
edetails-->
<propertyname="com.orientdb.entityClasses"value="com.example.domains"/>
</properties>
</persistence-unit>
</persistence>
Programmatic
Thesecondoneisprogrammatic:
Guiceexample
com.google.inject.persist.jpa.JpaPersistModule.properties(Properties)
468
JPA
/**
*triggeredassoonasawebapplicationisdeployed,andbeforeanyrequests
*begintoarrive
*/
@WebListener
publicclassGuiceServletConfigextendsGuiceServletContextListener{
@Override
protectedInjectorgetInjector(){
returnGuice.createInjector(
newJpaPersistModule("appJpaUnit").properties(orientDBProp),
newConfigFactoryModule(),
servletModule);
}
protectedstaticfinalPropertiesorientDBProp=newProperties(){{
setProperty("javax.persistence.jdbc.url","remote:localhost/test.odb");
setProperty("javax.persistence.jdbc.user","admin");
setProperty("javax.persistence.jdbc.password","admin");
setProperty("com.orientdb.entityClasses","com.example.domains");
}};
protectedstaticfinalServletModuleservletModule=newServletModule(){
@Override
protectedvoidconfigureServlets(){
filter("/*").through(PersistFilter.class);
//...
};
}
Nativeexample
//OPENTHEDATABASE
OObjectDatabaseTxdb=newOObjectDatabaseTx("remote:localhost/petshop").open("admin","admin");
//REGISTERTHECLASSONLYONCEAFTERTHEDBISOPEN/CREATED
db.getEntityManager().registerEntityClasses("foo.domain");
DBproperties,thatwerepassedprogrammatically,willoverwriteparsedfromXM Lones
Note
Configparsercheckspersistence.xmlwithvalidationschemes(XSD),soconfigurationfilemustbevalid.
1.0,2.0and2.1XSDschemesaresupported.
469
JM X
JMX
ReadCache
JM Xbeanname: com.orientechnologies.orient.core.storage.cache.local:type=O2QCacheMXBean
Ithasfollowingmembers:
usedMemory, usedMemoryInMB, usedMemoryInGBwhichisamountofdirectmemoryconsumedbyreadcacheindifferentunitsof
measurements
cacheHitsispercentofcaseswhenrecordswillbedownloadednotfromdiskbutfromreadcache
clearCacheStatistics()methodmaybecalledtoclearcachehitsstaticssowealwaysmaystarttogathercachehitsstatisticfrom
anymomentoftime
amSize, a1OutSize, a1InSizeisthesizeofLRUqueuesareusedin2Qalgorithm
WriteCache
JM Xbeanname: com.orientechnologies.orient.core.storage.cache.local:type=OWOWCacheMXBean,name=<storagename>,id=<storageid>
WritecachealikereadcacheisnotJVM wide,itisstoragewide,butoneJVM mayrunseveralserversandeachservermaycontain
storagewiththesamename,thatiswhyweneedsuchcomplexname.
JM Xbeanofwritecachehasfollowingmembers:
writeCacheSize, writeCacheSizeInMB, writeCacheSizeInGBprovidessizeofdataindifferentunitswhichshouldbeflushedto
diskinbackgroundthread
exclusiveWriteCacheSize, exclusiveWriteCacheSizeInMB, exclusiveWriteCacheSizeInGBprovidessizeofdatawhichshouldbe
flushedtodiskbutcontainedonlyinwritecache
Moreaboutmemorymodelanddataflow
Atfirstwhenwereadpageweloaditfromdiskandputitinreadcache.Thenwechangepageandputitbacktoreadcacheandwrite
cache,butwedonotcopypagefromreadtowritecachewemerelysendpointertothesamememorytowritecache.Writecache
flushes"dirtywritepage"inbackgroundthread.Thatiswhatproperty"writeCachSize"showsusamountofdataindirtypageswhich
shouldbeflushed.Butthereareveryraresituationswhenpagewhichisrarelyusedstillisnotflushedondiskandreadcachehasnot
enoughmemorytokeepit.Insuchcasethispageisremovedfromreadcache,butpointertothispagestillexistsinwritecache,thatis
whatproperty"exclusiveWriteCacheSize"showsus.Pleasenotthatthisvalueismorethan0onlyduringextremelyhighload.
TherestpropertiesofwritecacheJM Xbeanarefollowing:
lastFuzzyCheckpointDate
lastAmountOfFlushedPages
durationOfLastFlush
470
GremlinAPI
GremlinAPI
GremlinisalanguagespecializedtoworkwithPropertyGraphs.GremlinispartofTinkerPopOpenSourceproducts.Formore
information:
GremlinDocumentation
GremlinWiKi
OrientDBadaptertouseitinsideGremlin
OrientDBimplementationofTinkerPopBlueprints
ToknowmoreaboutGremlinandTinkerPop'sproductssubscribetotheGremlinGroup.
GetStarted
Launchthegremlin.sh(orgremlin.batonWindowsOS)consolescriptlocatedinthebindirectory:
>gremlin.bat
\,,,/
(oo)
-----oOOo-(_)-oOOo-----
Openthegraphdatabase
BeforeplayingwithGremlinyouneedavalidOrientGraphinstancethatpointstoanOrientDBdatabase.Toknowallthedatabase
typeslookatStoragetypes.
Whenyou'reworkingwithalocaloranin-memorydatabase,ifthedatabasedoesnotexistit'screatedforyouautomatically.Usingthe
remoteconnectionyouneedtocreatethedatabaseonthetargetserverbeforeusingit.Thisisduetosecurityrestrictions.
OncecreatedtheOrientGraphinstancewithaproperURLisnecessarytoassignittoavariable.GremliniswritteninGroovy,soit
supportsalltheGroovysyntax,andbothcanbemixedtocreateverypowerfulscripts!
Examplewithalocaldatabase(seebelowformoreinformationaboutit):
gremlin>g=newOrientGraph("plocal:/home/gremlin/db/demo");
==>orientgraph[plocal:/home/gremlin/db/demo]
Someusefullinks:
AllGremlinmethods
Allavailablesteps
Workingwithlocaldatabase
Thisisthemostoftenusedmode.Theconsoleopensandlocksthedatabaseforexclusiveuse.Thisdoesn'trequirestartinganOrientDB
server.
gremlin>g=newOrientGraph("plocal:/home/gremlin/db/demo");
==>orientgraph[plocal:/home/gremlin/db/demo]
Workingwitharemotedatabase
471
GremlinAPI
Toopenadatabaseonaremoteserverbesuretheserverisupandrunningfirst.Tostarttheserverjustlaunchserver.sh(orserver.bat
onWindowsOS)script.FormoreinformationlookatOrientDBServer
gremlin>g=newOrientGraph("remote:localhost/demo");
==>orientgraph[remote:localhost/demo]
Workingwithin-memorydatabase
Inthismodethedatabaseisvolatileandallthechangeswillbenotpersistent.Usethisinaclusteredconfiguration(thedatabaselifeis
assuredbytheclusteritself)orjustfortest.
gremlin>g=newOrientGraph("memory:demo");
==>orientgraph[memory:demo]
Usesecurity
OrientDBsupportssecuritybycreatingmultipleusersandrolesassociatedwithcertainprivileges.ToknowmorelookatSecurity.To
openthegraphdatabasewithadifferentuserthanthedefault,passtheuserandpasswordasadditionalparameters:
gremlin>g=newOrientGraph("memory:demo","reader","reader");
==>orientgraph[memory:demo]
CreateanewVertex
Tocreateanewvertex,usetheaddVertex()method.Thevertexwillbecreatedandauniqueidwillbedisplayedasthereturnvalue.
g.addVertex();
==>v[#5:0]
Createanedge
Tocreateanewedgebetweentwovertices,usetheaddEdge(v1,v2,label)method.Theedgewillbecreatedwiththelabelspecified.
Intheexamplebelowtwoverticesarecreatedandassignedtoavariable(GremlinisbasedonGroovy),thenanedgeiscreatedbetween
them.
gremlin>v1=g.addVertex();
==>v[#5:0]
gremlin>v2=g.addVertex();
==>v[#5:1]
gremlin>e=g.addEdge(v1,v2,'friend');
==>e[#6:0][#5:0-friend->#5:1]
Savechanges
OrientDBassignsatemporaryidentifiertoeachvertexandedgethatiscreated.Tosavethemtothedatabase
stopTransaction(SUCCESS)shouldbecalled
gremlin>g.stopTransaction(SUCCESS)
472
GremlinAPI
Retrieveavertex
ToretrieveavertexbyitsID,usethev(id)methodpassingtheRecordIdasanargument(withorwithouttheprefix'#').Thisexample
retrievesthefirstvertexcreatedintheaboveexample.
gremlin>g.v('5:0')
==>v[#5:0]
Getallthevertices
Toretrievealltheverticesintheopenedgraphuse.V(Vinupper-case):
gremlin>g.V
==>v[#5:0]
==>v[#5:1]
Retrieveanedge
Retrievinganedgeisverysimilartoretrievingavertex.Usethee(id)methodpassingtheRecordIdasanargument(withorwithoutthe
prefix'#').Thisexampleretrievesthefirstedgecreatedinthepreviousexample.
gremlin>g.e('6:0')
==>e[#6:0][#5:0-friend->#5:1]
Getalltheedges
Toretrievealltheedgesintheopenedgraphuse.E(Einupper-case):
gremlin>g.E
==>e[#6:0][#5:0-friend->#5:1]
Traversal
ThepowerofGremlinisintraversal.Onceyouhaveagraphloadedinyourdatabaseyoucantraverseitinmanydifferentways.
BasicTraversal
Todisplayalltheoutgoingedgesofthefirstvertexjustcreatedappendthe.outEatthevertex.Example:
gremlin>v1.outE
==>e[#6:0][#5:0-friend->#5:1]
Todisplayalltheincomingedgesofthesecondvertexcreatedinthepreviousexamplesappendthe.inEatthevertex.Example:
gremlin>v2.inE
==>e[#6:0][#5:0-friend->#5:1]
Inthiscasetheedgeisthesamebecauseit'stheoutgoingedgeof5:0andtheincomingedgeof5:1.
FormoreinformationlookattheBasicTraversalwithGremlin.
Filterresults
473
GremlinAPI
Thisexamplereturnsalltheoutgoingedgesofalltheverticeswithlabelequalto'friend'.
gremlin>g.V.outE('friend')
==>e[#6:0][#5:0-friend->#5:1]
Closethedatabase
Tocloseagraphusetheshutdown()method:
gremlin>g.shutdown()
==>null
ThisisnotstrictlynecessarybecauseOrientDBalwaysclosesthedatabasewhentheGremlinconsolequits.
Createcomplexpaths
Gremlinallowsyoutoconcatenateexpressionstocreatemorecomplextraversalsinasingleline:
v1.outE.inV
Ofcoursethiscouldbemuchmorecomplex.Belowisanexamplewiththegraphtakenfromtheofficialdocumentation:
g=newOrientGraph('memory:test')
//calculatebasiccollaborativefilteringforvertex1
m=[:]
g.v(1).out('likes').in('likes').out('likes').groupCount(m)
m.sort{a,b->a.value<=>b.value}
//calculatetheprimaryeigenvector(eigenvectorcentrality)ofagraph
m=[:];c=0;
g.V.out.groupCount(m).loop(2){c++<1000}
m.sort{a,b->a.value<=>b.value}
Passinginputparameters
SomeGremlinexpressionsrequiredeclarationofinputparameterstoberun.Thisisthecase,forexample,ofboundvariables,as
describedinJSR223GremlinScriptEngine.OrientDBhasenabledamechanismtopassvariablestoaGremlinpipelinedeclaredina
commandasdescribedbelow:
Map<String,Object>params=newHashMap<String,Object>();
params.put("map1",newHashMap());
params.put("map2",newHashMap());
db.command(newOCommandSQL("selectgremlin('
current.as('id').outE.label.groupCount(map1).optional('id').sideEffect{map2=it.map();map2+=map1;}
')")).execute(params);
GremlinPipeline
YoucanalsousenativeJavaGremlinPipelinelike:
newGremlinPipeline(g.getVertex(1)).out("knows").property("name").filter(newPipeFunction<String,Boolean>(){
publicBooleancompute(Stringargument){
returnargument.startsWith("j");
}
}).back(2).out("created");
474
GremlinAPI
Formoreinformation:UsingGremlinthroughJava
Declaringoutput
Inthesimplestcase,theoutputofthelaststep(https://github.com/tinkerpop/gremlin/wiki/Gremlin-Steps)intheGremlinpipeline
correspondstotheoutputoftheoverallGremlinexpression.However,itispossibletoinstructtheGremlinenginetoconsideranyof
theinputvariablesasoutput.Thiscanbedeclaredas:
Map<String,Object>params=newHashMap<String,Object>();
params.put("map1",newHashMap());
params.put("map2",newHashMap());
params.put("output","map2");
db.command(newOCommandSQL("selectgremlin('
current.as('id').outE.label.groupCount(map1).optional('id').sideEffect{map2=it.map();map2+=map1;}
')")).execute(params);
TherearemorepossibilitiestodefinetheoutputintheGremlinpipelines.Sothismechanismisexpectedtobeextendedinthefuture.
Please,contactOrientDBmailinglisttodiscusscustomizedoutputs.
Conclusions
Nowyou'velearnedhowtouseGremlinontopofOrientDB.ThebestplacetogoindepthwiththispowerfullanguageistheGremlin
WiKi.
475
Javascript
Javascript
OrientDBsupportsserver-sidescripting.AlltheJVM languagesaresupported.BydefaultJavaScriptisinstalled.
Scriptscanbeexecutedontheclientandontheserver-side.Ontheclient-side,theusermusthaveREADprivilegeagainstthe
database.commandresource.Ontheserver-side,thescriptinginterpretermustbeenabled.Itisdisabledbydefaultforsecurityreasons.
Inordertoreturntheresultofavariable,putthevariablenameaslaststatement.Example:
varr=db.query('selectfromouser');
print(r);
r
Willreturntheresultset.
Seealso
SQL-batch
Usage
ViaJavaAPI
ExecutesacommandlikeSQLbutusestheclass OCommandScriptpassinginthelanguagetouse.JavaScriptisinstalledbydefault.
Example:
db.command(newOCommandScript("Javascript","print('helloworld')")).execute();
Viaconsole
JavaScriptcodecanbeexecutedontheclient-side,theconsole,orserver-side:
Use jstoexecutethescriptontheclient-siderunningitintheconsole
use jsstoexecutethescriptontheserver-side.Thisfeatureisdisabledbydefault.ToenableitlookatEnableServerside
scripting.
Sincethesemi-colon ;characterisusedinbothconsoleandJavaScriptlanguagestoseparatestatements,howcanweexecutemultiple
commandsontheconsoleandwithJavaScript?
TheOrientDBconsoleusesareservedkeyword endtoswitchfromJavaScriptmodetoconsolemode.
Example:
orientdb>connectremote:localhost/demoadminadmin;jsfor(i=0;i<10;i++){db.query('selectfromMapPoint')};end;exi
t
Thislineconnectstotheremoteserverandexecutes10queriesontheconsole.The endcommandswitchesthemodebacktothe
OrientDBconsoleandthenexecutestheconsole exitcommand.
Belowisanexampletodisplaytheresultsofaqueryontheserverandontheclient.
1. connectstotheremoteserveras admin
2. executesaqueryandassignstheresulttothevariable r,thendisplaysitserver-sideandreturnsittobedisplayedontheclient
sidetoo
3. exitstheconsole
476
Javascript
Interactivemode
$./console.sh
OrientDBconsolev.1.5www.orientechnologies.com
Type'help'todisplayallthecommandssupported.
orientdb>connectremote:localhost/demoadminadmin
Connectingtodatabase[remote:localhost/demo]withuser'admin'...OK
orientdb>jssvarr=db.query('selectfromouser');print(r);r
---+---------+--------------------+--------------------+--------------------+-------------------#|RID|name|password|status|roles
---+---------+--------------------+--------------------+--------------------+-------------------0|#4:0|admin|{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873FC4BB8A81F6F2AB448A918|ACTIVE
|[1]
1|#4:1|reader|{SHA-256}3D0941964AA3EBDCB00CCEF58B1BB399F9F898465E9886D5AEC7F31090A0FB30|ACTIVE
|[1]
2|#4:2|writer|{SHA-256}B93006774CBDD4B299389A03AC3D88C3A76B460D538795BC12718011A909FBA5|ACTIVE
|[1]
---+---------+--------------------+--------------------+--------------------+-------------------Scriptexecutedin0,073000sec(s).Returned3records
orientdb>exit
Batchmode
Thesameexampleaboveisexecutedinbatchmode:
$./console.sh"connectremote:localhost/demoadminadmin;jssvarr=db.query('selectfromouser');print(r);r;exit"
OrientDBconsolev.1.0-SNAPSHOT(build11761)www.orientechnologies.com
Type'help'todisplayallthecommandssupported.
Connectingtodatabase[remote:localhost/demo]withuser'admin'...OK
---+---------+--------------------+--------------------+--------------------+-------------------#|RID|name|password|status|roles
---+---------+--------------------+--------------------+--------------------+-------------------0|#4:0|admin|{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873FC4BB8A81F6F2AB448A918|ACTIVE
|[1]
1|#4:1|reader|{SHA-256}3D0941964AA3EBDCB00CCEF58B1BB399F9F898465E9886D5AEC7F31090A0FB30|ACTIVE
|[1]
2|#4:2|writer|{SHA-256}B93006774CBDD4B299389A03AC3D88C3A76B460D538795BC12718011A909FBA5|ACTIVE
|[1]
---+---------+--------------------+--------------------+--------------------+-------------------Scriptexecutedin0,099000sec(s).Returned3records
Examplesofusage
Insert1000records
orientdb>jsfor(i=0;i<1000;i++){db.query('insertintojstest(label)values("test'+i+'")');}
CreatedocumentsusingwrappedJavaAPI
orientdb>jsnewcom.orientechnologies.orient.core.record.impl.ODocument('Profile').field('name','Luca').save()
Clientsidescriptexecutedin0,426000sec(s).Valuereturnedis:Profile#11:52{name:Luca}v3
EnableServer-sidescripting
Forsecurityreasonsserver-sidescriptingisdisabledbydefaultontheserver.Toenableitchangetheenablefieldto trueinthe
orientdb-server-config.xmlfile:
477
Javascript
<!--SERVERSIDESCRIPTINTERPRETER.WARNING!THISCANBEASECURITYHOLE:ENABLEITONLYIFCLIENTSARETRUSTED,TOTURNONS
ETTHE'ENABLED'PARAMETERTO'true'-->
<handlerclass="com.orientechnologies.orient.server.handler.OServerSideScriptInterpreter">
<parameters>
<parametername="enabled"value="true"/>
</parameters>
</handler>
NOTE:thiswillallowclientstoexecuteanycodeinsidetheserver.Enableitonlyifclientsaretrusted.
478
JavascriptAPI
JavascriptAPI
Thisdriverwrapsthemostcommonusecasesindatabaseusage.AllparametersrequiredbymethodsorconstructorareStrings.This
libraryworksontopofHTTPRESTfulprotocol.
Note:Duetocross-domainXMLHttpRequestrestrictionthisAPIworks,fornow,onlyplacedintheserverdeployment.Touseitwith
cross-sitelookatCross-sitescripting.
Thefullsourcecodeisavailablehere:oriendb-api.js.
Seealso
Javascript-Command
Example
vardatabase=newODatabase('http://localhost:2480/demo');
databaseInfo=database.open();
queryResult=database.query('selectfromAddresswherecity.country.name=\'Italy\'');
if(queryResult["result"].length==0){
commandResult=database.executeCommand('insertintoAddress(street,type)values(\'Viatest1\',\'Tipotest\')');
}else{
commandResult=database.executeCommand('updateAddresssetstreet=\'Viatest1\'wherecity.country.name=\'Italy\'');
}
database.close();
API
ODatabaseobject
ODatabaseobjectrequiresserverURLanddatabasename:
Syntax: newODatabase(http://:/)
Example:
varorientServer=newODatabase('http://localhost:2480/demo');
Oncecreateddatabaseinstanceisreadytobeused.Everymethodreturntheoperationresultwhenitsucceeded,nullelsewhere.
IncaseofnullresultthedatabaseinstancewillhavetheerrormessageobtainablebythegetErrorM essage()method.
Open
M ethodthatconnectstotheserver,itreturnsdatabaseinformationinJSONformat.
BrowserAuthentication
Syntax: <databaseInstance>.open()
Note:Thisimplementationaskstothebrowsertoprovideuserandpassword.
Example:
orientServer=newODatabase('http://localhost:2480/demo');
databaseInfo=orientServer.open();
JavascriptAuthentication
479
JavascriptAPI
Syntax: <databaseInstance>.open(username,userpassword)
Example:
orientServer=newODatabase('http://localhost:2480/demo');
databaseInfo=orientServer.open('admin','admin');
ReturnExample:
{"classes":[
{
"id":0,
"name":"ORole",
"clusters":[3],
"defaultCluster":3,"records":3,
"properties":[
{
"id":0,
"name":"mode",
"type":"BYTE",
"mandatory":false,
"notNull":false,
"min":null,
"max":null,
"indexed":false
},
{
"id":1,
"name":"rules",
"linkedType":"BYTE",
"type":"EMBEDDEDMAP",
"mandatory":false,
"notNull":false,
"min":null,
"max":null,
"indexed":false
}
]},
],
"dataSegments":[
{"id":-1,"name":"default","size":10485760,"filled":1380391,"maxSize":"0","files":"[${STORAGE_PATH}/default.0.od
a]"}
],
"clusters":[
{"id":0,"name":"internal","type":"PHYSICAL","records":4,"size":1048576,"filled":60,"maxSize":"0","files":"[
${STORAGE_PATH}/internal.0.ocl]"},
],
"txSegment":[
{"totalLogs":0,"size":1000000,"filled":0,"maxSize":"50mb","file":"${STORAGE_PATH}/txlog.otx"}
],"users":[
{"name":"admin","roles":"[admin]"},
{"name":"reader","roles":"[reader]"},
{"name":"writer","roles":"[writer]"}
],
"roles":[
{"name":"admin","mode":"ALLOW_ALL_BUT",
"rules":[]
},
{"name":"reader","mode":"DENY_ALL_BUT",
"rules":[{
"name":"database","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.internal","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.orole","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.ouser","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.class.*","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.*","create":false,"read":true,"update":false,"delete":false
480
JavascriptAPI
},{
"name":"database.query","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.command","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.hook.record","create":false,"read":true,"update":false,"delete":false
}]
},
],
"config":{
"values":[
{"name":"dateFormat","value":"yyyy-MM-dd"},
{"name":"dateTimeFormat","value":"yyyy-MM-ddhh:mm:ss"},
{"name":"localeCountry","value":""},
{"name":"localeLanguage","value":"en"},
{"name":"definitionVersion","value":0}
],
"properties":[
]
}
}
Query
M ethodthatexecutesthequery,itreturnsqueryresultsinJSONformat.
Syntax: <databaseInstance>.query(<queryText>,[limit],[fetchPlan])
LimitandfetchPlanareoptional.
SimpleExample:
queryResult=orientServer.query('selectfromAddresswherecity.country.name=\'Italy\'');
ReturnExample:
{"result":[{
"@rid":"12:0","@class":"Address",
"street":"PiazzaNavona,1",
"type":"Residence",
"city":"#13:0"
},{
"@rid":"12:1","@class":"Address",
"street":"PiazzadiSpagna,111",
"type":"Residence",
"city":"#13:0"
}
]
}
FetchedExample:fetchingofallfieldsexcept"type"
queryResult=orientServer.query('selectfromAddresswherecity.country.name=\'Italy\'',null,'*:-1type:0');
ReturnExample1:
481
JavascriptAPI
{"result":[{
"@rid":"12:0","@class":"Address",
"street":"PiazzaNavona,1",
"city":{
"@rid":"13:0","@class":"City",
"name":"Rome",
"country":{
"@rid":"14:0","@class":"Country",
"name":"Italy"
}
}
},{
"@rid":"12:1","@version":1,"@class":"Address",
"street":"PiazzadiSpagna,111",
"city":{
"@rid":"13:0","@class":"City",
"name":"Rome",
"country":{
"@rid":"14:0","@class":"Country",
"name":"Italy"
}
}
}
]
}
FetchedExample:fetchingofallfieldsexcept"city"(Class)
queryResult=orientServer.query('selectfromAddresswherecity.country.name=\'Italy\'',null,'*:-1city:0');
ReturnExample2:
{"result":[{
"@rid":"12:0","@class":"Address",
"street":"PiazzaNavona,1",
"type":"Residence"
},{
"@rid":"12:1","@version":1,"@class":"Address",
"street":"PiazzadiSpagna,111",
"type":"Residence"
}
]
}
FetchedExample:fetchingofallfieldsexcept"country"ofCityclass
queryResult=orientServer.query('selectfromAddresswherecity.country.name=\'Italy\'',null,'*:-1City.country:0');
ReturnExample3:
{"result":[{
"@rid":"12:0","@class":"Address",
"street":"PiazzaNavona,1",
"type":"Residence",
"city":{
"@rid":"13:0","@class":"City",
"name":"Rome"
}
}
]
}
ExecuteCommand
M ethodthatexecutesarbitrarycommands,itreturnscommandresultintextformat.
Syntax: <databaseInstance>.executeCommand(<commandText>)
482
JavascriptAPI
Example1(insert):
commandResult=orientServer.executeCommand('insertintoAddress(street,type)values(\'Viatest1\',\'Tipotest\')');
ReturnExample1(createdrecord):
Address@14:177{street:Viatest1,type:Tipotest}
Example2(delete):
commandResult=orientServer.executeCommand('deletefromAddresswherestreet=\'Viatest1\'andtype=\'Tipotest\'');
ReturnExample2(recordsdeleted):
{"value":5}
Note:Deleteexampleworksalsowithupdatecommand
Load
M ethodthatloadsarecordfromtherecordID,itreturnstherecordinformationsinJSONformat.
Syntax:`.load(,[fetchPlan]);
SimpleExample:
queryResult=orientServer.load('12:0');
ReturnExample:
{
"@rid":"12:0","@class":"Address",
"street":"PiazzaNavona,1",
"type":"Residence",
"city":"#13:0"
}
FetchedExample:allfieldsfetchedexcept"type"
queryResult=orientServer.load('12:0','*:-1type:0');
ReturnExample1:
{
"@rid":"12:0","@class":"Address",
"street":"PiazzaNavona,1",
"city":{
"@rid":"13:0",
"name":"Rome",
"country":{
"@rid":"14:0",
"name":"Italy"
}
}
}
ClassInfo
M ethodthatretrievesinformationofaclass,itreturnstheclassinformationsinJSONformat.
483
JavascriptAPI
Syntax: <databaseInstance>.classInfo(<className>)
Example:
addressInfo=orientServer.classInfo('Address');
ReturnExample:
{"result":[{
"@rid":"14:0","@class":"Address",
"street":"WA98073-9717",
"type":"Headquarter",
"city":"#12:1"
},{
"@rid":"14:1","@class":"Address",
"street":"WA98073-9717",
"type":"Headquarter",
"city":"#12:1"
}
]
}
BrowseCluster
M ethodthatretrievesinformationofacluster,itreturnstheclassinformationsinJSONformat.
Syntax: <databaseInstance>.browseCluster(<className>)
Example:
addressInfo=orientServer.browseCluster('Address');
ReturnExample:
{"result":[{
"@rid":"14:0","@class":"Address",
"street":"WA98073-9717",
"type":"Headquarter",
"city":"#12:1"
},{
"@rid":"14:1","@class":"Address",
"street":"WA98073-9717",
"type":"Headquarter",
"city":"#12:1"
}
]
}
ServerInformation
M ethodthatretrievesserverinformations,itreturnstheserverinformationsinJSONformat.
Note:Serverinformationneedsrootusernameandpassword.
Syntax: <databaseInstance>.serverInfo()
Example:
serverInfo=orientServer.serverInfo();
ReturnExample:
484
JavascriptAPI
{
"connections":[{
"id":"64",
"id":"64",
"remoteAddress":"127.0.0.1:51459",
"db":"-",
"user":"-",
"protocol":"HTTP-DB",
"totalRequests":"1",
"commandInfo":"Serverstatus",
"commandDetail":"-",
"lastCommandOn":"2010-12-2312:53:38",
"lastCommandInfo":"-",
"lastCommandDetail":"-",
"lastExecutionTime":"0",
"totalWorkingTime":"0",
"connectedOn":"2010-12-2312:53:38"
}],
"dbs":[{
"db":"demo",
"user":"admin",
"open":"open",
"storage":"OStorageLocal"
}],
"storages":[{
"name":"temp",
"type":"OStorageMemory",
"path":"",
"activeUsers":"0"
},{
"name":"demo",
"type":"OStorageLocal",
"path":"/home/molino/Projects/Orient/releases/0.9.25-SNAPSHOT/db/databases/demo",
"activeUsers":"1"
}],
"properties":[
{"name":"server.cache.staticResources","value":"false"
},
{"name":"log.console.level","value":"info"
},
{"name":"log.file.level","value":"fine"
}
]
}
Schema
M ethodthatretrievesdatabaseSchema,itreturnsanarrayofclasses(JSONparsedObject).
Syntax: <databaseInstance>.schema()
Example:
schemaInfo=orientServer.schema();
ReturnExample:
485
JavascriptAPI
{"classes":[
{
"id":0,
"name":"ORole",
"clusters":[3],
"defaultCluster":3,"records":3,
"properties":[
{
"id":0,
"name":"mode",
"type":"BYTE",
"mandatory":false,
"notNull":false,
"min":null,
"max":null,
"indexed":false
},
{
"id":1,
"name":"rules",
"linkedType":"BYTE",
"type":"EMBEDDEDMAP",
"mandatory":false,
"notNull":false,
"min":null,
"max":null,
"indexed":false
}
]},
]
}
getClass()
Returnaschemaclassfromtheschema.
Syntax: <databaseInstance>.getClass(<className>)
Example:
varcustomerClass=orientServer.getClass('Customer');
ReturnExample:
{
"id":0,
"name":"Customer",
"clusters":[3],
"defaultCluster":3,"records":3,
"properties":[
{
"id":0,
"name":"name",
"type":"STRING",
},
{
"id":1,
"name":"surname",
"type":"STRING",
}
]
}
Security
Roles
M ethodthatretrievesdatabaseSecurityRoles,itreturnsanarrayofRoles(JSONparsedObject).
486
JavascriptAPI
Syntax: <databaseInstance>.securityRoles()
Example:
roles=orientServer.securityRoles();
ReturnExample:
{"roles":[
{"name":"admin","mode":"ALLOW_ALL_BUT",
"rules":[]
},
{"name":"reader","mode":"DENY_ALL_BUT",
"rules":[{
"name":"database","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.internal","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.orole","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.ouser","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.class.*","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.cluster.*","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.query","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.command","create":false,"read":true,"update":false,"delete":false
},{
"name":"database.hook.record","create":false,"read":true,"update":false,"delete":false
}]
}
]
}
Users
M ethodthatretrievesdatabaseSecurityUsers,itreturnsanarrayofUsers(JSONparsedObject).
Syntax: <databaseInstance>.securityUsers()
Example:
users=orientServer.securityUsers();
ReturnExample:
{"users":[
{"name":"admin","roles":"[admin]"},
{"name":"reader","roles":"[reader]"},
{"name":"writer","roles":"[writer]"}
]
}
close()
M ethodthatdisconnectsfromtheserver.
Syntax: <databaseInstance>.close()
Example:
orientServer.close();
ChangeserverURL
487
JavascriptAPI
M ethodthatchangesserverURLinthedatabaseinstance.
You'llneedtocalltheopenmethodtoreconnecttothenewserver.
Syntax: <databaseInstance>.setDatabaseUrl(<newDatabaseUrl>)
Example:
orientServer.setDatabaseUrl('http://localhost:3040')
Changedatabasename
M ethodthatchangesdatabasenameinthedatabaseinstance.
You'llneedtocalltheopenmethodtoreconnecttothenewdatabase.
Syntax: <databaseInstance>.setDatabaseName(<newDatabaseName>)
Example:
orientServer.setDatabaseName('demo2');
Settingreturntype
ThisAPIallowsyoutochosethereturntype,JavascriptObjectorJSONplaintext.DefaultreturnisJavascriptObject.
Important:thejavascriptobjectisnotalwaystheevaluationofJSONplaintext:foreachdocument(identifiedbyitsRecordID)the
JSONfilecontainsonlyoneexpandedobject,allotherreferencesarejustitsRecordIDasString,sotheAPIwillreconstructthereal
structurebyre-linkingallreferencestothematchingjavascriptobject.
Syntax: orientServer.setEvalResponse(<boolean>)
Examples:
orientServer.setEvalResponse(true);
ReturntypeswillbeJavascriptObjects.
orientServer.setEvalResponse(false);
ReturntypeswillbeJSONplaintext.
Cross-sitescripting
ToinvokeOrientDBcross-siteyoucanusethe querycommandinGETandtheJSONPprotocol.Example:
<scripttype="text/javascript"src='http://127.0.0.1:2480/query/database/sql/select+from+XXXX?jsoncallback=vardatajson='></sc
ript>
Thiswillputtheresultofthequery selectfromXXXX</code>intothe<code>datajson</code>variable.
Errors
Incaseoferrorstheerrormessagewillbestoredinsidethedatabaseinstance,retrievablebygetErrorM essage()method.
Syntax: <databaseInstance>.getErrorMessage()
Example:
if(orientServer.getErrorMessage()!=null){
//writeerrormessage
}
488
ScalaAPI
ScalaAPI
OrientDBisaNoSQLdatabasewriteninJava,wecanuseitinscalaeasily.LookalsoatScalautilitiesandtestsprojectforScalahigh
levelclassesbuiltontopofOrientDB.
usingSBT
Usethefollowingconfiguration:
fork:=true
Javamethodinvocationproblems
UsuallythemainproblemsarerelatedtocallingconventionsbetweenScalaandJava.
Parameters
Becarefultopassparameterstomethodswithvarargslike db.query(...).Youneedtoconvertittojava'srepeatedargscorrectly.
Lookattheselinks:
http://stackoverflow.com/questions/3022865/calling-java-vararg-method-from-scala-with-primitives
http://stackoverflow.com/questions/1008783/using-varargs-from-scala
http://stackoverflow.com/questions/3856536/how-to-pass-a-string-scala-vararg-to-a-java-method-using-scala-2-8
Collections
Youcanonlyusejavacollectionswhendefinepojos.Ifyouusescalacollections,theycanbepersisted,butcan'tbequeried.
This'snotaproblem,ifyouimported:
importscala.collection.JavaConverters._
importscala.collection.JavaConversions._
Youdon'tneedtoconvertJavaandScalacollectionsmanually(evendon'tneedtoinvoke .asJavaor .asScala)Youcantreatthese
javacollectionsasscala's.
models.scala
489
ScalaAPI
packagemodels
importjavax.persistence.{Version,Id}
classUser{
@Idvarid:String=_
varname:String=_
varaddresses:java.util.List[Address]=newjava.util.ArrayList()
@Versionvarversion:String=_
overridedeftoString="User:"+this.id+",name:"+this.name+",addresses:"+this.addresses
}
classAddress{
varcity:String=_
varstreet:String=_
overridedeftoString="Address:"+this.city+","+this.street
}
classQuestion{
@Idvarid:String=_
vartitle:String=_
varuser:User=_
@Versionvarversion:String=_
overridedeftoString="Question:"+this.id+",title:"+this.title+",belongs:"+user.name
}
test.scala
packagemodels
importcom.orientechnologies.orient.core.id.ORecordId
importcom.orientechnologies.orient.core.sql.query.OSQLSynchQuery
importscala.collection.JavaConverters._
importscala.collection.JavaConversions._
importcom.orientechnologies.orient.`object`.db.{OObjectDatabaseTx,OObjectDatabasePool}
importcom.orientechnologies.orient.core.db.`object`.ODatabaseObject
objectTest{
implicitdefdbWrapper(db:OObjectDatabaseTx)=new{
defqueryBySql[T](sql:String,params:AnyRef*):List[T]={
valparams4java=params.toArray
valresults:java.util.List[T]=db.query(newOSQLSynchQuery[T](sql),params4java:_*)
results.asScala.toList
}
}
defmain(args:Array[String])={
//~~~~~~~~~~~~~createdb~~~~~~~~~~~~~~~~~~~
varuri:String="plocal:test/orientdb"
vardb:OObjectDatabaseTx=newOObjectDatabaseTx(uri)
if(!db.exists){
db.create()
}else{
db.open("admin","admin")
}
//~~~~~~~~~~~~registermodels~~~~~~~~~~~~~~~~
db.getEntityManager.registerEntityClasses("models")
//~~~~~~~~~~~~~createsomedata~~~~~~~~~~~~~~~~
varuser:User=newUser
user.name="aaa"
db.save(user)
varaddress1=newAddress
address1.city="NY"
address1.street="road1"
varaddress2=newAddress
address2.city="ST"
490
ScalaAPI
address2.street="road2"
user.addresses+=address1
user.addresses+=address2
db.save(user)
varq1=newQuestion
q1.title="Howtouseorientdbinscala?"
q1.user=user
db.save(q1)
varq2=newQuestion
q2.title="Showmeademo"
q2.user=user
db.save(q2)
//~~~~~~~~~~~~~~~~countthem~~~~~~~~~~~~~~~~
valuserCount=db.countClass(classOf[User])
println("Usercount:"+userCount)
valquestionCount=db.countClass(classOf[Question])
println("Questioncount:"+questionCount)
//~~~~~~~~~~~~~~~~~getallusers~~~~~~~~~~~~
valusers=db.queryBySql[User]("selectfromUser")
for(user<-users){
println("-user:"+user)
}
//~~~~~~~~~~~~~~~~~~getthefirstuser~~~~~~~~
valfirstUser=db.queryBySql[User]("selectfromUserlimit1").head
println("Firstuser:"+firstUser)
//querybyid
valuserById=db.queryBySql[User]("selectfromUserwhere@rid=?",newORecordId(user.id))
println("Userbyid:"+userById)
//querybyfield
valuserByField=db.queryBySql[User]("selectfromUserwherename=?",user.name)
println("Userbyfield:"+userByField)
//querybycity
valuserByCity=db.queryBySql[User]("selectfromUserwhereaddressescontains(city=?)","NY")
println("Userbycity:"+userByCity)
//queryquestionsoftheuser
valquestions=db.queryBySql[Question]("selectfromQuestionwhereuser=?",user)
for(q<-questions){
println("-question:"+q)
}
db.drop()
db.close()
}
}
491
HTTPAPI
HTTPProtocol
OrientDBRESTfulHTTPprotocolallowstotalkwithaOrientDBServerinstanceusingtheHTTPprotocolandJSON.OrientDB
supportsalsoahighlyoptimizedBinaryprotocolforsuperiorperformances.
AvailableCommands
allocation
DB'sdefragmentation
batch
Batchofcommands
class
Operationsonschema
classes
cluster
Operationson
clusters
command
Executescommands
connect
Createthesession
database
Informationabout
database
disconnect
Disconnectsession
document
OperationsondocumentsbyRID
GET-HEAD-POST-PUTDELETE-PATCH
documentbyclass
Operationsondocuments
byClass
export
Exportsadatabase
function
Executesaserver-side
function
index
Operationsonindexes
listDatabases
Availabledatabases
property
Operationsonschema
properties
query
Query
server
Informationabouttheserver
HTTPMethods
ThisprotocolusesthefourmethodsoftheHTTPprotocol:
GET,toretrievevaluesfromthedatabase.It'sidempotentthatmeansnochangestothedatabasehappen.RememberthatinIE6
theURLcanbemaximumof2,083characters.OtherbrowserssupportslongerURLs,butifyouwanttostaycompatiblewithall
limitto2,083characters
POS T,toinsertvaluesintothedatabase
PUT,tochangevaluesintothedatabase
DELETE,todeletevaluesfromthedatabase
WhenusingPOSTandPUTthefollowingareimportantwhenpreparingthecontentsofthepostmessage:
Alwayshavethecontenttypesetto“application/json”or"application/xml"
WheredataordatastructureisinvolvedthecontentisinJSONformat
ForOrientDBSQLorGremlinthecontentitselfisjusttext
Headers
Alltherequestsmusthavethese2headers:
'Accept-Encoding':'gzip,deflate'
'Content-Length':<content-length>
`
Wherethe <content-length>isthelengthoftherequest'sbody.
Syntax
TheRESTAPIisveryflexible,withthefollowingfeatures:
492
HTTPAPI
DatareturnedisinJSONformat
JSONPcallbackissupported
Supportforhttpandhttpsconnections
TheAPIitselfiscaseinsensitive
APIcanjustbeusedasawrappertoretrieve(andcontrol)datathroughrequestswritteninOrientDBSQLorGremlin
Youcanavoidusing #forRecordIDsinURLs,ifyouprefer.Justdropthe #fromtheURLanditwillstillwork
TheRESTsyntaxusedisthesameforallthefourHTTPmethods:
Syntax: http://<server>:<port>/<command>/[<database>/<arguments>]
ResultsarealwaysinJSONformat.Supportfor'document'objecttypesisthroughtheuseoftheattribute @type:'d'.Thisalso
applieswhenusinginnerdocumentobjects.Example:
{
"@type":"d",
"Name":"Test",
"Data":{"@type":"d",
"value":0},
"@class":"SimpleEntity"
}
JSONPisalsosupportedbyaddingacallbackparametertotherequest(containingthecallbackfunctionname).
Syntax: http://<server>:<port>/<command>/[<database>/<arguments>]?callback=<callbackFunctionName>
Commandsaredividedintwomaincategories:
Servercommands,suchastoknowserverstatisticsandtocreateanewdatabase
Databasecommands,allthecommandsagainstadatabase
Authenticationandsecurity
Allthecommands(buttheDisconnectneedavalidauthenticationbeforetogetexecuted.TheOrientDBServerchecksifthe
AuthorizationHTTPheaderispresent,otherwiseanswerswitharequestofauthentication(HTTPerrorcode:401).
TheHTTPclient(ortheInternetBrowser)mustsenduserandpasswordusingtheHTTPBaseauthentication.Passwordisencoded
usingBase64algorithm.PleasenotethatifyouwanttoencryptthepasswordusingasafemodetakeinconsiderationtouseSSL
connections.
Servercommandsusetherealm"OrientDBServer",whilethedatabasecommandsusearealmperdatabaseinthisform: "OrientDBdb<database>",where <database>isthedatabasename.InthiswaytheBrowser/HTTPclientcanreuseuserandpasswordinserted
multipletimesuntilthesessionexpiresorthe"Disconnect"iscalled.
Onfirstcall(orwhenthesessionisexpiredandanewauthenticationisrequired),OrientDBreturnstheOSESSIONIDparameterin
response'sHTTPheader.OnfurthercallstheclientshouldpassthisOSESSIONIDheaderintherequestsandOrientDBwillskipthe
authenticationbecauseasessionisalive.Bydefaultsessionsexpireafter300seconds(5minutes),butyoucanchangethisconfiguration
bysettingtheglobalsetting: network.http.sessionExpireTimeout
JSONdatatypehandlingandSchema-lessmode
SinceOrientDBsupportsalsoschema-less/hybridmodeshowtomanagetypes?JSONdoesn'tsupportallthetypesOrientDBhas,so
howcanIpasstherighttypewhenit'snotdefinedintheschema?
Theanswerisusingthespecialfield"@fieldTypes"asstringcontainingallthefieldtypesseparatedbycomma.Example:
{"@class":"Account","date":1350426789,"amount":100.34,
"@fieldTypes":"date=t,amount=c"}
493
HTTPAPI
Thesupportedspecialtypesare:
'f'forfloat
'c'fordecimal
'l'forlong
'd'fordouble
'b'forbyteandbinary
'a'fordate
't'fordatetime
's'forshort
'e'forSet,becausearraysandListareserializedasarrayslike[3,4,5]
'x'forlinks
'n'forlinksets
'z'forlinklist
'm'forlinkmap
'g'forlinkbag
'u'forcustom
Keep-Alive
Attention:OrientDBHTTPAPIutilizesKeep-Alivefeatureforbetterperformance:theTCP/IPsocketiskeptopenavoidingthe
creationofanewoneforeachcommand.Ifyouneedtore-authenticate,openanewconnectionavoidingtoreusethealreadyopenone.
Toforceclosingput"Connection:close"intherequestheader.
HTTPcommands
Connect
GET-Connect
Connecttoaremoteserverusingbasicauthentication.
Syntax: http://<server>:[<port>]/connect/<database>
Example
HTTPGETrequest: http://localhost:2480/connect/demoHTTPresponse:204ifok,otherwise401.
Database
GET-Database
HTTPGETrequest: http://localhost:2480/database/demoHTTPresponse:
{
"server":{
"version":"1.1.0-SNAPSHOT",
"osName":"Windows7",
"osVersion":"6.1",
"osArch":"amd64",
"javaVendor":"OracleCorporation",
"javaVersion":"23.0-b21"
},"classes":[],
...
}
494
HTTPAPI
POST-Database
Createanewdatabase.
Syntax: http://<server>:[<port>]/database/<database>/<type>
HTTPPOSTrequest: http://localhost:2480/database/demo/plocal
HTTPresponse: {"classes":[],"clusters":[],"users":[],"roles":[],"config":[],"properties":{}}
Class
GET-Class
Getsinformationsaboutrequestedclass.
Syntax: http://<server>:[<port>]/class/<database>/<class-name>
HTTPresponse:
{"class":{
"name":"<class-name>"
"properties":[
{"name":<property-name>,
"type":<property-type>,
"mandatory":<mandatory>,
"notNull":<not-null>,
"min":<min>,
"max":<max>
}
]
}
}
Formoreinformationaboutpropertieslookatthesupportedtypes,orseetheSQLCreatepropertypagefortextvaluestobeused
whengettingorpostingclasscommands
Example
HTTPGETrequest: http://localhost:2480/class/demo/OFunctionHTTPresponse:
495
HTTPAPI
{
"name":"OFunction",
"superClass":"",
"alias":null,
"abstract":false,
"strictmode":false,
"clusters":[
7
],
"defaultCluster":7,
"records":0,
"properties":[
{
"name":"language",
"type":"STRING",
"mandatory":false,
"readonly":false,
"notNull":false,
"min":null,
"max":null,
"collate":"default"
},
{
"name":"name",
"type":"STRING",
"mandatory":false,
"readonly":false,
"notNull":false,
"min":null,
"max":null,
"collate":"default"
},
{
"name":"idempotent",
"type":"BOOLEAN",
"mandatory":false,
"readonly":false,
"notNull":false,
"min":null,
"max":null,
"collate":"default"
},
{
"name":"code",
"type":"STRING",
"mandatory":false,
"readonly":false,
"notNull":false,
"min":null,
"max":null,
"collate":"default"
},
{
"name":"parameters",
"linkedType":"STRING",
"type":"EMBEDDEDLIST",
"mandatory":false,
"readonly":false,
"notNull":false,
"min":null,
"max":null,
"collate":"default"
}
]
}
POST-Class
Createanewclasswheretheschemaofthevertexesoredgesisknown.OrientDBallows(encourages)classestobederivedfromother
classdefinitions–thisisachievedbyusingtheCOM M ANDcallwithanOrientDBSQLcommand.Returnstheidofthenewclass
created.
Syntax: http://<server>:[<port>]/class/<database>/<class-name>
496
HTTPAPI
HTTPPOSTrequest: http://localhost:2480/class/demo/Address2HTTPresponse: 9
Property
POST-Property
Createoneormorepropertiesintoagivenclass.Returnsthenumberofpropertiesoftheclass.
Singlepropertycreation
Syntax: http://<server>:[<port>]/property/<database>/<class-name>/<property-name>/[<property-type>]
Createsapropertynamed <property-name>in <class-name>.If <property-type>isnotspecifiedthepropertywillbecreatedas
STRING.
Multiplepropertycreation
Syntax: http://<server>:[<port>]/property/<database>/<class-name>/
RequiresaJSONdocumentpostrequestcontent:
{
"fieldName":{
"propertyType":"<property-type>"
},
"fieldName":{
"propertyType":"LINK",
"linkedClass":"<linked-class>"
},
"fieldName":{
"propertyType":"<LINKMAP|LINKLIST|LINKSET>",
"linkedClass":"<linked-class>"
},
"fieldName":{
"propertyType":"<LINKMAP|LINKLIST|LINKSET>",
"linkedType":"<linked-type>"
}
}
Example
Singleproperty:
StringPropertyExample:HTTPPOSTrequest: http://localhost:2480/class/demo/simpleFieldHTTPresponse: 1
TypePropertyExample:HTTPPOSTrequest: http://localhost:2480/class/demo/dateField/DATEHTTPresponse: 1
LinkPropertyExample:HTTPPOSTrequest: http://localhost:2480/class/demo/linkField/LINK/PersonHTTPresponse: 1
Multipleproperties:HTTPPOSTrequest: http://localhost:2480/class/demo/HTTPPOSTcontent:
497
HTTPAPI
{
"name":{
"propertyType":"STRING"
},
"father":{
"propertyType":"LINK",
"linkedClass":"Person"
},
"addresses":{
"propertyType":"LINKMAP",
"linkedClass":"Address"
},
"examsRatings":{
"propertyType":"LINKMAP",
"linkedType":"INTEGER"
}
"events":{
"propertyType":"LINKLIST",
"linkedType":"DATE"
}
"family":{
"propertyType":"LINKLIST",
"linkedClass":"Person"
}
...
HTTPresponse: 6
Cluster
GET-Cluster
Wheretheprimaryusageisadocumentdb,orwherethedeveloperwantstooptimiseretrievalusingtheclusteringofthedatabase,use
theCLUSTERcommandtobrowsetherecordsoftherequestedcluster.
Syntax: http://<server>:[<port>]/cluster/<database>/<cluster-name>/
Where <limit>isoptionalandtellsthemaximumofrecordstoload.Defaultis20.
Example
HTTPGETrequest: http://localhost:2480/cluster/demo/Address
HTTPresponse:
{"schema":{
"id":5,
"name":"Address"
},
"result":[{
"_id":"11:0",
"_ver":0,
"@class":"Address",
"type":"Residence",
"street":"PiazzaNavona,1",
"city":"12:0"
}
...
Command
POST-Command
Executeacommandagainstthedatabase.Returnstherecordsaffectedorthelistofrecordsforqueries.CommandexecutedviaPOSTcan
benon-idempotent(lookatQuery).
498
HTTPAPI
Syntax: http://<server>:[<port>]/command/<database>/<language>[/<command-text>[/limit[/<fetchPlan>]]]
Thecontentcanbe <command-text>orstartingfromv2.2ajsoncontainingthecommandandparameters:
byparametername: {"command":<command-text>,"parameters":{"<param-name>":<param-value>}}
byparameterposition: {"command":<command-text>,"parameters":[<param-value>]}
Where:
<language>isthenameofthelanguagebetweenthosesupported.OrientDBdistributioncomeswith"sql"andGraphDB
distributionhasboth"sql"and"gremlin"
command-textisthetextcontainingthecommandtoexecute
limitisthemaximumnumberofrecordtoreturn.Optional,defaultis20
fetchPlanisthefetchingstrategytouse.FormoreinformationlookatFetchingStrategies.Optional,defaultis*:1(1depthlevel
only)
Thecommand-textcanappearineithertheURLorthecontentofthePOSTtransmission.Wherethecommand-textisincludedinthe
URL,itmustbeencodedaspernormalURLencoding.BydefaulttheresultisreturnedinJSON.TohavetheresultinCSV,pass
"Accept:text/csv"inHTTPRequest.
Startingfromv2.2,theHTTPpayloadcanbeaJSONwithbothcommandtoexecuteandparameters.Example:
Executeaquerypassingparametersbyname:
{
"command":"selectfromVwherename=:nameandcity=:city",
"parameters":{
"name":"Luca",
"city":"Rome"
}
}
Executeaquerypassingparametersbyposition:
{
"command":"selectfromVwherename=?andcity=?",
"parameters":["Luca","Rome"]
}
ReadtheSQLsectionortheGremlinintroductionforthetypeofcommands.
Example
HTTPPOSTrequest: http://localhost:2480/command/demo/sqlcontent: updateProfilesetonline=false
HTTPresponse: 10
Orthesame:
HTTPPOSTrequest: http://localhost:2480/command/demo/sql/updateProfilesetonline=false
HTTPresponse: 10
ExtracttheuserlistinCS Vformatusingcurl
curl--useradmin:admin--header"Accept:text/csv"-d"selectfromouser""http://localhost:2480/command/GratefulDeadConcerts
/sql"
Batch
POST-Batch
499
HTTPAPI
Executesabatchofoperationsinasinglecall.Thisisusefultoreducenetworklatencyissuingmultiplecommandsasmultiplerequests.
Batchcommandsupportstransactionsaswell.
Syntax: http://<server>:[<port>]/batch/<database>
Content:{"transaction":,"operations":[{"type":""}*]}
Returns:theresultoflastoperation.
Where:typecanbe:
'c'forcreate,'record'fieldisexpected.
'u'forupdate,'record'fieldisexpected.
'd'fordelete.The'@rid'fieldonlyisneeded.
'cmd'forcommands(Sincev1.6).Theexpectedfieldsare:
'language',betweenthosesupported(sql,gremlin,script,etc.)
'command'asthetextofthecommandtoexecute
'script'forscripts(Sincev1.6).Theexpectedfieldsare:
'language',betweenthelanguageinstalledintheJVM .Javascriptisthedefaultone,butyoucanalsouseSQL(seebelow)
'script'asthetextofthescripttoexecute
Example
{"transaction":true,
"operations":[
{"type":"u",
"record":{
"@rid":"#14:122",
"name":"Luca",
"vehicle":"Car"
}
},{
"type":"d",
"record":{
"@rid":"#14:100"
}
},{
"type":"c",
"record":{
"@class":"City",
"name":"Venice"
}
},{
"type":"cmd",
"language":"sql",
"command":"createedgeFriendfrom#10:33to#11:33"
},{
"type":"script",
"language":"javascript",
"script":"orient.getGraph().createVertex('class:Account')"
}
]
}
SQLbatch
{"transaction":true,
"operations":[
{
"type":"script",
"language":"sql",
"script":["LETaccount=CREATEVERTEXAccountSETname='Luke'",
"LETcity=SELECTFROMCityWHEREname='London'",
"CREATEEDGELivesFROM$accountTO$cityRETRY100"]
}
]
}
500
HTTPAPI
Function
POSTandGET-Function
Executesaserver-sidefunctionagainstthedatabase.ReturnstheresultofthefunctionthatcanbeastringoraJSONcontainingthe
document(s)returned.
ThedifferencebetweenGETandPOSTmethodcallsareifthefunctionhasbeendeclaredasidempotent.Inthiscasecanbecalledalso
byGET,otherwiseonlyPOSTisaccepted.
Syntax: http://<server>:[<port>]/function/<database>/<name>[/<argument>*]<server>
Where
<name>isthenameofthefunction
<argument>,optional,aretheargumentstopasstothefunction.Theyarepassedbyposition.
Creationoffunctions,whennotusingtheJavaAPI,canbedonethroughtheStudioineitherOrientDBSQLorJava–seetheOrientDB
Functionspage.
Example
HTTPPOSTrequest: http://localhost:2480/function/demo/sum/3/5
HTTPresponse: 8.0
Database
GET-Database
Retrievealltheinformationaboutadatabase.
Syntax: http://<server>:[<port>]/database/<database>
Example
HTTPGETrequest: http://localhost:2480/database/demo
HTTPresponse:
{"classes":[
{
"id":0,
"name":"ORole",
"clusters":[3],
"defaultCluster":3,"records":0},
{
"id":1,
"name":"OUser",
"clusters":[4],
"defaultCluster":4,"records":0},
{
...
POST-Database
Createanewdatabase.Requiresadditionalauthenticationtotheserver.
Syntaxfortheurl`http://:
storagecanbe
'plocal'fordisk-baseddatabase
'memory'forinmemoryonlydatabase.
501
HTTPAPI
type,isoptional,andcanbedocumentorgraph.Bydefaultisadocument.
Example
HTTPPOSTrequest: http://localhost:2480/database/demo2/localHTTPresponse:
{"classes":[
{
"id":0,
"name":"ORole",
"clusters":[3],
"defaultCluster":3,"records":0},
{
"id":1,
"name":"OUser",
"clusters":[4],
"defaultCluster":4,"records":0},
{
...
DELETE-Database
Dropadatabase.Requiresadditionalauthenticationtotheserver.
Syntax: http://<server>:[<port>]/database/<databaseName>
Where:
databaseNameisthenameofdatabase
Example
HTTPDELETErequest: http://localhost:2480/database/demo2HTTPresponsecode204
Export
GET-Export
ExportsagzipfilethatcontainsthedatabaseJSONexport.
Syntax:http://:[]/export/
HTTPGETrequest: http://localhost:2480/export/demo2HTTPresponse:demo2.gzipfile
Import
POST-Import
ImportsadatabasefromanuploadedJSONtextfile.
Syntax: http://<server>:[<port>]/import/<database>
Important:Connectrequired:theconnectionwiththeselecteddatabasemustbealreadyestablished
Example
HTTPPOSTrequest: http://localhost:2480/import/HTTPresponse:returnsaJSONobjectcontainingtheresulttextSuccess:
{
"responseText":"Databaseimportedcorrectly"
}
502
HTTPAPI
_Fail::
{
"responseText":"Errormessage"
}
ListDatabases
GET-ListDatabases
Retrievestheavailabledatabases.
Syntax: http://<server>:<port>/listDatabases
TolettotheStudiotodisplaythedatabaselistbydefaultthepermissiontolistthedatabaseisassignedtoguest.Removethis
permissionifyoudon'twantanonymoususercandisplayit.
FormoredetailsseeServerResources
Exampleofconfigurationof"guest"serveruser:a15b5e6bb7d06bd5d6c35db97e51400b
Example
HTTPGETrequest: http://localhost:2480/listDatabasesHTTPresponse:
{
"@type":"d","@version":0,
"databases":["demo","temp"]
}
Disconnect
GET-Disconnect
Syntax: http://<server>:[<port>]/disconnect
Example
HTTPGETrequest: http://localhost:2480/disconnectHTTPresponse:empty.
Document
GET-Document
Thisisakeywaytoretrievedatafromthedatabase,especiallywhencombinedwitha <fetchplan>.Whereasingleresultisrequired
thentheRIDcanbeusedtoretrievethatsingledocument.
Syntax: http://<server>:[<port>]/document/<database>/<record-id>[/<fetchPlan>]
Where:
<record-id>SeeConcepts:RecordID
<fetchPlan>Optional,isthefetchplanused.0meanstherootrecord,-1infinitedepth,positivenumbersisthedepthlevel.Look
atFetchingStrategiesformoreinformation.
Example
HTTPGETrequest: http://localhost:2480/document/demo/9:0
503
HTTPAPI
HTTPresponsecanbe:
HTTPCode200,withthedocumentinJSONformatinthepayload,suchas:
{
"_id":"9:0",
"_ver":2,
"@class":"Profile",
"nick":"GGaribaldi",
"followings":[],
"followers":[],
"name":"Giuseppe",
"surname":"Garibaldi",
"location":"11:0",
"invitedBy":null,
"sex":"male",
"online":true
}
HTTPCode404,ifthedocumentwasnotfound
Theexampleabovecanbeextendedtoreturnalltheedgesandverticesbeneath#9:0
HTTPGETrequest: http://localhost:2480/document/demo/9:0/*:-1
HEAD-Document
Checkifadocumentexists
Syntax: http://<server>:[<port>]/document/<database>/<record-id>
Where:
<record-id>SeeConcepts:RecordID
Example
HTTPHEADrequest: http://localhost:2480/document/demo/9:0
HTTPresponsecanbe:
HTTPCode204,ifthedocumentexists
HTTPCode404,ifthedocumentwasnotfound
POST-Document
Createanewdocument.Returnsthedocumentwiththenew@ridassigned.Before1.4.xthereturnwasthe@ridcontentonly.
Syntax: http://<server>:[<port>]/document/<database>
Example
HTTPPOSTrequest: http://localhost:2480/document/demo
content:
{
"@class":"Profile",
"nick":"GGaribaldi",
"followings":[],
"followers":[],
"name":"Giuseppe",
"surname":"Garibaldi",
"location":"11:0",
"invitedBy":null,
"sex":"male",
"online":true
}
504
HTTPAPI
HTTPresponse,asthedocumentcreatedwiththeassignedRecordIDas@rid:
{
"@rid":"#11:4456",
"@class":"Profile",
"nick":"GGaribaldi",
"followings":[],
"followers":[],
"name":"Giuseppe",
"surname":"Garibaldi",
"location":"11:0",
"invitedBy":null,
"sex":"male",
"online":true
}
PUT-Document
Updateadocument.Remembertoalwayspasstheversiontoupdate.Thispreventtoupdatedocumentschangedbyotherusers
(M VCC).
Syntax: http://<server>:[<port>]/document/<database>[/<record-id>][?updateMode=full|partial]Where:
updateModecanbefull(default)orpartial.Withpartialmodeonlythedeltaofchangesissent,otherwisetheentiredocumentis
replaced(fullmode)
Example
HTTPPUTrequest: http://localhost:2480/document/demo/9:0
content:
{
"@class":"Profile",
"@version":3,
"nick":"GGaribaldi",
"followings":[],
"followers":[],
"name":"Giuseppe",
"online":true
}
HTTPresponse,astheupdateddocumentwiththeupdated@versionfield(Sincev1.6):
content:
{
"@class":"Profile",
"@version":4,
"nick":"GGaribaldi",
"followings":[],
"followers":[],
"name":"Giuseppe",
"online":true
}
PATCH-Document
Updateadocumentwithonlythedifferencetoapply.Remembertoalwayspasstheversiontoupdate.Thispreventtoupdate
documentschangedbyotherusers(M VCC).
Syntax: http://<server>:[<port>]/document/<database>[/<record-id>]Where:
Example
Thisisthedocument9:0beforetoapplythepatch:
505
HTTPAPI
{
"@class":"Profile",
"@version":4,
"name":"Jay",
"amount":10000
}
HTTPPATCHrequest: http://localhost:2480/document/demo/9:0
content:
{
"@class":"Profile",
"@version":4,
"amount":20000
}
HTTPresponse,astheupdateddocumentwiththeupdated@versionfield(Sincev1.6):
content:
{
"@class":"Profile",
"@version":5,
"name":"Jay",
"amount":20000
}
DELETE-Document
Deleteadocument.
Syntax: http://<server>:[<port>]/document/<database>/<record-id>
Example
HTTPDELETErequest: http://localhost:2480/document/demo/9:0
HTTPresponse:empty
DocumentByClass
GETDocumentbyClass
Retrieveadocumentbyclusternameandrecordposition.
Syntax: http://<server>:[<port>]/documentbyclass/<database>/<class-name>/<record-position>[/fetchPlan]
Where:
<class-name>isthenameofthedocument'sclass
<record-position>istheabsolutepositionoftherecordinsidetheclass'defaultcluster
<fetchPlan>Optional,isthefetchplanused.0meanstherootrecord,-1infinitedepth,positivenumbersisthedepthlevel.Look
atFetchingStrategiesformoreinformation.
Example
HTTPGETrequest: http://localhost:2480/documentbyclass/demo/Profile/0
HTTPresponse:
506
HTTPAPI
{
"_id":"9:0",
"_ver":2,
"@class":"Profile",
"nick":"GGaribaldi",
"followings":[],
"followers":[],
"name":"Giuseppe",
"surname":"Garibaldi",
"location":"11:0",
"invitedBy":null,
"sex":"male",
"online":true
}
HEAD-DocumentbyClass
Checkifadocumentexists
Syntax: http://<server>:[<port>]/documentbyclass/<database>/<class-name>/<record-position>
Where:
<class-name>isthenameofthedocument'sclass
<record-position>istheabsolutepositionoftherecordinsidetheclass'defaultcluster
Example
HTTPHEADrequest: http://localhost:2480/documentbyclass/demo/Profile/0
HTTPresponsecanbe:
HTTPCode204,ifthedocumentexists
HTTPCode404,ifthedocumentwasnotfound
Allocation
GET-Allocation
Retrieveinformationaboutthestoragespaceofadisk-baseddatabase.
Syntax: http://<server>:[<port>]/allocation/<database>
Example
HTTPGETrequest: http://localhost:2480/allocation/demo
HTTPresponse: {"size":61910,"segments":[{"type":"d","offset":0,"size":33154},{"type":"h","offset":33154,"size":
4859},{"type":"h","offset":3420,"size":9392},{"type":"d","offset":12812,"size":49098}],"dataSize":47659,
"dataSizePercent":76,"holesSize":14251,"holesSizePercent":24}
Index
NOTE:Everysinglenewdatabasehasthedefaultmanualindexcalled"dictionary".
GET-Index
Retrievearecordlookingintotheindex.
Syntax: http://<server>:[<port>]/index/<index-name>/<key>
Example
507
HTTPAPI
HTTPGETrequest: http://localhost:2480/dictionary/testHTTPresponse:
{
"name":"Jay",
"surname":"Miner"
}
PUT-Index
Createormodifyanindexentry.
Syntax: http://<server>:[<port>]/index/<index-name>/<key>
Example
HTTPPUTrequest: http://localhost:2480/dictionary/testcontent: {"name":"Jay","surname":"Miner"}
HTTPresponse:Noresponse.
DELETE-Index
Removeanindexentry.
Syntax: http://<server>:[<port>]/index/<index-name>/<key>
Example
HTTPDELETErequest: http://localhost:2480/dictionary/testHTTPresponse:Noresponse.
Query
GET-Query
Executeaqueryagainstthedatabase.QuerymeansonlyidempotentcommandslikeSQLSELECTandTRAVERSE.Idempotentmeans
thecommandisread-onlyandcan'tchangethedatabase.RememberthatinIE6theURLcanbemaximumof2,083characters.Other
browserssupportslongerURLs,butifyouwanttostaycompatiblewithalllimitto2,083characters.
Syntax: http://<server>:[<port>]/query/<database>/<language>/<query-text>[/<limit>][/<fetchPlan>]
Where:
<language>isthenameofthelanguagebetweenthosesupported.OrientDBdistributioncomeswith"sql"only.Gremlinlanguage
cannotbeexecutedwithquerybecauseitcannotguaranteetobeidempotent.ToexecuteGremlinusecommandinstead.
query-textisthetextcontainingthequerytoexecute
limitisthemaximumnumberofrecordtoreturn.Optional,defaultis20
fetchPlanisthefetchingstrategytouse.FormoreinformationlookatFetchingStrategies.Optional,defaultis*:1(1depthlevel
only)
Otherkeypoints:
Tousecommandsthatchangethedatabase(non-idempotent),seethePOST–Commandsection
Thecommand-textincludedintheURLmustbeencodedasperanormalURL
SeetheSQLsectionforthetypeofqueriesthatcanbesent
Example
HTTPGETrequest: http://localhost:2480/query/demo/sql/selectfromProfile
HTTPresponse:
508
HTTPAPI
{"result":[
{
"_id":"-3:1",
"_ver":0,
"@class":"Address",
"type":"Residence",
"street":"PiazzadiSpagna",
"city":"-4:0"
},
{
"_id":"-3:2",
"_ver":0,
"@class":"Address",
"type":"Residence",
"street":"test",
"city":"-4:1"
}]}
Thesamequerywiththelimittomaximum20resultsusingthefetchplan*:-1thatmeansloadallrecursively:
HTTPGETrequest: http://localhost:2480/query/demo/sql/selectfromProfile/20/*:-1
Server
GET-Server
RetrieveinformationabouttheconnectedOrientDBServer.Requiresadditionalauthenticationtotheserver.
Syntax: http://<server>:[<port>]/server
Example
HTTPGETrequest: http://localhost:2480/serverHTTPresponse:
{
"connections":[{
"id":"4",
"id":"4",
"remoteAddress":"0:0:0:0:0:0:0:1:52504",
"db":"-",
"user":"-",
"protocol":"HTTP-DB",
"totalRequests":"1",
"commandInfo":"Serverstatus",
"commandDetail":"-",
"lastCommandOn":"2010-05-2605:08:58",
"lastCommandInfo":"-",
"lastCommandDetail":"-",
"lastExecutionTime":"0",
"totalWorkingTime":"0",
...
POST-Server
Changesserverconfiguration.Supportedconfigurationare:
anysettingcontainedinOGlobalConfiguationclass,byusingtheprefix configurationinsetting-name
logginglevel,byusingtheprefix loginsetting-name
Syntax: http://<server>:[<port>]/server/<setting-name>/<setting-value>
Example
ExampleonchangingtheserverlogleveltoFINEST
509
HTTPAPI
localhost:2480/server/log.console/FINEST
Exampleonchangingthedefaulttimeoutforqueryto10seconds
localhost:2480/server/configuration.command.timeout/10000
Connection
POST-Connection
Syntax: http://<server>:[<port>]/connection/<command>/<id>
Where:
commandcanbe:
killtokillaconnection
interrupttointerrupttheoperation(ifpossible)
id,astheconnectionid.ToknowalltheconnectionsuseGET/connection/[<db>]
You'vetoexecutethiscommandauthenticatedintheOrientDBServerrealm(nodatabaserealm),sogettherootpasswordfrom
config/orientdb-server-config.xmlfile(lastsection).
510
BinaryProtocol
BinaryProtocol
Currentprotocolversionfor2.1.x:32.Lookatcompatibilityforretro-compatibility.
Tableofcontent
Introduction
Connection
Gettingstarted
Session
Enabledebugmessagesonprotocol
Exchange
Networkmessageformat
Supportedtypes
Recordformat
Request
Operationtypes
Response
Statuses
Errors
Operations
REQUEST_SHUTDOWN
REQUEST_CONNECT
REQUEST_DB_OPEN
REQUEST_DB_REOPEN
REQUEST_DB_CREATE
REQUEST_DB_CLOSE
REQUEST_DB_EXIST
REQUEST_DB_RELOAD
REQUEST_DB_DROP
REQUEST_DB_SIZE
REQUEST_DB_COUNTRECORDS
REQUEST_DATACLUSTER_ADD(deprecated)
REQUEST_DATACLUSTER_DROP(deprecated)
REQUEST_DATACLUSTER_COUNT(deprecated)
REQUEST_DATACLUSTER_DATARANGE(deprecated)
REQUEST_RECORD_LOAD
REQUEST_RECORD_CREATE
REQUEST_RECORD_UPDATE
REQUEST_RECORD_DELETE
REQUEST_COM M AND
SQLcommandpayload
SQLScriptcommandpayload
REQUEST_TX_COM M IT
REQUEST_INDEX_GET
REQUEST_INDEX_PUT
REQUEST_INDEX_REM OVE
SpecialuseofLINKSETtypes
Treenodebinarystructure
History
Version31
Version24
Version23
511
BinaryProtocol
Version22
Version21
Version20
Version19
Version18
Version17
Version16
Version15
Version14
Version13
Version12
Version11
Compatibility
Introduction
TheOrientDBbinaryprotocolisthefastestwaytointerfaceaclientapplicationtoanOrientDBServerinstance.Theaimofthispageis
toprovideastartingpointfromwhichtobuildalanguagebinding,maintaininghigh-performance.
Ifyou'dliketodevelopanewbinding,pleasetakealooktotheavailableonesbeforestartinganewprojectfromscratch:Existent
Drivers.
Also,checktheavailableRESTimplementations.
Beforestarting,pleasenotethat:
RecordisanabstractionofDocument.However,keepinmindthatinOrientDByoucanhandlestructuresatalowerlevelthan
Documents.Theseincludepositionalrecords,rawstrings,rawbytes,etc.
Formorein-depthinformationpleaselookattheJavaclasses:
Clientside:OStorageRemote.java
Serverside:ONetworkProtocolBinary.java
Protocolconstants:OChannelBinaryProtocol.java
Connection
(Since0.9.24-SNAPSHOTNov25th2010)Onceconnected,theserversendsashortnumber(2byte)containingthebinaryprotocol
number.Theclientshouldcheckthatitsupportsthatversionoftheprotocol.Everytimetheprotocolchangestheversionis
incremented.
Gettingstarted
Aftertheconnectionhasbeenestablished,aclientcanConnecttotheserverorrequesttheopeningofadatabaseDatabaseOpen.
Currently,onlyTCP/IPrawsocketsaresupported.ForthisoperationusesocketAPIsappropriatetothelanguageyou'reusing.After
theConnectandDatabaseOpenalltheclient'srequestsaresenttotheserveruntiltheclientclosesthesocket.Whenthesocketis
closed,OrientDBServerinstancefreesresourcestheusedfortheconnection.
Thefirstoperationfollowingthesocket-levelconnectionmustbeoneof:
ConnecttotheservertoworkwiththeOrientDBServerinstance
Openadatabasetoopenanexistingdatabase
InbothcasesaSession-Idissentbacktotheclient.TheserverassignsauniqueSession-Idtotheclient.Thisvaluemustbeusedforall
furtheroperationsagainsttheserver.Youmayopenadatabaseafterconnectingtotheserver,usingthesameSession-Id
Session
512
BinaryProtocol
Thesessionmanagementsupportstwomodes:statefulandstateless:
thestatefulisbasedonaSession-id
thestatelessisbasedonaToken
Thesessionmodeisselectedatopen/connectoperation.
Session-Id
Alltheoperationsthatfollowtheopen/connectmustcontain,asthefirstparameter,theclientS ession-Id(asInteger,4bytes)andit
willbesentbackoncompletionoftherequestjustaftertheresultfield.
NOTE:Inordertocreateanewserver-sideconnection,theclientmustsendanegativenumberintotheopen/connectcalls.
ThisS ession-Idcanbeusedintotheclienttokeeptrackoftherequestsifithandlesmultiplesessionboundtothesameconnection.In
thiswaytheclientcanimplementasharingpolicytosaveresources.Thisrequiresthattheclientimplementationhandletheresponse
returnedanddispatchittothecorrectcallerthread.
OpeningmultipleTCP/IPsocketsagainstOrientDBServerallowstoparallelizerequests.However,payattention
touseoneSession-idperconnection.IfmultiplesocketsusethesameSession-Id,requestswillnotbeexecuted
concurrentlyontheserverside.
Token
Alltheoperationinastatelesssessionarebasedonthetoken,thetokenisabyte[]thatcontainsalltheinformationfortheinteraction
withtheserver,thetokenisacquiredatthemomentofopenorconnect,andneedtoberesendforeachrequest.thesessionidusedin
thestatefulrequestsisstillthereandisusedtoassociatetherequesttotheresponse.intheresponsecanberesendatokenincaseof
expirerenew.
Enabledebugmessagesonprotocol
Tomakethedevelopmentofanewclienteasierit'sstronglysuggestedtoactivatedebugmodeonthebinarychannel.Toactivatethis,
editthefile orientdb-server-config.xmlandconfigurethenewparameter network.binary.debugonthe"binary"or"distributed"
listener.E.g.:
...
<listenerprotocol="distributed"port-range="2424-2430"
ip-address="127.0.0.1">
<parameters>
<parametername="network.binary.debug"value="true"/>
</parameters>
</listener>
...
Inthelogfile(ortheconsoleifyouhaveconfiguredthe orientdb-server-log.propertiesfile)allthepacketsreceivedwillbeprinted.
Exchange
Thisisthetypicalexchangeofmessagesbetweenclientandserversides:
513
BinaryProtocol
+------++------+
|Client||Server|
+------++------+
|TCP/IPSocketconnection|
+-------------------------->|
|DB_OPEN|
+-------------------------->|
|RESPONSE(+SESSION-ID)|
+<--------------------------+
......
|REQUEST(+SESSION-ID)|
+-------------------------->|
|RESPONSE(+SESSION-ID)|
+<--------------------------+
......
|DB_CLOSE(+SESSION-ID)|
+-------------------------->|
|TCP/IPSocketclose|
+-------------------------->|
Networkmessageformat
Inexplainingthenetworkmessagestheseconventionswillbeused:
fieldsarebracketedbyparenthesisandcontainthenameandthetypeseparatedby':'.E.g. (length:int)
Supportedtypes
Thenetworkprotocolsupportsdifferenttypesofinformation:
Minimum
lengthin
bytes
Maximum
lengthin
bytes
boolean
1
1
Singlebyte:1=true,0=false
1
byte
1
1
Singlebyte,usedtostoresmallnumbersand
booleans
1
short
2
2
Signedshorttype
01
int
4
4
Signedintegertype
0001
long
8
8
Signedlongtype
00000001
bytes
4
N
Usedforbinarydata.Theformatis (length:int)
[(bytes)].Send-1asNULL
000511111
string
4
N
Type
Notes
Example
Usedfortextmessages.Theformatis:
(length:int)[(bytes)](content:<length>).Send
0005Hello
-1asNULL
record
2
N
Anentirerecordserialized.Theformatdependsif
aRIDispassedoranentirerecordwithits
content.Incaseofnullrecordthen-2asshortis
passed.IncaseofRID-3ispassesasshortand
thentheRID: (-3:short)(cluster-id:short)
(cluster-position:long).Incaseofrecord:
(0:short)(record-type:byte)(cluster-id:short)
(cluster-position:long)(record-version:int)
(record-content:bytes)
strings
4
N
Usedformultipletextmessages.Theformatis:
(length:int)[(Nth-string:string)]
00020005Hello0007World!
Notewhenthetypeofafieldinaresponsedependsonthevaluesofthepreviousfields,thatfieldwillbewrittenwithoutthetype
(e.g., (a-field)).Thetypeofthefieldwillbethenspecifiedbasedonthevaluesofthepreviousfieldsinthedescriptionofthe
response.
514
BinaryProtocol
Recordformat
TherecordformatischooseduringtheCONNECTorDB_OPENrequest,theformatsavailableare:
CSV(serialization-implvalue"ORecordDocument2csv")Binary(serialization-implvalue"ORecordSerializerBinary")
TheCSVformatisthedefaultforalltheversions0.and1.orforanyclientwithNetworkProtocolVersion<22
Request
Eachrequesthasownformatdependingoftheoperationrequested.Theoperationrequestedisindicatedinthefirstbyte:
1bytefortheoperation.SeeOperationtypesforthelist
4bytesfortheSession-IdnumberasInteger
NbytesoptionaltokenbytesonlypresentiftheREQUEST_CONNECT/REQUEST_DB_OPENreturnatoken.
Nbytes=messagecontentbasedontheoperationtype
Operationtypes
Command
Value
as
byte
Description
Async
Server(CONNECTOperations)
REQUEST_SHUTDOWN
1
Shutdownserver.
no
REQUEST_CONNECT
2
Requiredinitialoperationtoaccessto
servercommands.
no
REQUEST_DB_OPEN
3
Requiredinitialoperationtoaccess
tothedatabase.
no
REQUEST_DB_CREATE
4
Addanewdatabase.
no
REQUEST_DB_EXIST
6
Checkifdatabaseexists.
no
REQUEST_DB_DROP
7
Deletedatabase.
no
REQUEST_CONFIG_GET
70
Getaconfigurationproperty.
no
REQUEST_CONFIG_SET
71
Setaconfigurationproperty.
no
REQUEST_CONFIG_LIST
72
Getalistofconfigurationproperties.
no
REQUEST_DB_LIST
74
Getalistofdatabases.
no
REQUEST_DB_CLOSE
5
Closeadatabase.
no
REQUEST_DB_SIZE
8
Getthesizeofadatabase(inbytes).
no
REQUEST_DB_COUNTRECORDS
9
Gettotalnumberofrecordsina
database.
no
REQUEST_DATACLUSTER_ADD(deprecated)
10
Addadatacluster.
no
REQUEST_DATACLUSTER_DROP(deprecated)
11
Deleteadatacluster.
no
REQUEST_DATACLUSTER_COUNT(deprecated)
12
Getthetotalnumberofdataclusters.
no
REQUEST_DATACLUSTER_DATARANGE(deprecated)
13
Getthedatarangeofdataclusters.
no
Database(DB_OPENOperations)
515
BinaryProtocol
REQUEST_DATACLUSTER_COPY
14
Copyadatacluster.
no
REQUEST_DATACLUSTER_LH_CLUSTER_IS_USED
16
REQUEST_RECORD_M ETADATA
29
Getmetadatafromarecord.
no
REQUEST_RECORD_LOAD
30
Loadarecord.
no
REQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST
44
Loadarecord.
no
REQUEST_RECORD_CREATE
31
Addarecord.
yes
REQUEST_RECORD_UPDATE
32
REQUEST_RECORD_DELETE
33
Deletearecord.
yes
REQUEST_RECORD_COPY
34
Copyarecord.
yes
REQUEST_RECORD_CLEAN_OUT
38
Cleanoutrecord.
yes
REQUEST_POSITIONS_FLOOR
39
Getthelastrecord.
yes
REQUEST_COUNT(DEPRECATED)
40
See
REQUEST_DATACLUSTER_COUNT
no
REQUEST_COM M AND
41
Executeacommand.
no
REQUEST_POSITIONS_CEILING
42
Getthefirstrecord.
no
REQUEST_TX_COM M IT
60
Committransaction.
no
REQUEST_DB_RELOAD
73
Reloaddatabase.
no
REQUEST_PUSH_RECORD
79
no
REQUEST_PUSH_DISTRIB_CONFIG
80
no
REQUEST_PUSH_LIVE_QUERY
81
no
REQUEST_DB_COPY
90
no
REQUEST_REPLICATION
91
no
REQUEST_CLUSTER
92
no
REQUEST_DB_TRANSFER
93
no
REQUEST_DB_FREEZE
94
no
REQUEST_DB_RELEASE
95
no
REQUEST_DATACLUSTER_FREEZE(deprecated)
96
no
REQUEST_DATACLUSTER_RELEASE(deprecated)
97
no
REQUEST_CREATE_SBTREE_BONSAI
110
Createsansb-treebonsaiontheremote
server
no
REQUEST_SBTREE_BONSAI_GET
111
Getvaluebykeyfromsb-treebonsai
no
REQUEST_SBTREE_BONSAI_FIRST_KEY
112
Getfirstkeyfromsb-treebonsai
no
REQUEST_SBTREE_BONSAI_GET_ENTRIES_M AJOR
113
Getstheportionofentriesgreaterthan
thespecifiedone.Ifreturns0entries
thanthespecifiedentrieisthelargest
no
REQUEST_RIDBAG_GET_SIZE
114
Rid-bagspecificoperation.Sendbut
doesnotsavechangesofridbag.
Retrievescomputedsizeofridbag.
no
REQUEST_INDEX_GET
120
Lookupinanindexbykey
no
REQUEST_INDEX_PUT
121
Createorupdateanentryinanindex
no
REQUEST_INDEX_REM OVE
122
Removeanentryinanindexbykey
no
no
yes
516
BinaryProtocol
Response
Everyrequesthasaresponseunlessthecommandsupportstheasynchronousmode(lookatthetableabove).
1byte:Successstatusoftherequestifsucceededorfailed(0=OK,1=ERROR)
4bytes:Session-Id(Integer)
Nbytesoptionaltoken,isonlypresentfortokenbasedsession(REQUEST_CONNECT/REQUEST_DB_OPENreturnatoken)
andisusuallyempty(N=0)isonlyfilledupbytheserverwhenrenewofanexpiringtokenisrequired.
Nbytes:M essagecontentdependingontheoperationrequested
PushRequest
Apushrequestisamessagesentbytheserverwithoutanyrequestfromtheclient,ithasasimilarstructureofaresponseandis
distinguishedusingtheresposestatusbyte:
1byte:Successstatushasvalue3incaseofpushrequest
4bytes:Session-IdhaseverytimeM IN_INTEGERvalue(-2^31)
1byte:Pushcommandid
Nbytes:M essagecontentdependingonthepushmassage,thisiswrittenassa (content:bytes)havinginsidethedetailsofthe
specificmessage.
Statuses
Everytimetheclientsendsarequest,andthecommandisnotinasynchronousmode(lookatthetableabove),clientmustreadtheonebyteresponsestatusthatindicatesOKorERROR.Therestofresponsebytesdependsonthisfirstbyte.
*OK=0;
*ERROR=1;
*PUSH_REQUEST=3
OKresponsebytesaredependsforeveryrequesttype.ERRORresponsebytessequencedescribedbelow.
Errors
Theformatis: [(1)(exception-class:string)(exception-message:string)]*(0)(serialized-exception:bytes)
Thepairsexception-classandexception-messagecontinuewhilethefollowingbyteis1.A0inthispositionindicatesthatnomoredata
follows.
E.g.(parenthesesareusedherejusttoseparatefieldstomakethiseasiertoread:theyarenotpresentintheserverresponse):
(1)(com.orientechnologies.orient.core.exception.OStorageException)(Can'topenthestorage'demo')(0)
Exampleof2depth-levelsexception:
(1)(com.orientechnologies.orient.core.exception.OStorageException)(Can'topenthestorage'demo')(1)(com.orientechnologies.ori
ent.core.exception.OStorageException)(Filenotfound)(0)
Since1.6.1wealsosendserializedversionofexceptionthrownonserverside.Thisallowstopreservefullstacktraceofserver
exceptiononclientsidebutthisfeaturecanbeusedbyJavaclientsonly.
Operations
Thissectionexplainstherequestandresponsemessagesofallsuportedoperations.
517
BinaryProtocol
REQUEST_SHUTDOWN
Shutdowntheserver.Requires"shutdown"permissiontobesetinorientdb-server-config.xmlfile.
Request:(user-name:string)(user-password:string)
Response:empty
TypicallythecredentialsarethoseoftheOrientDBserveradministrator.Thisisnotthesameastheadminuserforindividualdatabases.
REQUEST_CONNECT
Thisisthefirstoperationrequestedbytheclientwhenitneedstoworkwiththeserverinstance.ThisoperationreturnstheSession-Id
ofthenewclienttoreuseforallthenextcalls.
Request:(driver-name:string)(driver-version:string)(protocol-version:short)(client-id:string)(serialization-impl:string)(toke
n-session:boolean)(user-name:string)(user-password:string)
Response:(session-id:int)(token:bytes)
Request
client'sdriver-name-thenameoftheclientdriver.Example:"OrientDBJavaclient".
client'sdriver-version-theversionoftheclientdriver.Example:"1.0rc8-SNAPSHOT"
client'sprotocol-version-theversionoftheprotocoltheclientwantstouse.Example:30.
client'sclient-id-canbenullforclients.Inclusteredconfigurationsit'sthedistributednodeIDasTCP host:port.Example:
"10.10.10.10:2480".
client'sserialization-impl-theserializationformatrequiredbytheclient.
token-session-trueiftheclientwantstouseatoken-basedsession,falseotherwise.
user-name-theusernameoftheuserontheserver.Example:"root".
user-password-thepasswordoftheuserontheserver.Example:"37aed6392".
TypicallythecredentialsarethoseoftheOrientDBserveradministrator.Thisisnotthesameastheadminuserforindividualdatabases.
Response
session-id-thenewsessionidoramatchidincaseoftokenauthentication.
token-thetokenfortoken-basedauthentication.Iftheclientssendstoken-sessionasfalseintherequestortheserverdoesn't
supporttoken-basedauthentication,thiswillbeanempty byte[].
REQUEST_DB_OPEN
Thisisthefirstoperationtheclientshouldcall.ItopensadatabaseontheremoteOrientDBServer.ThisoperationreturnstheSessionIdofthenewclienttoreuseforallthenextcallsandthelistofconfiguredclustersintheopeneddatabse.
Request:(driver-name:string)(driver-version:string)(protocol-version:short)(client-id:string)(serialization-impl:string)(toke
n-session:boolean)(database-name:string)(user-name:string)(user-password:string)
Response:(session-id:int)(token:bytes)(num-of-clusters:short)[(cluster-name:string)(cluster-id:short)](cluster-config:bytes)(
orientdb-release:string)
Request
client'sdriver-name-thenameoftheclientdriver.Example:"OrientDBJavaclient".
client'sdriver-version-theversionoftheclientdriver.Example:"1.0rc8-SNAPSHOT"
client'sprotocol-version-theversionoftheprotocoltheclientwantstouse.Example:30.
client'sclient-id-canbenullforclients.Inclusteredconfigurationsit'sthedistributednodeIDasTCP host:port.Example:
"10.10.10.10:2480".
client'sserialization-impl-theserializationformatrequiredbytheclient.
518
BinaryProtocol
token-session-trueiftheclientwantstouseatoken-basedsession,falseotherwise.
database-name-thenameofthedatabasetoconnectto.Example:"demo".
user-name-theusernameoftheuserontheserver.Example:"root".
user-password-thepasswordoftheuserontheserver.Example:"37aed6392".
Response
session-id-thenewsessionidoramatchidincaseoftokenauthentication.
token-thetokenfortoken-basedauthentication.Iftheclientssendstoken-sessionasfalseintherequestortheserverdoesn't
supporttoken-basedauthentication,thiswillbeanempty byte[].
num-of-clusters-thesizeofthearrayofclustersintheform (cluster-name:string)(cluster-id:short)thatfollowsthisnumber.
cluster-name,cluster-id-thenameandidofacluster.
cluster-config-it'susuallynullunlessrunninginaserverclusteredconfiguration.
orientdb-release-containstheversionoftheOrientDBreleasedeployedontheserverandoptionallythebuildnumber.Example:
"1.4.0-SNAPSHOT(build13)".
REQUEST_DB_REOPEN
Usedonnewsocketsforassociatethespecificsocketwiththeserversidesessionforthespecificclient,canbeusedexclusivelywith
thetokenauthentication
Request:empty
Response:(session-id:int)
REQUEST_DB_CREATE
CreatesadatabaseintheremoteOrientDBserverinstance.
Request:(database-name:string)(database-type:string)(storage-type:string)
Response:empty
Request
database-name-thenameofthedatabasetocreate.Example:"M yDatabase".
database-type-thetypeofthedatabasetocreate.Canbeeither documentor graph(sinceversion8).Example:"document".
storage-type-specifiesthestoragetypeofthedatabasetocreate.Itcanbeoneofthesupportedtypes:
plocal-persistentdatabase
memory-volatiledatabase
Note:itdoesn'tmakesensetouse remoteinthiscontext.
REQUEST_DB_CLOSE
ClosesthedatabaseandthenetworkconnectiontotheOrientDBserverinstance.Noresponseisexpected.TheTCPsocketisalso
closed.
Request:empty
Response:noresponse,thesocketisjustclosedatserverside
REQUEST_DB_EXIST
AsksifadatabaseexistsintheOrientDBserverinstance.
519
BinaryProtocol
Request:(database-name:string)(server-storage-type:string)
Response:(result:boolean)
Request
database-name-thenameofthetargetdatabase.Notethatthiswasemptybefore 1.0rc1.
storage-type-specifiesthestoragetypeofthedatabasetobecheckedforexistance.Since 1.5-snapshot.Itcanbeoneofthe
supportedtypes:
plocal-persistentdatabase
memory-volatiledatabase
Response
result-trueifthegivendatabaseexists,falseotherwise.
REQUEST_DB_RELOAD
Reloadsinformationaboutthegivendatabase.Availablesince 1.0rc4.
Request:empty
Response:(num-of-clusters:short)[(cluster-name:string)(cluster-id:short)]
Response
num-of-clusters-thesizeofthearrayofclustersintheform (cluster-name:string)(cluster-id:short)thatfollowsthisnumber.
cluster-name,cluster-id-thenameandidofacluster.
REQUEST_DB_DROP
RemovesadatabasefromtheOrientDBserverinstance.Thisoperationreturnsasuccessfulresponseifthedatabaseisdeleted
successfully.Otherwise,ifthedatabasedoesn'texistontheserver,itreturnsanerror(an OStorageException).
Request:(database-name:string)(storage-type:string)
Response:empty
Request
database-name-thenameofthedatabasetoremove.
storage-type-specifiesthestoragetypeofthedatabasetocreate.Since 1.5-snapshot.Itcanbeoneofthesupportedtypes:
plocal-persistentdatabase
memory-volatiledatabase
REQUEST_DB_SIZE
Returnsthesizeofthecurrentlyopendatabase.
Request:empty
Response:(size:long)
Response
size-thesizeofthecurrentdatabase.
520
BinaryProtocol
REQUEST_DB_COUNTRECORDS
Returnsthenumberofrecordsinthecurrentlyopendatabase.
Request:empty
Response:(count:long)
Response
count-thenumberofrecordsinthecurrentdatabase.
REQUEST_DATACLUSTER_ADD
Addanewdatacluster.Deprecated.
Request:(name:string)(cluster-id:short-since1.6snapshot)
Response:(new-cluster:short)
Where:typeisoneof"PHYSICAL"or"M EM ORY".Ifcluster-idis-1(recommendedvalue)newclusteridwillbegenerated.
REQUEST_DATACLUSTER_DROP
Removeacluster.Deprecated.
Request:(cluster-number:short)
Response:(delete-on-clientside:byte)
Where:
delete-on-clientsidecanbe1iftheclusterhasbeensuccessfullyremovedandtheclienthastoremovetoo,otherwise0
REQUEST_DATACLUSTER_COUNT
Returnsthenumberofrecordsinoneormoreclusters.Deprecated.
Request:(cluster-count:short)(cluster-number:short)*(count-tombstones:byte)
Response:(records-in-clusters:long)
Where:
cluster-countthenumberofrequestedclusters
cluster-numbertheclusteridofeachsinglecluster
count-tombstonestheflagwhichindicateswhetherdeletedrecordsshouldbetakeninaccount.Itisapplicableforautosharded
storageonly,otherwiseitisignored.
records-in-clustersisthetotalnumberofrecordsfoundintherequestedclusters
Example
Requesttherecordcountforclusters5,6and7.Notethe"03"atthebeginningtotellyou'repassing3clusterids(asshorteach).1,000
aslong(8bytes)istheanswer.
Request:03050607
Response:00001000
REQUEST_DATACLUSTER_DATARANGE
521
BinaryProtocol
Returnstherangeofrecordidsforacluster.Deprecated.
Request:(cluster-number:short)
Response:(begin:long)(end:long)
Example
Requesttherangeforcluster7.Therange0-1,000isreturnedintheresponseas2longs(8byteseach).
Request:07
Response:0000000000001000
REQUEST_RECORD_LOAD
LoadsarecordbyitsRecordID,accordingtoafetchplan.
Request:(cluster-id:short)(cluster-position:long)(fetch-plan:string)(ignore-cache:boolean)(load-tombstones:boolean)
Response:[(payload-status:byte)[(record-type:byte)(record-version:int)(record-content:bytes)]*]+
Request
cluster-id,cluster-position-theRecordIDoftherecord.
fetch-plan-thefetchplantouseoranemptystring.
ignore-cache-iftruetellstheservertoignorethecache,iffalsetellstheservertonotignorethecache.Availablesinceprotocolv.9
(introducedinrelease1.0rc9).
load-tombstones-aflagwhichindicateswhetherinformationaboutdeletedrecordshouldbeloaded.Theflagisappliedonlyto
autoshardedstorageandignoredotherwise.
Response
payload-status-canbe:
0:norecordsremaintobefetched.
1:arecordisreturnedasresultset.
2:arecordisreturnedaspre-fetchedtobeloadedinclient'scacheonly.It'snotpartoftheresultsetbuttheclientknows
thatit'savailableforlateraccess.Thisvalueisnotcurrentlyused.
record-type-canbe:
d:document
b:rawbytes
f:flatdata
REQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST
LoadsarecordbyRecordID,accordingtoafetchplan.Therecordisonlyloadedifthepersistentversionismorerecentoftheversion
specifiedintherequest.
Request:(cluster-id:short)(cluster-position:long)(version:int)(fetch-plan:string)(ignore-cache:boolean)
Response:[(payload-status:byte)[(record-type:byte)(record-version:int)(record-content:bytes)]*]*
Request
cluster-id,cluster-position-theRecordIDoftherecord.
version-theversionoftherecordtofetch.
fetch-plan-thefetchplantouseoranemptystring.
ignore-cache-iftruetellstheservertoignorethecache,iffalsetellstheservertonotignorethecache.Availablesinceprotocolv.9
(introducedinrelease1.0rc9).
522
BinaryProtocol
Response
payload-status-canbe:
0:norecordsremaintobefetched.
1:arecordisreturnedasresultset.
2:arecordisreturnedaspre-fetchedtobeloadedinclient'scacheonly.It'snotpartoftheresultsetbuttheclientknows
thatit'savailableforlateraccess.Thisvalueisnotcurrentlyused.
record-type-canbe:
d:document
b:rawbytes
f:flatdata
REQUEST_RECORD_CREATE
Createsanewrecord.ReturnstheRecordIDofthenewlycreatedrecord..Newrecordscanhaveversion>0(since 1.0)incasethe
RecordIDhasbeenrecycled.
Request:(cluster-id:short)(record-content:bytes)(record-type:byte)(mode:byte)
Response:(cluster-id:short)(cluster-position:long)(record-version:int)(count-of-collection-changes)[(uuid-most-sig-bits:long)
(uuid-least-sig-bits:long)(updated-file-id:long)(updated-page-index:long)(updated-page-offset:int)]*
Request
cluster-id-theidoftheclusterinwhichtocreatethenewrecord.
record-content-therecordtocreateserializedusingtheappropriateserializationformatchosenatconnectiontime.
record-type-thetypeoftherecordtocreate.Itcanbe:
d:document
b:rawbytes
f:flatdata
mode-canbe:
0-synchronous.It'sthedefaultmodewhichwaitsfortheanswerbeforetheresponseissent.
1-asynchronous.Theresponseisidenticaltothesynchronousresponse,butthedriverisencouragedtomanagethe
answerinacallback.
2-no-response.Don'twaitfortheanswer(fireandforget).Thismodeisusefulonmassiveoperationssinceitreduces
networklatency.
Inversionsbefore 2.0,theresponsestartedwithanadditionaldatasegment-id,thesegmentidtostorethedata(availablesince
version10- 1.0-SNAPSHOT),with-1meaningdefaultone.
Response
cluster-id,cluster-position-theRecordIDofthenewlycreatedrecord.
record-version-theversionofthenewlycreatedrecord.
Thelastpartofresponse(from count-of-collection-changeson)referstoRidBagmanagement.Takealookatthemainpageformore
details.
REQUEST_RECORD_UPDATE
UpdatestherecordidentifiedbythegivenRecordID.Returnsthenewversionoftherecord.
Request:(cluster-id:short)(cluster-position:long)(update-content:boolean)(record-content:bytes)(record-version:int)(record-ty
pe:byte)(mode:byte)
Response:(record-version:int)(count-of-collection-changes)[(uuid-most-sig-bits:long)(uuid-least-sig-bits:long)(updated-file-i
d:long)(updated-page-index:long)(updated-page-offset:int)]*
Request
523
BinaryProtocol
cluster-id,cluster-position-theRecordIDoftherecordtoupdate.
update-content-canbe:
true-thecontentoftherecordhasbeenchangedandshouldbeupdatedinthestorage.
false-therecordwasmodifiedbutitsowncontenthasnotchanged:relatedcollections(e.g.RidBags)havetobeupdated,but
therecordversionanditscontentsshouldnotbeupdated.
record-content-thenewcontentsoftherecordserializedusingtheappropriateserializationformatchosenatconnectiontime.
record-version-theversionoftherecordtoupdate.
record-type-thetypeoftherecordtocreate.Itcanbe:
d:document
b:rawbytes
f:flatdata
mode-canbe:
0-synchronous.It'sthedefaultmodewhichwaitsfortheanswerbeforetheresponseissent.
1-asynchronous.Theresponseisidenticaltothesynchronousresponse,butthedriverisencouragedtomanagethe
answerinacallback.
2-no-response.Don'twaitfortheanswer(fireandforget).Thismodeisusefulonmassiveoperationssinceitreduces
networklatency.
Response
record-version-thenewversionoftheupdatedrecord
Thelastpartofresponse(from count-of-collection-changeson)referstoRidBagmanagement.Takealookatthemainpageformore
details.
REQUEST_RECORD_DELETE
DeletearecordidentifiedbythegivenRecordID.Duringtheoptimistictransactiontherecordwillbedeletedonlyifthegivenversion
andtheversionoftherecordontheservermatch.Thisoperationreturnstrueiftherecordisdeletedsuccessfully,falseotherwise.
Request:(cluster-id:short)(cluster-position:long)(record-version:int)(mode:byte)
Response:(has-been-deleted:boolean)
Request
cluster-id,cluster-position-theRecordIDoftherecordtodelete.
record-version-theversionoftherecordtodelete.
mode-canbe:
0-synchronous.It'sthedefaultmodewhichwaitsfortheanswerbeforetheresponseissent.
1-asynchronous.Theresponseisidenticaltothesynchronousresponse,butthedriverisencouragedtomanagethe
answerinacallback.
2-no-response.Don'twaitfortheanswer(fireandforget).Thismodeisusefulonmassiveoperationssinceitreduces
networklatency.
Response
has-been-deleted-trueiftherecordisdeletedsuccessfully,falseifit'snotoriftherecordwiththegivenRecordIDdoesn'texist.
REQUEST_COMMAND
Executesremotecommands.
524
BinaryProtocol
Request:(mode:byte)(command-payload-length:int)(class-name:string)(command-payload)
Response:
-synchronouscommands:[(synch-result-type:byte)[(synch-result-content:?)]]+
-asynchronouscommands:[(asynch-result-type:byte)[(asynch-result-content:?)]*](pre-fetched-record-size.md)[(pre-fetched-reco
rd)]*+
Request
mode-itcanassumeoneofthefollowingvalues:
a-asynchronousmode
s-synchronousmode
l-livemode
command-payload-length-thelengthoftheclass-namefieldplusthelengthofthecommand-payloadfield.
class-name-theclassnameofthecommandimplementation.Therearesomeshortformsforthemostcommoncommands,which
are:
q-standsfor"query"asidempotentcommand(e.g., SELECT).It'slikepassing
com.orientechnologies.orient.core.sql.query.OSQLSynchquery.
c-standsfor"command"asnon-idempotentcommand(e.g., INSERTor UPDATE).It'slikepassing
com.orientechnologies.orient.core.sql.OCommandSQL.
s-standsfor"script"(forserver-sidescriptingusinglanguageslikeJavaScript).It'slikepassing
com.orientechnologies.orient.core.command.script.OCommandScript.
anyotherstring-thestringistheclassnameofthecommand.Thecommandwillbecreatedviareflectionusingthedefault
constructorandinvokingthe fromStream()methodagainstit.
command-payload-isthepayloadofthecommandasspecifiedinthe"Commands"section.
Response
Responseisdifferentforsynchronousandasynchronousrequest:
synchronous:
synch-result-typecanbe:
'n',meansnullresult
'r',meanssinglerecordreturned
'l',listofrecords.Theformatis:
anintegertoindicatethecollectionsize.Startingformv32,sizecanbe-1tostreamaresultset.Lastitemwillbenull
alltherecordsandeachentryistypedwithashortthatcanbe:
'0'arecordinthenextbytes
'-2'norecordandisconsideredasanullrecord
'-3'onlyarecordIdinthenextbytes
's',setofrecords.Theformatis:
anintegertoindicatethecollectionsize.Startingformv32,sizecanbe-1tostreamaresultset.Lastitemwillbenull
alltherecordsandeachentryistypedwithashortthatcanbe:
'0'arecordinthenextbytes
'-2'norecordandisconsideredasanullrecord
'-3'onlyarecordIdinthenextbytes
'a',serializedresult,abyte[]issent
'i',iterableofrecords
theresultrecordswillbestreamed,nosizeasstartisgiven,eachentryhasaflagatthestart(sameasasynch-resulttype)
0:norecordremaintobefetched
1:arecordinthenextbytes
2:arecordinthenextbytestobeloadedinclient'scacheonly.It'snotpartoftheresultsetbut
synch-result-content,canonlybearecord
pre-fetched-record-size,asthenumberofpre-fetchedrecordsnotdirectlypartoftheresultsetbutjoinedtoitbyfetching
pre-fetched-recordasthepre-fetchedrecordcontent
asynchronous:
asynch-result-typecanbe:
525
BinaryProtocol
0:norecordsremaintobefetched
1:arecordisreturnedasaresultset
2:arecordisreturnedaspre-fetchedtobeloadedinclient'scacheonly.It'snotpartoftheresultsetbuttheclientknowsthat
it'savailableforlateraccess
asynch-result-content,canonlybearecord
REQUEST_TX_COMMIT
Commitsatransaction.Thisoperationflushesallthependingchangestotheserverside.
Request:(transaction-id:int)(using-tx-log:boolean)(tx-entry)*(0-byteindicatingend-of-records)
Response:(created-record-count:int)[(client-specified-cluster-id:short)(client-specified-cluster-position:long)(created-clust
er-id:short)(created-cluster-position:long)]*(updated-record-count:int)[(updated-cluster-id:short)(updated-cluster-position:lo
ng)(new-record-version:int)]*(count-of-collection-changes:int)[(uuid-most-sig-bits:long)(uuid-least-sig-bits:long)(updated-fil
e-id:long)(updated-page-index:long)(updated-page-offset:int)]*
Request
transaction-id-theidofthetransaction.Readthe"TransactionID"sectionbelowformoreinformation.
using-tx-log-tellstheserverwhethertousethetransactionlogtorecoverthetransactionornot.Use truebydefaulttoensure
consistency.Note:disablingthelogcouldspeeduptheexecutionofthetransaction,butitmakesimpossibletorollbackthe
transactionincaseoferrors.Thiscouldleadtoinconsistenciesinindexesaswell,sinceincaseofduplicatedkeystherollbackisnot
calledtorestoretheindexstatus.
tx-entry-alistofelements(terminatedbya0byte)withtheformdescribedbelow.
Transactionentry
Eachtransactionentrycanspecifyoneoutofthreeactionstoperform:create,updateordelete.
Thegeneralformofatransactionentry(tx-entryabove)is:
(1:byte)(operation-type:byte)(cluster-id:short)(cluster-position:long)(record-type:byte)(entry-content)
Thefirstbytemeansthatthere'sanotherentrynext.Thevaluesoftherestoftheseattributesdependdirectlyontheoperationtype.
Update
operation-type-hasthevalue1.
cluster-id,cluster-position-theRecordIDoftherecordtoupdate.
record-type-thetypeoftherecordtoupdate( dfordocument, bforrawbytesand fforflatdata).
entry-content-hastheform (version:int)(update-content:boolean)(record-content:bytes)where:
update-content-canbe:
true-thecontentoftherecordhasbeenchangedandshouldbeupdatedinthestorage.
false-therecordwasmodifiedbutitsowncontenthasnotchanged:relatedcollections(e.g.RidBags)havetobeupdated,
buttherecordversionanditscontentsshouldnotbeupdated.
version-theversionoftherecordtoupdate.
record-content-thenewcontentsoftherecordserializedusingtheappropriateserializationformatchosenatconnection
time.
Delete
operation-type-hasthevalue2.
cluster-id,cluster-position-theRecordIDoftherecordtoupdate.
record-type-thetypeoftherecordtoupdate( dfordocument, bforrawbytesand fforflatdata).
entry-content-hastheform (version:int)where:
version-theversionoftherecordtodelete.
Create
526
BinaryProtocol
operation-type-hasthevalue3.
cluster-id,cluster-position-whencreatinganewrecord,settheclusteridto -1.Theclusterpositionmustbeaninteger <
-1,uniqueinthescopeofthetransaction(meaningthatiftwonewrecordsarebeingcreatedinthesametransaction,theyshould
havetwodifferentidsboth <-1).
record-type-thetypeoftherecordtoupdate( dfordocument, bforrawbytesand fforflatdata).
entry-content-hastheform (record-content:bytes)where:
record-content-thenewcontentsoftherecordserializedusingtheappropriateserializationformatchosenatconnection
time.
TransactionID
EachtransactionmusthaveanID;theclientisresponsibleforassigninganIDtoeachtransaction.TheIDmustbeuniqueinthescope
ofeachsession.
Response
Theresponsecontainstwoparts:
amapof"temporary"client-generatedrecordidsto"real"server-providedrecordidsforeachcreatedrecord(notguaranteedto
havethesameorderastherecordsintherequest).
amapofupdatedrecordidstoupdaterecordversions.
Iftheversionofacreatedrecordisnot 0,thentheRecordIDofthecreatedrecordwillalsoappearinthelistof"updated"records,
alongwithitsnewversion.Thisisaknownbug.
LookatOptimisticTransactiontoknowhowtemporaryRecordIDsaremanaged.
Thelastpartofresponse(from count-of-collection-changeson)referstoRidBagmanagement.Takealookatthemainpageformore
details.
REQUEST_INDEX_GET
Lookupsinanindexbykey.
Request:(index-name:string)(key:document)(fetch-plan:string)
Response:(result-type:byte)
Request
index-name-thenameoftheindex.
key-adocumentwhose "key"fieldcontainsthekey.
fetch-plan-thefetchplantouseoranemptystring.
Response
key-isstoredinthefieldnamed"key"insidethedocument
result-typecanbe:
'n',meansnullresult
'r',meanssinglerecordreturned
'l',listofrecords.Theformatis:
anintegertoindicatethecollectionsize
alltherecordsonebyone
's',setofrecords.Theformatis:
anintegertoindicatethecollectionsize
alltherecordsonebyone
'a',serializedresult,abyte[]issent
synch-result-content,canonlybearecord
pre-fetched-record-size,asthenumberofpre-fetchedrecordsnotdirectlypartoftheresultsetbutjoinedtoitbyfetching
527
BinaryProtocol
pre-fetched-recordasthepre-fetchedrecordcontent
REQUEST_INDEX_PUT
Createorupdateanentryinindexbykey.
Request:(index-name:string)(key:document)(value:rid)
Response:noresponse
Where:
keyisstoredinthefieldnamed"key"insidethedocument
REQUEST_INDEX_REMOVE
Removeanentrybykeyfromanindex.Itreturnstrueiftheentrywaspresent,otherwisefalse.
Request:(index-name:string)(key:document)
Response:(found:boolean)
Where:
keyisstoredinthefieldnamed"key"insidethedocument
REQUEST_CREATE_SBTREE_BONSAI
Request:(clusterId:int)
Response:(collectionPointer)
See:serializationofcollectionpointer
Createsansb-treebonsaiontheremoteserver.
REQUEST_SBTREE_BONSAI_GET
Request:(collectionPointer)(key:binary)
Response:(valueSerializerId:byte)(value:binary)
See:serializationofcollectionpointer
Getvaluebykeyfromsb-treebonsai.
Keyandvalueareserializedaccordingtoformatoftreeserializer.IftheoperationisusedbyRidBagkeyisalwaysaRIDandvaluecan
benullorinteger.
REQUEST_SBTREE_BONSAI_FIRST_KEY
Request:(collectionPointer)
Response:(keySerializerId:byte)(key:binary)
See:serializationofcollectionpointer
Getfirstkeyfromsb-treebonsai.Nulliftreeisempty.
Keyareserializedaccordingtoformatoftreeserializer.IftheoperationisusedbyRidBagkeyisnullorRID.
REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR
528
BinaryProtocol
Request:(collectionPointer)(key:binary)(inclusive:boolean)(pageSize:int)
Response:(count:int)[(key:binary)(value:binary)]*
See:serializationofcollectionpointer
Getstheportionofentriesmajorthanspecifiedone.Ifreturns0entriesthanthespecifiedentryisthelargest.
Keysandvaluesareserializedaccordingtoformatoftreeserializer.IftheoperationisusedbyRidBagkeyisalwaysaRIDandvalueis
integer.
DefaultpageSizeis128.
REQUEST_RIDBAG_GET_SIZE
Request:(collectionPointer)(collectionChanges)
Response:(size:int)
See:serializationofcollectionpointer,serializationofcollectionchanges
Rid-bagspecificoperation.Sendbutdoesnotsavechangesofridbag.Retrievescomputedsizeofridbag.
SpecialuseofLINKSETtypes
NOTE.Since1.7rc1thisfeatureisdeprecated.UsageofRidBagispreferable.
Startingfrom1.0rc8-SNAPSHOTOrientDBcantransformcollectionsoflinksfromtheclassicmode:
[#10:3,#10:4,#10:5]
to:
(ORIDs@pageSize:16,root:#2:6)
Formoreinformationlookattheannouncementofthisnewfeature:https://groups.google.com/d/topic/orientdatabase/QF52JEwCuTM /discussion
Inpracticetooptimizecaseswithmanyrelationships/edgesthecollectionistransformedinamvrb-tree.Thisisbecausetheembedded
object.Inthatcasetheimportantthingisthelinktotherootnodeofthebalancedtree.
Youcandisablethisbehaviourbysetting
mvrbtree.ridBinaryThreshold=-1
Wheremvrbtree.ridBinaryThresholdisthethresholdwhereOrientDBwillusethetreeinsteadofplaincollection(asbefore).-1means
"hey,neverusethenewmodebutleaveallasbefore".
Treenodebinarystructure
Toimproveperformancethisstructureismanagedinbinaryform.Belowhowismade:
+-----------+-----------+--------+------------+----------+-----------+---------------------+
|TREESIZE|NODESIZE|COLOR.|PARENTRID|LEFTRID|RIGHTRID|RIDLIST..........|
+-----------+-----------+--------+------------+----------+-----------+---------------------+
|4bytes.|4bytes.|1byte|10bytes..|10bytes|10bytes.|10*MAX_SIZEbytes|
+-----------+-----------+--------+------------+----------+-----------+---------------------+
=39bytes+10*PAGE-SIZEbytes
Where:
TREESIZEassignedinteger(4bytes)containingthesizeofthetree.Onlytherootnodehasthisvalueupdated,sotoknowthe
529
BinaryProtocol
sizeofthecollectionyouneedtoloadtherootnodeandgetthisfield.othernodescancontainnotupdatedvaluesbecauseupon
rotationofpiecesofthetree(madeduringtreerebalancing)therootcanchangeandtheoldrootwillhavethe"old"sizeasdirty.
NODESIZEassignedinteger(4bytes)containingnumberofentriesinthisnode.It'salways<=tothepage-sizedefinedatthetree
levelandequalsforallthenodes.Bydefaultpage-sizeis16items
COLORas1bytecontaining1=Black,0=Red.ToknowmoreaboutthemeaningofthislookatRed-BlackTrees
PARENTRIDasRID(10bytes)oftheparentnoderecord
LEFTRIDasRID(10bytes)oftheleftnoderecord
RIGHTRIDasRID(10bytes)oftherightnoderecord
RIDLIS TasthelistofRIDscontainingthereferencestotherecords.Thisispre-allocatedtotheconfiguredpage-size.Sinceeach
RIDtakes10bytes,apage-sizeof16means16x10bytes=160bytes
Thesizeofthetree-nodeondisk(andmemory)isfixedtoavoidfragmentation.Tocomputeit:39bytes+10*PAGE-SIZEbytes.For
apage-size=16you'llhave39+160=199bytes.
REQUEST_PUSH_LIVE_QUERY
(operation:byte)(query_token:int)(record-type:byte)(record-version:int)(cluster-id:short)(cluster-position:long)(record-conten
t:bytes)
where:
operationthetipeofoperationhappend,possiblevalues
LOADED=0
UPDATED=1
DELETED=2
CREATED=3
query_tokenthetokenthatidentifytherelativequeryofthepushmessage,itmatchtheresulttokenofthelivequerycommand
request.
record-typetypeoftherecord('d'or'b')
record-versionrecordversion
cluster-idrecordclusterid
cluster-positionrecordclusterpostion
record-contentrecordcontent
History
version33
Removedthetokendatafromerrorheandlingheaderincaseofnontokensession.Removedthedb-typefromREQUEST_DB_OPEN
addedREQUEST_DB_REOPEN
Version32
Addedsupportofstreamableresultsetincaseofsynccommand,addedanewresultoftype'i'thatstreamtheresultinthesamewayof
asyncresult.
Version31
Addednewcommandstomanipulateidexes:REQUEST_INDEX_GET,REQUEST_INDEX_PUTand
REQUEST_INDEX_REM OVE.
Version30
530
BinaryProtocol
AddednewcommandREQUEST_RECORD_LOAD_IF_VERSION_NOT_LATEST
Version29
AddedsupportsupportoflivequeryinREQUEST_COM M AND,addednewpushcommandREQUEST_PUSH_LIVE_QUERY
Version28
Sinceversion28theREQUEST_RECORD_LOADresponseorderischangedfrom: [(payload-status:byte)[(record-content:bytes)
(record-version:int)(record-type:byte)]*]+to: [(payload-status:byte)[(record-type:byte)(record-version:int)(recordcontent:bytes)]*]+
Version27
Sinceversion27isintroducedanextensiontoallowuseatokenbasedsession,ifthismodalityisenabledafewthingschangeinthe
modalitytheprotocolworks.
inthefirstnegotiationtheclientshouldaskforatokenbasedauthenticationusingthetoken-authflag
theserverwillreplywithatokenoranemptybytearraythatmeansthatitnotsupporttokenbasedsessionandisusingaold
stylesession.
iftheserverdon'tsendbackthetokentheclientcanfailordropbackthetheoldmodality.
foreachrequesttheclientshouldsendthetokenandthesessionId
thesessionIdisneededonlyformatcharesponsetoarequest
ifusedthetokentheconnectionscanbesharedbetweenusersanddbofthesameserver,notneededtohaveconnectionassociated
todbanduser.
protocolmethodschanged:
REQUEST_DB_OPEN
requestaddtokensessionflag
responseaddofthetoken
REQUEST_CONNECT
requestaddtokensessionflag
responseaddofthetoken
Version26
Addedcluster-idintheREQUEST_CREATE_RECORDresponse.
Version25
ReviewdserializationofindexchangesintheREQUEST_TX_COM M ITfordetais#2676Removeddoubleserializationofcommands
parameters,nowtheparametersaredirectlyserializedinadocumentseeNetworkBinaryProtocolCommandsand#2301
Version24
cluster-typeandcluster-dataSegmentIdparameterswereremovedfromresponseforREQUEST_DB_OPEN,
REQUEST_DB_RELOADrequests.
datasegment-idparameterwasremovedfromREQUEST_RECORD_CREATErequest.
type,locationanddatasegment-nameparameterswereremovedfromREQUEST_DATACLUSTER_ADDrequest.
REQUEST_DATASEGM ENT_ADDrequestwasremoved.
REQUEST_DATASEGM ENT_DROPrequestwasremoved.
531
BinaryProtocol
Version23
Addsupportof updateContentflagtoUPDATE_RECORDandCOM M IT
Version22
REQUEST_CONNECTandREQUEST_OPENnowsendthedocumentserializationformatthattheclientrequire
Version21
REQUEST_SBTREE_BONSAI_GET_ENTRIES_M AJOR(whichisusedtoiteratethroughSBTree)nowgets"pageSize"asint
aslastargument.Version20hadafixedpageSize=5.ThenewversionprovidesconfigurablepageSizebyclient.DefaultpageSize
valueforprotocol=20hasbeenchangedto128.
Version20
Ridbagcommandswereintroduced.
Save/commitwasadaptedtosupportclientnotificationsaboutchangesofcollectionpointers.
Version19
Serializedversionofserverexceptionissenttotheclient.
Version18
Abilitytosetclusteridduringclustercreationwasadded.
Version17
Synchronouscommandscansendfetchedrecordslikeasynchronousone.
Version16
StoragetypeisrequiredforREQUEST_DB_FREEZE,REQUEST_DB_RELEASE,REQUEST_DB_DROP,
REQUEST_DB_EXISTcommands.
Thisisrequiredtosupportplocalstorage.
Version15
SETtypesarestoredindifferentwaythenLIST.Beforerel.15bothwerestoredbetweensquaredbraces[]whilenowSETare
storedbetween<>
Version14
DB_OPENreturnsinformationaboutversionofOrientDBdeployedonserver.
Version13
Tosupportupcomingauto-shardingsupportfeaturefollowingchangesweredone
532
BinaryProtocol
RECORD_LOADflagtosupportabilitytoloadtombstoneswasadded.
DATACLUSTER_COUNTflagtosupportabilitytocounttombstonesinclusterwasadded.
Version12
DB_OPENreturnsthedataSegmentIdforeachcluster
Version11
RECORD_CREATEalwaysreturnstherecordversion.Thiswasnecessarybecausenewrecordscouldhaveversion>0toavoid
M VCCproblemsonRIDrecycle
Compatibility
CurrentreleaseofOrientDBserversupportsolderclientversions.
version33:100%compatible2.2-SNAPSHOT
version32:100%compatible2.1-SNAPSHOT
version31:100%compatible2.1-SNAPSHOT
version30:100%compatible2.1-SNAPSHOT
version29:100%compatible2.1-SNAPSHOT
version28:100%compatible2.1-SNAPSHOT
version27:100%compatible2.0-SNAPSHOT
version26:100%compatible2.0-SNAPSHOT
version25:100%compatible2.0-SNAPSHOT
version24:100%compatible2.0-SNAPSHOT
version23:100%compatible2.0-SNAPSHOT
version22:100%compatible2.0-SNAPSHOT
version22:100%compatible2.0-SNAPSHOT
version21:100%compatible1.7-SNAPSHOT
version20:100%compatible1.7rc1-SNAPSHOT
version19:100%compatible1.6.1-SNAPSHOT
version18:100%compatible1.6-SNAPSHOT
version17:100%compatible.1.5
version16:100%compatible.1.5-SNAPSHOT
version15:100%compatible.1.4-SNAPSHOT
version14:100%compatible.1.4-SNAPSHOT
version13:100%compatible.1.3-SNAPSHOT
version12:100%compatible.1.3-SNAPSHOT
version11:100%compatible.1.0-SNAPSHOT
version10:100%compatible.1.0rc9-SNAPSHOT
version9:100%compatible.1.0rc9-SNAPSHOT
version8:100%compatible.1.0rc9-SNAPSHOT
version7:100%compatible.1.0rc7-SNAPSHOT-1.0rc8
version6:100%compatible.Before1.0rc7-SNAPSHOT
<version6:notcompatible
533
CSVSerialization
CSVSerialization
TheCSVserialzationistheformathowrecordareserializedintheorientdb0.and1.version.
Documentsareserializedinaproprietaryformat(asastring)derivedfromJSON,butmorecompact.Thestringretrievedfromthe
storagecouldbefilledwithspaces.Thisisduetotheoversizefeatureifitisset.Justignorethetailingspaces.
ToknowmoreabouttypeslookatSupportedtypes.
Thesearetherules:
Anystringcontentmustescapesomecharacters:
"->\"
\->\
Theclass,ifpresent,isatthebeginandmustendwith<code>@</code>.E.g. Customer@
EachFieldmustbepresentwithitsnameandvalueseparatedby :.E.g. name:"Barack"
Fieldsmustbeseparatedby ,.E.g. name:"Barack",surname:"Obama"
AllS tringsmustbeenclosedby "character.E.g. city:"Rome"
AllBinarycontent(likebyte[mustbeencodedinBase64andenclosedbyunderscore _character.E.g.
buffer:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGx.Sincev1.0rc7
Numbers(integer,long,short,byte,floats,double)areformattedasstringsasouputbytheJavatoString()method.Nothousands
separatormustbeused.Thedecimalseparatorisalways .Startingfromversion0.9.25,ifthetypeisnotinteger,asuffixisused
todistinguishtherighttypewhenunmarshalled:b=byte,s=short,l=long,f=float,d=double,c=BigDecimal(since1.0rc8).E.g.
salary:120.3for code:124b.
OutputofFloats
OutputofDoubles
OutputofBigDecimal
Booleansareexpressedas trueand falsealwaysinlower-case.Theyarerecognizedasbooleansincethetexthasnodouble
quoteasisthecasewithstrings
DatesmustbeinthePOSIXformat(alsocalledUNIXformat:http://en.wikipedia.org/wiki/Unix_time).Arealwaysstoredaslongs
butendwith:
the't'characterwhenit'sDATETIM Etype(defaultinschema-lessmodewhenaDateobjectisused).Datetimehandlesthe
maximumprecisionuptomilliseconds.E.g. lastUpdate:1296279468000tisreadas2011-01-2905:37:48
the'a'characterwhenit'sDATEtype.Datehandlesuptodayasprecision.E.g. lastUpdate:1306281600000aisreadas2011-05-25
00:00:00(Availablesince1.0rc2)
RecordID(link)mustbeprefixedby #.ARecordIdalwayshastheformat <cluster-id>:<cluster-position>.E.g.
location:#3:2
Embeddeddocumentsareenclosedbyparenthesis (and )characters.E.g. (name:"rules").Note:beforeSVNrevision2007
(0.9.24-snapshot)only </code>characterswereusedtobeginandendtheembeddeddocument.*
Lists(arrayandlist)mustbeenclosedby [and ]characters.E.g. [1,2,3], [#10:3,#10:4]and [(name:"Luca")].Before
rel.15SETtypewasstoredasalist,butnowitusesownformat(seebelow)
S ets(collectionswithoutduplicates)mustbeenclosedby <and >characters.E.g. <1,2,3>, <#10:3,#10:4>and
<(name:"Luca")>.ThereisaspecialcasewhenuseLINKSETtypereportedindetailinSpecialuseofLINKSETtypessection.
Beforerel.15SETtypewasstoredasalist(seeupon).
Maps(asacollectionofentrieswithkey/value)mustbeenclosedin {and }characters.E.g. rules:
{"database":2,"database.cluster.internal":2</code>}(NB.tosetavaluepartofakey/valuepair,setittothetext"null",without
quotationmarks.Eg. rules:{"database_name":"fred","database_alias":null})
RidBagsaspecialcollectionforlinkmanagement.Representedas %(content:binary);wherethecontentisbinarydataencodedin
base64.Takealookatthemainpageformoredetails.
Nullfieldshaveanemptyvaluepartofthefield.E.g. salary_cloned:,salary:
[<class>@][,][<field-name>:<field-value>]*
Simpleexample(linebreaksintroducedsoit'svisibleonthispage):
534
CSVSerialization
Profile@nick:"ThePresident",follows:[],followers:[#10:5,#10:6],name:"Barack",surname:"Obama",
location:#3:2,invitedBy:,salary_cloned:,salary:120.3f
Complexexampleusedinschema(linebreaksintroducedsoit'svisibleonthispage):
name:"ORole",id:0,defaultClusterId:3,clusterIds:[3],properties:[(name:"mode",type:17,offset:0,
mandatory:false,notNull:false,min:,max:,linkedClass:,
linkedType:,index:),(name:"rules",type:12,offset:1,mandatory:false,notNull:false,min:,
max:,linkedClass:,linkedType:17,index:)]
OtherexampleofORolethatusesamap(linebreaksintroducedsoit'svisibleonthispage):
ORole@name:"reader",inheritedRole:,mode:0,rules:{"database":2,"database.cluster.internal":2,"database.cluster.orole":2,"databa
se.cluster.ouser":2,
"database.class.*":2,"database.cluster.*":2,"database.query":2,"database.command":2,
"database.hook.record":2}
Serialization
BelowtheserializationoftypesinJSONandBinaryformat(alwaysreferstolatestversionoftheprotocol).
Type
JS ONformat
Binarydescriptor
String
0
Valueendswith'b'.Example:23b
Short
10000
Valueendswith's'.Example:23s
Integer
1000000
Justthevalue.Example:234392
Long
1000000000
Valueendswith'l'.Example:23439223l
Float
100000.33333
Valueendswith'f'.Example:234392.23f
Double
100.33
Valueendswith'd'.Example:10020.2302d
Decimal
1000.3333
Valueendswith'c'.Example:234.923c
Boolean
true
'true'or'false'.Example:true
Date
1436983328000
Valueinmillisecondsendswith'a'.Example:1436983328000a
Datetime
1436983328000
Valueinmillisecondsendswith't'.Example:1436983328000t
Binary
base64encodedbinary,like:
"A3ERjRFdc0023Kc"
Bytessurroundedwith _characters.Example: _2332322 _
Link
#10:3
JusttheRID.Example:#10:232
Linklist
[#10:3,#10:4]
Collectionsvaluesseparatedbycommasandsurroundedbybrackets"[]".
Example:[#10:3,#10:6]
Linkset
Example: [#10:3,#10:6]
Example: <#10:3,#10:4>
Linkmap
Example: {"name":"#10:3"}
M apentriesseparatedbycommasandsurroundedbycurlybraces"{}".
Example: {"Jay":#10:3,"Mike":#10:6}
Embedded
{"Jay":"#10:3","Mike":"#10:6"}
Embedded
list
Example: [20,30]
Collectionsofvaluesseparatedbycommasandsurroundedbybrackets"[
]".Example: [20,30]
Embedded
set
['is','a','test']
Collectionsofvaluesseparatedbycommasandsurroundedbyminorand
major"<>".Example: Embedded
map
{"name":"Luca"}
M apofvaluesseparatedbycommasandsurroundedbycurlybraces"{
}".Example: {"key1":23,"key2":2332}
Custom
base64encodedbinary,like:
"A3ERjRFdc0023Kc"
-
Embeddeddocumentserializedsurroundedbyparenthesis"()".Example:
({"Jay":#10:3,"Mike":#10:6})
535
CSVSerialization
536
SchemalessSerialization
SchemalessSerialization
Thebinaryschemalessserializationisanattempttodefineaserializationformatthatcanserializeadocumentcontainingallthe
informationaboutthestructureandthedatawithsupportforpartialserialization/deserialization.
Thetypesdescribedherearedifferentfromthetypesusedinthebinaryprotocol.
Aserializedrecordhasthefollowingshape:
(serialization-version:byte)(class-name:string)(header:byte[])(data:byte[])
Version
1bytethatcontainstheversionofthecurrentserialization(inordertoallowprogressiveserializationupgrades).
ClassName
Astringcontainingthenameoftheclassoftherecord.Iftherecordhasnoclass, class-namewillbejustanemptystring.
Header
Theheadercontainsalistoffieldsoftheserializedrecords,alongwiththeirpositioninthe datafield.Theheaderhasthefollowing
shape:
(field:field-definition)+
Where field-definitionhasthisshape:
(field-type:varint)(field-contents:byte[])
Thefieldcontentsdependonthevalueofthe field-typevarint.Oncedecodedtoaninteger,itsvaluecanbe:
0-signalstheendoftheheader
apositivenumber i-signalsthatwhatfollowsisanamedfield(andit'sthelengthofthefieldname,seebelow)
anegativenumber i-signalsthatwhatfollowsisaproperty(anditencodesthepropertyid,seebelow)
Namedfields
Namedfieldsareencodedas:
(field-name:string)(pointer-to-data-structure:int32)(data-type:byte)
field-name-thenameofthefield.The field-typevarintisincludedin field-name(asperthestringencoding)asmentioned
above.
pointer-to-data-structure-apointertothedatastructureforthecurrentfieldinthe datasegment.It's 0ifthefieldisnull.
data-type-thetypeidofthetypeofthevalueforthecurrentfield.Thesupportedtypes(withtheirids)aredefinedinthis
section.
Properties
Propertiesareencodedas:
(property-id:varint)(pointer-to-data-structure:int32)
537
SchemalessSerialization
property-id-isthe field-typedescribedabove.It'sanegativevaluethatencodesapropertyid.Decodingofthisvalueintothe
correspondingpropertyidcanbedoneusingthisformula: (property-id*-1)-1.Thepropertyidentifiedbythisidwillbe
foundintheschema(withitsnameanditstype),storedinthe globalPropertiesfieldattherootofthedocumentthatrepresents
theschemadefinition.
pointer-to-data-structure-apointertothedatastructureforthecurrentfieldinthe datasegment.It's 0ifthefieldisnull.
Data
Thedatasegmentiswherethevaluesofthefieldsarestored.It'sanarrayofdatastructures(eachwithatypedescribedbythe
correspondingfield).
(data:data-structure[])
Eachtypeisserializeddifferently,asdescribedbelow.
Typeserialization
SHORT,INTEGER,LONG
Integersareencodedusingthevarint(withZigZag)algorithmusedbyGoogle'sProtoBuf(andspecifiedhere).
BYTE
Bytesisstoredraw,assinglebytes.
BOOLEAN
Booleansareserializedusingasinglebyte, 0meaningfalseand 1meaningtrue.
FLOAT
Thisisstoredasflatbytearraycopyingthememoryfromthefloatmemory.
(float:byte[4])
DOUBLE
Thisisstoredasflatbytearraycopyingthememoryfromthedoublememory.
(double:byte[8])
DATETIME
Thedateisconvertedtomilliseconds(fromtheUnixepoch)andstoredasthetypeLONG.
DATE
Thedateisconvertedtoseconds(fromtheUnixepoch),movedtomidnightUTC+0,dividedby86400(thenumberofsecondsinaday)
andstoredasthetypeLONG.
STRING
Stringsarestoredasbinarystructures(encodedasUTF-8).Stringsareprecededbytheirsize(inbytes).
(size:varint)(string:byte[])
538
SchemalessSerialization
size-thenumberofthebytesinthestringstoredasavarint
string-thebytesofthestringencodedasUTF-8
BINARY
BytearraysarestoredlikeSTRINGs.
(size:varint)(bytes:byte[])
size-thenumberofthebytestostore
bytes-therawbytes
EMBEDDED
Embeddeddocumentsareserializedusingtheprotocoldescribedinthisdocument(recursively).Theserializeddocumentisjustabyte
array.
(serialized-document:bytes[])
EMBEDDEDLIST,EMBEDDEDSET
Theembeddedcollectionsarestoredasanarrayofbytesthatcontaintheserializeddocumentintheembeddedmode.
(size:varint)(collection-type:byte)(items:item[])
size-thenumberofitemsinthelist/set
collection-type-thetypeoftheelementsinthelistorANYifthetypeisunknown.
itemsanarrayofvaluesserializedbytypeorifthetypeofthecollectionisANYtheitemwillhaveit'sownstructure.
The itemdatastructurehasthefollowingshape:
(data-type:byte)(data:byte)
data-type-thetypeidofthedataintheitem
data-thedataintheitemserializedaccordingtothedata-type
EMBEDDEDMAP
M apscanhavekeyswiththefollowingtypes:
STRING
SHORT
INTEGER
LONG
BYTE
DATE
DATETIM E
DECIM AL
FLOAT
DOUBLE
Asofnowthough,allkeysareconvertedtoS TRINGs.
AnEM BEDDEDM APisserializedasanheaderandalistofvalues.
(size:varint)(header:header-structure)(values:byte[][])
size-thenumberofkey-valuepairsinthemap
539
SchemalessSerialization
header-serializedas (key-type:byte)(key-value:byte[])(pointer-to-data:int32)(value-type:byte)(where pointer-to-datais
thesameastheoneintheheader,offsettingfromthestartofthetop-leveldocument).
values-thevaluesserializedaccordingtotheirtype.
LINK
Thelinkisstoredastwo64bitintegers:theclusteridandtherecord'spositioninthecluster.
(cluster-id:int64)(record-position:int64)
LINKLIST,LINKSET
Linkcollections(listsandsets)areserializedasthesizeofthecollectionandthenalistofLINKs.
(size:varint)(links:LINK[])
LINKMAP
M apsoflinkscanhavekeyswiththefollowingtypes:
STRING
SHORT
INTEGER
LONG
BYTE
DATE
DATETIM E
DECIM AL
FLOAT
DOUBLE
Asofnowthough,allkeysareconvertedtoS TRINGs.
ALINKM APisserializedasthenumberofkey-valuepairsandthenthelistofkey-valuepairs.
(size:varint)(key-value-pairs:key-value[])
A key-valuepairisserializedas:
(key-type:byte)(key-value:byte[])(link:LINK)
key-type-thetypeidofthetypeofthekey
key-value-thevalueofthekey,serializedaccordingtokey-type
link-thelinkvalue
DECIMAL
Decimalsareconvertedtointegersandstoredasthescaleandthevalue.Forexample, 10234.546isstoreadasscale 3andvalue
10234546.
(scale:int32)(value-size:int32)(value:byte[])
scale-thescaleofthedecimal.
value-size-thenumberofbytesthatformthe value.
value-thebytesrepresentingthevalueofthedecimal(inbig-endianorder).
LINKBAG
540
SchemalessSerialization
Nodocumentationyet.:(
541
Commands
NetworkBinaryProtocolCommands
Thisistheguidetothecommandsyoucansendthroughthebinaryprotocol.
Seealso
ListofSQLCommands
NetworkBinaryProtocolSpecification
thecommandsaredividedinthreemaingroups:
SQL(select)Query
SQLCommands
Scriptcommands
SQL(Select)Query
(text:string)(non-text-limit:int)[(fetch-plan:string)](serialized-params:bytes[])
texttextoftheselectquery
non-text-limitLimitcanbesetinquery'stext,orhere.Thisfieldhadpriority.Send-1touselimitfromquery'stext
fetch-planusedonlyforselectqueries,otherwiseempty
serialized-paramsthebyte[]resultoftheserializationofaODocument.
S erializedParametersODocumentcontent
TheODocumenthavetocontainafieldcalled"params"oftypeM ap.
theM apshouldhaveaskey,incaseofpositionalperametersthenumericpositionoftheparameter,incaseofnamedparametersthe
nameoftheparameterandasvaluethevalueoftheparameter.
SQLCommands
(text:string)(has-simple-parameters:boolean)(simple-paremeters:bytes[])(has-complex-parameters:boolean)(complex-parameters:byt
es[])
texttextofthesqlcommand
has-simple-parametersbooleanflagfordetermineifthesimple-parametersbytearrayispresentornot
simple-parametersthebyte[]resultoftheserializationofaODocument.
has-complex-parametersbooleanflagfordetermineifthecomplex-parametersbytearrayispresentornot
complex-parametersthebyte[]resultoftheserializationofaODocument.
S erializedS impleParametersODocumentcontent
TheODocumenthavetocontainafieldcalled"parameters"oftypeM ap.
theM apshouldhaveaskey,incaseofpositionalperametersthenumericpositionoftheparameter,incaseofnamedparametersthe
nameoftheparameterandasvaluethevalueoftheparameter.
S erializedComplexParametersODocumentcontent
TheODocumenthavetocontainafieldcalled"compositeKeyParams"oftypeM ap.
theM apshouldhaveaskey,incaseofpositionalperametersthenumericpositionoftheparameter,incaseofnamedparametersthe
nameoftheparameterandasvalueaListthatisthelistofcompositeparameters.
Script
542
Commands
(language:string)(text:string)(has-simple-parameters:boolean)(simple-paremeters:bytes[])(has-complex-parameters:boolean)(compl
ex-parameters:bytes[])
languagethelanguageofthescriptpresentinthetextfield.AlltheothersparamentersareserializedastheSQLCommands
543
SQLReference
SQL
Whenitcomestoquerylanguages,SQListhemostlywidelyrecognizedstandard.Themajorityofdevelopershaveexperienceandare
comfortablewithSQL.ForthisreasonOrientDBusesSQLasit'squerylanguageandaddssomeextensionstoenablegraph
functionality.ThereareafewdifferencesbetweenthestandardSQLsyntaxandthatsupportedbyOrientDB,butforthemostpart,it
shouldfeelverynatural.ThedifferencesarecoveredintheOrientDBSQLdialectsectionofthispage.
M anySQLcommandssharetheWHEREcondition.KeywordsandclassnamesinOrientDBSQLarecaseinsensitive.Fieldnamesand
valuesarecasesensitive.Inthefollowingexampleskeywordsareinuppercasebutthisisnotstrictlyrequired.
IfyouarenotyetfamiliarwithSQL,wesuggestyoutogetthecourseonKhanAcademy.
Forexample,ifyouhaveaclass MyClasswithafieldnamed id,thenthefollowingSQLstatementsareequivalent:
SELECTFROMMyClassWHEREid=1
selectfrommyclasswhereid=1
ThefollowingisNOTequivalent.Noticethatthefieldname'ID'isnotthesameas'id'.
SELECTFROMMyClassWHEREID=1
Automaticusageofindexes
OrientDBallowsyoutoexecutequeriesagainstanyfield,indexedornot-indexed.TheSQLengineautomaticallyrecognizesifany
indexescanbeusedtospeedupexecution.Youcanalsoqueryanyindexesdirectlybyusing INDEX:<index-name>asatarget.Example:
SELECTFROMINDEX:myIndexWHEREkey='Jay'
Extraresources
SQLexpressionsyntax
Whereclause
Operators
Functions
Pagination
Pivoting-With-Query
SQLbatch
OrientDBSQLdialect
OrientDBsupportsSQLasaquerylanguagewithsomedifferencescomparedwithSQL.OrientTechnologiesdecidedtoavoidcreating
Yet-Another-Query-Language.InsteadwestartedfromfamiliarSQLwithextensionstoworkwithgraphs.Weprefertofocuson
standards.
IfyouwantlearnSQL,therearemanyonlinecoursessuchas:
OnlinecourseIntroductiontoDatabasesbyJenniferWidomfromStanforduniversity
IntroductiontoSQLatW3Schools
BeginnerguidetoSQL
SQLCourse.com
YouTubechannelBasicSQLTrainingbyJoeyBlue
Toknowmore,looktoOrientDBSQLSyntax.
Ororderanybooklikethese
544
SQLReference
JOINs
ThemostimportantdifferencebetweenOrientDBandaRelationalDatabaseisthatrelationshipsarerepresentedby LINKSinsteadof
JOINs.
Forthisreason,theclassicJOINsyntaxisnotsupported.OrientDBusesthe"dot( .)notation"tonavigate LINKS.Example1:In
SQLyoumightcreateajoinsuchas:
SELECT*
FROMEmployeeA,CityB
WHEREA.city=B.id
ANDB.name='Rome'
InOrientDBanequivalentoperationwouldbe:
SELECT*FROMEmployeeWHEREcity.name='Rome'
Thisismuchmorestraightforwardandpowerful!IfyouusemultipleJOINs,theOrientDBSQLequivalentwillbeanevenlarger
benefit.Example2:InSQLyoumightcreateajoinsuchas:
SELECT*
FROMEmployeeA,CityB,CountryC,
WHEREA.city=B.id
ANDB.country=C.id
ANDC.name='Italy'
InOrientDBanequivalentoperationwouldbe:
SELECT*FROMEmployeeWHEREcity.country.name='Italy'
Projections
InSQLprojectionsaremandatoryandyoucanusethestarcharacter *toincludeallofthefields.WithOrientDBthistypeof
projectionisoptional.Example:InSQLtoselectallofthecolumnsofCustomeryouwouldwrite:
SELECT*FROMCustomer
InOrientDBthe *isoptional:
SELECTFROMCustomer
DISTINCT
InSQL, DISTINCTisakeywordbutinOrientDBitisafunction,soifyourqueryis:
SELECTDISTINCTnameFROMCity
InOrientDByouwouldwrite:
SELECTDISTINCT(name)FROMCity
HAVING
OrientDBdoesnotsupportthe HAVINGkeyword,butwithanestedqueryit'seasytoobtainthesameresult.ExampleinSQL:
545
SQLReference
SELECTcity,sum(salary)ASsalary
FROMEmployee
GROUPBYcity
HAVINGsalary>1000
Thisgroupsallofthesalariesbycityandextractstheresultofaggregateswiththetotalsalarygreaterthan1,000dollars.InOrientDB
the HAVINGconditionsgoinaselectstatementinthepredicate:
SELECTFROM(SELECTcity,SUM(salary)ASsalaryFROMEmployeeGROUPBYcity)WHEREsalary>1000
Selectfrommultipletargets
OrientDBallowsonlyoneclass(classesareequivalenttotablesinthisdiscussion)asopposedtoSQL,whichallowsformanytablesas
thetarget.Ifyouwanttoselectfrom2classes,youhavetoexecute2subqueriesandjointhemwiththe UNIONALLfunction:
SELECTFROME,V
InOrientDB,youcanaccomplishthiswithafewvariabledefinitionsandbyusingthe expandfunctiontotheunion:
SELECTEXPAND($c)LET$a=(SELECTFROME),$b=(SELECTFROMV),$c=UNIONALL($a,$b)
Querymetadata
OrientDBprovidesthe metadata:targettoretrieveinformationaboutOrientDB'smetadata:
schema,togetclassesandproperties
indexmanager,togetinformationaboutindexes
Querytheschema
Getalltheconfiguredclasses:
selectexpand(classes)frommetadata:schema
----+-----------+---------+----------------+----------+--------+--------+----------+----------+------------+---------#|name|shortName|defaultClusterId|strictMode|abstract|overSize|clusterIds|properties|customFields|superClass
----+-----------+---------+----------------+----------+--------+--------+----------+----------+------------+---------0|UserGroup|null|13|false|false|0.0|[1]|[2]|null|V
1|WallPost|null|15|false|false|0.0|[1]|[4]|null|V
2|Owner|null|12|false|false|0.0|[1]|[1]|null|E
3|OTriggered|null|-1|false|true|0.0|[1]|[0]|null|null
4|E|E|10|false|false|0.0|[1]|[0]|null|null
5|OUser|null|5|false|false|0.0|[1]|[4]|null|OIdentity
6|OSchedule|null|7|false|false|0.0|[1]|[7]|null|null
7|ORestricted|null|-1|false|true|0.0|[1]|[4]|null|null
8|AssignedTo|null|11|false|false|0.0|[1]|[1]|null|E
9|V|null|9|false|false|2.0|[1]|[0]|null|null
10|OFunction|null|6|false|false|0.0|[1]|[5]|null|null
11|ORole|null|4|false|false|0.0|[1]|[4]|null|OIdentity
12|ORIDs|null|8|false|false|0.0|[1]|[0]|null|null
13|OIdentity|null|-1|false|true|0.0|[1]|[0]|null|null
14|User|null|14|false|false|0.0|[1]|[2]|null|V
----+-----------+---------+----------------+----------+--------+--------+----------+----------+------------+----------
GetalltheconfiguredpropertiesfortheclassOUser:
546
SQLReference
selectexpand(properties)from(
selectexpand(classes)frommetadata:schema
)wherename='OUser'
----+--------+----+---------+--------+-------+----+----+------+------------+----------#|name|type|mandatory|readonly|notNull|min|max|regexp|customFields|linkedClass
----+--------+----+---------+--------+-------+----+----+------+------------+----------0|status|7|true|false|true|null|null|null|null|null
1|roles|15|false|false|false|null|null|null|null|ORole
2|password|7|true|false|true|null|null|null|null|null
3|name|7|true|false|true|null|null|null|null|null
----+--------+----+---------+--------+-------+----+----+------+------------+-----------
Getonlytheconfigured customFieldspropertiesforOUser(assumingyouaddedCUSTOM metadatalikefoo=bar):
selectcustomFieldsfrom(
selectexpand(classes)frommetadata:schema
)wherename="OUser"
----+------+-----------#|@CLASS|customFields
----+------+-----------0|null|{foo=bar}
----+------+------------
Or,ifyouwishtogetonlytheconfigured customFieldsofanattribute,likeifyouhadacommentforthepasswordattributeforthe
OUserclass.
selectcustomFieldsfrom(
selectexpand(properties)from(
selectexpand(classes)frommetadata:schema
)wherename="OUser"
)wherename="password"
----+------+---------------------------------------------------#|@CLASS|customFields
----+------+---------------------------------------------------0|null|{comment=FooBaryourpasswordtokeepitsecure!}
----+------+----------------------------------------------------
Querytheavailableindexes
Getalltheconfiguredindexes:
selectexpand(indexes)frommetadata:indexmanager
----+------+------+--------+---------+---------+------------------------------------+----------------------------------------------------#|@RID|mapRid|clusters|type|name|indexDefinition|indexDefinitionClass
----+------+------+--------+---------+---------+------------------------------------+----------------------------------------------------0|#-1:-1|#2:0|[0]|DICTIO...|dictio...|{keyTypes:[1]}|com.orientechnologies.orient.core.index.O
SimpleKeyI...
1|#-1:-1|#1:1|[1]|UNIQUE|OUser....|{className:OUser,field:name,keyTy...|com.orientechnologies.orient.core.index.O
PropertyIn...
2|#-1:-1|#1:0|[1]|UNIQUE|ORole....|{className:ORole,field:name,keyTy...|com.orientechnologies.orient.core.index.O
PropertyIn...
----+------+------+--------+---------+---------+------------------------------------+-----------------------------------------
547
CRUDOperations
SQL
M ostNoSQLproductsemployacustomquerylanguage.Inthis,OrientDBdiffersbyfocusingonstandardsinquerylanguages.Thatis,
insteadofinventing"YetAnotherQueryLanguage,"itbeginswiththewidelyusedandwell-understoodlanguageofSQL.Itthen
extendsSQLtosupportmorecomplexgraphingconcepts,suchasTreesandGraphs.
WhySQL?BecauseSQLisubiquitousinthedatabasedevelopmentworld.Itisfamiliarandmorereadableandconcisethanits
competitors,suchasM apReducescriptsorJSONbasedquerying.
SELECT
The SELECTstatementqueriesthedatabaseandreturnsresultsthatmatchthegivenparameters.Forinstance,earlierinGettingStarted,
twoquerieswerepresentedthatgavethesameresults: BROWSECLUSTERouserand BROWSECLASSOUser.Hereisathirdoption,
availablethrougha SELECTstatement.
orientdb>SELECTFROMOUser
Noticethatthequeryhasnoprojections.Thismeansthatyoudonotneedtoenteracharactertoindicatethatthequeryshouldreturn
theentirerecord,suchastheasteriskintheRelationalmodel,(thatis, SELECT*FROMOUser).
Additionally,OUserisaclass.Bydefault,OrientDBexecutesqueriesagainstclasses.Targetscanalsobe:
ClustersToexecuteagainstacluster,ratherthanaclass,prefix CLUSTERtothetargetname.
orientdb>SELECTFROMCLUSTER:Ouser
RecordIDToexecuteagainstoneormoreRecordID's,usetheidentifier(s)asyourtarget.Forexample.
orientdb>SELECTFROM#10:3
orientdb>SELECTFROM[#10:1,#10:30,#10:5]
IndexesToexecuteaqueryagainstanindex,prefix INDEXtothetargetname.
orientdb>SELECTVALUEFROMINDEX:dictionaryWHEREkey='Jay'
WHERE
M uchlikethestandardimplementationofSQL,OrientDBsupports WHEREconditionstofilterthereturningrecordstoo.Forexample,
orientdb>SELECTFROMOUserWHEREnameLIKE'l%'
Thisreturnsall OUserrecordswherethenamebeginswith l.Formoreinformationonsupportedoperatorsandfunctions,see
WHERE.
ORDERBY
Inadditionto WHERE,OrientDBalsosupports ORDERBYclauses.Thisallowsyoutoordertheresultsreturnedbythequeryaccording
tooneormorefields,ineitherascendingordescendingorder.
orientdb>SELECTFROMEmployeeWHEREcity='Rome'ORDERBYsurnameASC,nameASC
Theexamplequeriesthe Employeeclass,itreturnsalistingofallemployeesinthatclasswholiveinRomeanditorderstheresultsby
surnameandname,inascendingorder.
548
CRUDOperations
GROUPBY
Intheeventthatyouneedresultsofthequerygroupedtogetheraccordingtothevaluesofcertainfields,youcanmanagethisusingthe
GROUPBYclause.
orientdb>SELECTSUM(salary)FROMEmployeeWHEREage<40GROUPBYjob
Intheexample,youquerythe Employeeclassforthesumofthesalariesofallemployeesundertheageofforty,groupedbytheirjob
types.
LIMIT
Intheeventthatyourqueryreturnstoomanyresults,makingitdifficulttoreadormanage,youcanusethe LIMITclausetoreduceit
tothetopmostofthereturnvalues.
orientdb>SELECTFROMEmployeeWHEREgender='male'LIMIT20
Intheexample,youquerythe Employeeclassforalistofmaleemployees.Giventhattherearelikelytobeanumberofthese,you
limitthereturntothefirsttwentyentries.
SKIP
Whenusingthe LIMITclausewithqueries,youcanonlyviewthetopmostofthereturnresults.Intheeventthatyouwouldliketo
viewcertainresultsfurtherdownthelist,forinstancethevaluesfromtwentytoforty,youcanpaginateyourresultsusingthe SKIP
keywordinthe LIMITclause.
orientdb>SELECTFROMEmployeeWHEREgender='male'LIMIT20
orientdb>SELECTFROMEmployeeWHEREgender='male'SKIP20LIMIT20
orientdb>SELECTFROMEmployeeWHEREgender='male'SKIP40LIMIT20
Thefirstqueryreturnsthefirsttwentyresults,thesecondreturnsthenexttwentyresults,thethirduptosixty.Youcanusethese
queriestomanagepagesattheapplicationlayer.
INSERT
The INSERTstatementaddsnewdatatoaclassandcluster.OrientDBsupportsthreeformsofsyntaxusedtoinsertnewdataintoyour
database.
ThestandardANSI-93syntax:
orientdb>INSERTINTOEmployee(name,surname,gender)
VALUES('Jay','Miner','M')
ThesimplifiedANSI-92syntax:
orientdb>INSERTINTOEmployeeSETname='Jay',surname='Miner',gender='M'
TheJSONsyntax:
orientdb>INSERTINTOEmployeeCONTENT{name:'Jay',surname:'Miner',
gender:'M'}
EachofthesequeriesaddsJayM inertothe Employeeclass.Youcanchoosewhicheversyntaxthatworksbestwithyourapplication.
549
CRUDOperations
UPDATE
The UPDATEstatementchangesthevaluesofexistingdatainaclassandcluster.InOrientDBtherearetwoformsofsyntaxusedto
updatedataonyourdatabase.
ThestandardANSI-92syntax:
orientdb>UPDATEEmployeeSETlocal=TRUEWHEREcity='London'
TheJSONsyntax,usedwiththe MERGEkeyword,whichmergesthechangeswiththecurrentrecord:
orientdb>UPDATEEmployeeMERGE{local:TRUE}WHEREcity='London'
Eachofthesestatementsupdatesthe Employeeclass,changingthe localpropertyto TRUEwhentheemployeeisbasedinLondon.
DELETE
The DELETEstatementremovesexistingvaluesfromyourclassandcluster.OrientDBsupportsthestandardANSI-92compliant
syntaxforthesestatements:
orientdb>DELETEFROMEmployeeWHEREcity<>'London'
Here,entriesareremovedfromthe EmployeeclasswheretheemployeeinquestionisnotbasedinLondon.
S eealso:
TheSQLReference
TheConsoleCommandReference
550
Select
SELECT
OrientDBsupportstheSQLlanguagetoexecutequeriesagainstthedatabaseengine.Formoreinformation,seeoperatorsandfunctions.
FormoreinformationonthedifferencesbetweenthisimplementationandtheSQL-92standard,seeOrientDBSQL.
S yntax:
SELECT[<Projections>][FROM<Target>[LET<Assignment>*]]
[WHERE<Condition>*]
[GROUPBY<Field>*]
[ORDERBY<Fields>*[ASC|DESC]*]
[UNWIND<Field>*]
[SKIP<SkipRecords>]
[LIMIT<MaxRecords>]
[FETCHPLAN<FetchPlan>]
[TIMEOUT<Timeout>[<STRATEGY>]
[LOCKdefault|record]
[PARALLEL]
[NOCACHE]
<Projections>Indicatesthedatayouwanttoextractfromthequeryastheresult-set.Note:InOrientDB,thisvariableis
optional.
FROMDesignatestheobjecttoquery.Thiscanbeaclass,cluster,singleRecprdID,setofRecordID's,or(beginninginversion
1.7.7)indexvaluessortedbyascendingordescendingkeyorder.
Whenqueryingaclass,for <target>usetheclassname.
Whenqueryingacluster,for <target>use CLUSTER:<cluster-name>.Thiscausesthequerytoexecuteonlyonrecordsin
thatcluster.
WhenqueryingrecordID's,youcanspecificoneorasmallsetofrecordstoquery.Thisisusefulwhenyouneedtospecifya
startingpointinnavigatinggraphs.
Whenqueryingindexes,usethefollowingprefixes:
INDEXVALUES:<index>and INDEXVALUESASC:<index>sortsvaluesintoanascendingorderofindexkeys.
INDEXVALUESDESC:<index>sortsthevaluesintoadescendingorderofindexkeys.
WHEREDesignatesconditionstofiltertheresult-set.
LETBindscontextvariablestouseinprojections,conditionsorsub-queries.
GROUPBYDesignatesfieldonwhichtogrouptheresult-set.Inthecurrentrelease,youcanonlygroupononefield.
ORDERBYDesignatesthefieldwithwhichtoordertheresult-set.Usetheoptional ASCand DESCoperatorstodefinethe
directionoftheorder.Thedefaultisascending.Additionally,ifyouareusingaprojection,youneedtoincludethe ORDERBYfield
intheprojection.NotethatORDERBYworksonlyonprojectionfields(fieldsthatarereturnedintheresultset)notonLET
variables.
UNWINDDesignatesthefieldonwhichtounwindthecollection.Introducedinversion2.1.
SKIPDefinesthenumberofrecordsyouwanttoskipfromthestartoftheresult-set.Youmayfindthisusefulinpagination,
whenusingitinconjunctionwith LIMIT.
LIMITDefinesthemaximumnumberofrecordsintheresult-set.Youmayfindthisusefulinpagination,whenusingitin
conjunctionwith SKIP.
FETCHPLANDefineshowyouwantittofetchresults.Formoreinformation,seeFetchingStrategy.
TIMEOUTDefinesthemaximumtimeinmillisecondsforthequery.Bydefault,querieshavenotimeouts.Ifyoudon'tspecifya
timeoutstrategy,itdefaultsto EXCEPTION.Thesearetheavailabletimeoutstrategies:
RETURNTruncatetheresult-set,returningthedatacollecteduptothetimeout.
EXCEPTIONRaisesanexception.
LOCKDefinesthelockingstrategy.Thesearetheavailablelockingstrategies:
DEFAULTLockstherecordfortheread.
RECORDLockstherecordinexclusivemodeforthecurrenttransaction,untilthetransactioncommitsoryouperforma
rollbackoperation.
PARALLELExecutesthequeryagainstxconcurrentthreads,wherexreferstothenumberofprocessorsorcoresfoundonthehost
operatingsystemofthequery.Youmayfind PARALLELexecutionusefulonlongrunningqueriesorqueriesthatinvolvemultiple
cluster.Forsimplequeries,using PARALLELmaycauseaslowdownduetotheoverheadinherentinusingmultiplethreads.
NOCACHEDefineswhetheryouwanttoavoidusingthecache.
551
Select
NOTE:Beginningwithversion1.0rc7,the RANGEoperatorwasremoved.Toexecuterangequeries,insteadusethe BETWEEN
operatoragainst @RID.Formoreinformation,seePagination.
Examples:
Returnallrecordsoftheclass Person,wherethenamestartswith Luk:
orientdb>SELECTFROMPersonWHEREnameLIKE'Luk%'
Alternatively,youmightalsouseeitherofthesequeries:
orientdb>SELECTFROMPersonWHEREname.left(3)='Luk'
orientdb>SELECTFROMPersonWHEREname.substring(0,3)='Luk'
Returnallrecordsofthetype !AnimalTypewherethecollection racescontainsatleastoneentrywherethefirstcharacteris
e,ignoringcase:
orientdb>SELECTFROManimaltypeWHEREracesCONTAINS(name.toLowerCase().subString(
0,1)='e')
Returnallrecordsoftype !AnimalTypewherethecollection racescontainsatleastoneentrywithnames Europeanor
Asiatic:
orientdb>SELECT*FROManimaltypeWHEREracesCONTAINS(namein['European',
'Asiatic'])
Returnallrecordsintheclass Profilewhereanyfieldcontainstheword danger:
orientdb>SELECTFROMProfileWHEREANY()LIKE'%danger%'
Returnanyrecordatanylevelthathastheword danger:
DEPRECIATEDSYNTAX
orientdb>SELECTFROMProfileWHEREANY()TRAVERSE(ANY()LIKE'%danger%')
Returnanyrecordwhereuptothethirdlevelofconnectionshassomefieldthatcontainstheword danger,ignoringcase:
orientdb>SELECTFROMProfileWHEREANY()TRAVERSE(0,3)(
ANY().toUpperCase().indexOf('danger')>-1)
Returnallresultsonclass Profile,orderedbythefield nameindescendingorder:
orientdb>SELECTFROMProfileORDERBYnameDESC
Returnthenumberofrecordsintheclass Accountpercity:
orientdb>SELECTSUM(*)FROMAccountGROUPBYcity
Traverserecordsfromarootnode:
orientdb>SELECTFROM11:4WHEREANY()TRAVERSE(0,10)(address.city='Rome')
Returnonlyalimitedsetofrecords:
552
Select
orientdb>SELECTFROM[#10:3,#10:4,#10:5]
Returnthreefieldsfromtheclass Profile:
orientdb>SELECTnick,followings,followersFROMProfile
Returnthefield nameinuppercaseandthefieldcountrynameofthelinkedcityoftheaddress:
orientdb>SELECTname.toUppercase(),address.city.country.nameFROMProfile
Returnrecordsfromtheclass Profileindescendingorderoftheircreation:
orientdb>SELECTFROMProfileORDERBY@ridDESC
Beginninginversion1.7.7,OrientDBcanopenaninversecursoragainstclusters.Thisisveryfastanddoesn'trequiretheclassic
orderingresources,CPUandRAM .
Projections
InthestandardimplementationsofSQL,projectionsaremandatory.InOrientDB,theomissionofprojectstranslatestoitsreturningthe
entirerecord.Thatis,itreadsnoprojectionastheequivalentofthe *wildcard.
orientdb>SELECTFROMAccount
Forallprojectionsexceptthewildcard *,itcreatesanewtemporarydocument,whichdoesnotincludethe @ridand @version
fieldsoftheoriginalrecord.
orientdb>SELECTname,ageFROMAccount
Thenamingconventionforthereturneddocumentfieldsare:
Fieldnameforplainfields,like invoicebecoming invoice.
Firstfieldnameforchainedfields,like invoice.customer.namebecoming invoice.
Functionnameforfunctions,like MAX(salary)becoming max.
Intheeventthatthetargetfieldexists,itusesanumericprogression.Forinstance,
orientdb>SELECTMAX(incoming),MAX(cost)FROMBalance
------+-----max|max2
------+-----1342|2478
------+------
Tooverridethedisplayforthefieldnames,usethe AS.
553
Select
orientdb>SELECTMAX(incoming)ASmax_incoming,MAX(cost)ASmax_costFROMBalance
---------------+---------max_incoming|max_cost
---------------+---------1342|2478
---------------+----------
Withthedollarsign $,youcanaccessthecontextvariables.Eachtimeyourunthecommand,OrientDBaccessesthecontexttoread
andwritethevariables.Forinstance,sayyouwanttodisplaythepathanddepthlevelsuptothefifthofa TRAVERSEonallrecordsin
the Movieclass.
orientdb>SELECT$path,$depthFROM(TRAVERSE*FROMMovieWHERE$depth
LETBlock
The LETblockcontainscontextvariablestoassigneachtimeOrientDBevaluatesarecord.Itdestroysthesevaluesoncethequery
executionends.Youcanusecontextvariablesinprojections,conditions,andsub-queries.
AssigningFieldsforReuse
OrientDBallowsforcrossingrelationships.Insinglequeries,youneedtoevaluatethesamebranchofthenestedrelationship.Thisis
betterthanusingacontextvariablethatreferstothefullrelationship.
orientdb>SELECTFROMProfileWHEREaddress.city.nameLIKE'%Saint%"'AND
(address.city.country.name='Italy'OR
address.city.country.name='France')
Usingthe LETmakesthequeryshorterandfaster,becauseittraversestherelationshipsonlyonce:
orientdb>SELECTFROMProfileLET$city=address.cityWHERE$city.nameLIKE
'%Saint%"'AND($city.country.name='Italy'OR$city.country.name='France')
Inthiscase,ittraversesthepathtill address.cityonlyonce.
Sub-query
The LETblockallowsyoutoassignacontextvariabletotheresultofasub-query.
orientdb>SELECTFROMDocumentLET$temp=(SELECT@rid,$depthFROM(TRAVERSE
V.OUT,E.INFROM$parent.current)WHERE@class='Concept'AND
(id='firstconcept'ORid='secondconcept'))WHERE$temp.SIZE()>0
LETBlockinProjection
Youcanusecontextvariablesaspartofaresult-setinprojections.Forinstance,thequerybelowdisplaysthecitynamefromthe
previousexample:
orientdb>SELECT$temp.nameFROMProfileLET$temp=address.cityWHERE$city.name
LIKE'%Saint%"'AND($city.country.name='Italy'OR
$city.country.name='France')
554
Select
Unwinding
Beginningwithversion2.1,OrientDBallowsunwindingofcollectionfieldsandobtainingmultiplerecordsasaresult,oneforeach
elementinthecollection:
orientdb>SELECTname,OUT("Friend").nameASfriendNameFROMPerson
--------+------------------name|friendName
--------+------------------'John'|['Mark','Steve']
--------+-------------------
Intheeventifyouwantonerecordforeachelementin friendName,youcanrewritethequeryusing UNWIND:
orientdb>SELECTname,OUT("Friend").nameASfriendNameFROMPersonUNWINDfriendName
--------+------------name|friendName
--------+------------'John'|'Mark'
'John'|'Steve'
--------+-------------
NOTE:FormoreinformationonotherSQLcommands,seeSQLcommands.
History
1.7.7:Newtargetprefixes INDEXVALUES:, INDEXVALUESASC:and INDEXVALUESDESC:added.
1.7: PARALLELkeywordaddedtoexecutethequeryagainstxconcurrentthreads,wherexisthenumberofprocessorsorcores
foundontheoperatingsystemwherethequeryruns. PARALLELexecutionisusefulonlongrunningqueriesorqueriesthatinvolve
multipleclusters.Onsimplequeries,using PARALLELcancauseaslowdownduetotheoverheadofusingmultiplethreads.
555
Insert
INSERT
The INSERTcommandcreatesanewrecordinthedatabase.Recordscanbeschema-lessorfollowrulesspecifiedinyourmodel.
S yntax:
INSERTINTO[CLASS:]<class>|CLUSTER:<cluster>|INDEX:<index>
[(<field>[,]*)VALUES(<expression>[,]*)[,]*]|
[SET<field>=<expression>|<sub-command>[,]*]|
[CONTENT{<JSON>}]
[RETURN<expression>]
[FROM<query>]
CONTENTDefinesJSONdataasanoptiontosetfieldvalues.
RETURNDefinesanexpressiontoreturninsteadofthenumberofinsertedrecords.YoucanuseanyvalidSQLexpression.The
mostcommonuse-cases,
@ridReturnstheRecordIDofthenewrecord.
@thisReturnstheentirenewrecord.
FROMDefineswhereyouwanttoinserttheresult-set.Introducedinversion1.7.
Examples:
Insertsanewrecordwiththename Jayandsurname Miner.
Asanexample,intheSQL-92standard,suchaswithaRelationaldatabase,youmightuse:
orientdb>INSERTINTOProfile(name,surname)
VALUES('Jay','Miner')
Alternatively,intheOrientDBabbreviatedsyntax,thequerywouldbewrittenas,
orientdb>INSERTINTOProfileSETname='Jay',surname='Miner'
InJSONcontentsyntax,itwouldbewrittenasthis,
orientdb>INSERTINTOProfileCONTENT{"name":"Jay","surname":"Miner"}
Insertanewrecordoftheclass Profile,butinadifferentclusterfromthedefault.
InSQL-92syntax:
orientdb>INSERTINTOProfileCLUSTERprofile_recent(name,surname)VALUES
('Jay','Miner')
Alternative,intheOrientDBabbreviatedsyntax:
orientdb>INSERTINTOProfileCLUSTERprofile_recentSETname='Jay',
surname='Miner'
Insertseveralrecordsatthesametime:
orientdb>INSERTINTOProfile(name,surname)VALUES('Jay','Miner'),
('Frank','Hermier'),('Emily','Sout')
Insertanewrecord,addingarelationship.
556
Insert
InSQL-93syntax:
orientdb>INSERTINTOEmployee(name,boss)VALUES('jack',#11:09)
IntheOrientDBabbreviatedsyntax:
orientdb>INSERTINTOEmployeeSETname='jack',boss=#11:99
Insertanewrecord,addacollectionofrelationships.
InSQL-93syntax:
orientdb>INSERTINTOProfile(name,friends)VALUES('Luca',[#10:3,#10:4])
IntheOrientDBabbreviatedsyntax:
orientdb>INSERTINTOProfilesSETname='Luca',friends=[#10:3,#10:4]
Insertsusing SELECTsub-queries
orientdb>INSERTINTODiverSETname='Luca',buddy=(SELECTFROMDiver
WHEREname='Marko')
Insertsusing INSERTsub-queries:
orientdb>INSERTINTODiverSETname='Luca',buddy=(INSERTINTODiver
SETname='Marko')
Insertingintoadifferentcluster:
orientdb>INSERTINTOCLUSTER:asiaemployee(name)VALUES('Matthew')
However,notethatthedocumenthasnoassignedclass.Tocreateadocumentofacertainclass,butinadifferentclusterthanthe
default,insteaduse:
orientdb>INSERTINTOCLUSTER:asiaemployee(@class,content)VALUES
('Employee','Matthew')
Thatinsertsthedocumentoftheclass Employeeintothecluster asiaemployee.
Insertanewrecord,addingitasanembeddeddocument:
orientdb>INSERTINTOProfile(name,address)VALUES('Luca',{"@type":"d",
"street":"MelroseAvenue","@version":0})
Insertfromaquery.
Tocopyrecordsfromanotherclass,use:
orientdb>INSERTINTOGermanyClientFROMSELECTFROMClientWHERE
country='Germany'
Thisinsertsalltherecordsfromtheclass ClientwherethecountryisGermany,intheclass GermanyClient.
Tocopyrecordsfromoneclassintoanother,whileaddingafield:
557
Insert
orientdb>INSERTINTOGermanyClientFROMSELECT*,trueAScopiedFROMClient
WHEREcountry='Germany'
Thisinsertsallrecordsfromtheclass ClientwherethecountryisGermanyintotheclass GermanClient,withtheadditionfield
copiedtothevalue true.
FormoreinformationonSQL,seeSQLcommands.
558
Update
UPDATE
Updateoneormorerecordsinthecurrentdatabase.Remember:OrientDBcanworkinschema-lessmode,soyoucancreateanyfield
on-the-fly.Furthermore,thecommandalsosupportsextensionstoworkoncollections.
S yntax:
UPDATE<class>|CLUSTER:<cluster>|<recordID>
[SET|INCREMENT|ADD|REMOVE|PUT<field-name>=<field-value>[,]*]|[CONTENT|MERGE<JSON>]
[UPSERT]
[RETURN<returning>[<returning-expression>]]
[WHERE<conditions>]
[LOCKdefault|record]
[LIMIT<max-records>][TIMEOUT<timeout>]
SETDefinesthefieldstoupdate.
INCREMENTIncrementsthefieldbythevalue.
Forinstance,recordat 10with INCREMENTvalue=3setsthenewvalueto 13.Youmayfindthisusefulinatomicupdatesof
counters.Usenegativenumberstodecrement.Additionally,youcanuse INCREMENTtoimplementsequencesandauto-increment.
ADDAddsanewitemincollectionfields.
REMOVERemovesanitemincollectionandmapfields.
PUTPutsanentryintoamapfield.
CONTENTReplacestherecordcontentwithaJSONdocument.
MERGEM ergestherecordcontentwithaJSONdocument.
LOCKSpecifieshowtolocktherecordbetweentheloadandupdate.Youcanuseoneofthefollowinglockstrategies:
DEFAULTNolock.Useintheeventofconcurrentupdates,theM VCCthrowsanexception.
RECORDLockstherecordduringtheupdate.
UPSERTUpdatesarecordifitexistsorinsertsanewrecordifitdoesn't.Thisavoidstheneedtoexecutetwocommands,(onefor
eachcondition,insertingandupdating).
UPSERTrequiresa WHEREclauseandaclasstarget.Therearefurtherlimitationson UPSERT,explainedbelow.
RETURNSpecifiesanexpressiontoreturninsteadoftherecordandwhattodowiththeresult-setreturnedbytheexpression.The
availablereturnoperatorsare:
COUNTReturnsthenumberofupdatedrecords.Thisisthedefaultreturnoperator.
BEFOREReturnstherecordsbeforetheupdate.
AFTERReturntherecordsaftertheupdate.
WHERE
LIMITDefinesthemaximumnumberofrecordstoupdate.
TIMEOUTDefinesthetimeyouwanttoallowtheupdaterunbeforeittimesout.
NOTE:TheRecordIDmusthavea #prefix.Forinstance, #12:3.
Examples:
Updatetochangethevalueofafield:
orientdb>UPDATEProfileSETnick='Luca'WHEREnickISNULL
Updated2record(s)in0.008000sec(s).
Updatetoremoveafieldfromallrecords:
orientdb>UPDATEProfileREMOVEnick
Updatetoaddavalueintoacollection:
559
Update
orientdb>UPDATEAccountADDaddress=#12:0
NOTE:Beginningwithversion2.0.5,theOrientDBservergeneratesaservererrorifthereisnospacebetween #andthe
=.Youmustwritethecommandas:
orientdb>UPDATEAccountADDaddress=#12:0
Updatetoremoveavaluefromacollection,ifyouknowtheexactvaluethatyouwanttoremove:
Removeanelementfromalinklistorset:
orientdb>UPDATEAccountREMOVEaddress=#12:0
Removeanelementfromalistorsetofstrings:
orientdb>UPDATEAccountREMOVEaddresses='Foo'
Updatetoremoveavalue,filteringonvalueattributes.
RemoveaddressesbasedinthecityofRome:
orientdb>UPDATEAccountREMOVEaddresses=addresses[city='Rome']
Updatetoremoveavalue,filteringbasedonpositioninthecollection.
orientdb>UPDATEAccountREMOVEaddresses=addresses[1]
Thisremovethesecondelementfromalist,(positionnumbersstartfrom 0,so addresses[1]isthesecondelelment).
Updatetoputamapentryintothemap:
orientdb>UPDATEAccountPUTaddresses='Luca',#12:0
Updatetoremoveavaluefromamap
orientdb>UPDATEAccountREMOVEaddresses='Luca'
Updateanembeddeddocument.The UPDATEcommandcantakeJSONasavaluetoupdate.
orientdb>UPDATEAccountSETaddress={"street":"MelroseAvenue","city":{
"name":"BeverlyHills"}}
Updatethefirsttwentyrecordsthatsatisfyacondition:
orientdb>UPDATEProfileSETnick='Luca'WHEREnickISNULLLIMIT20
Updatearecordorinsertifitdoesn'talreadyexist:
orientdb>UPDATEProfileSETnick='Luca'UPSERTWHEREnick='Luca'
Updateawebcounter,avoidingconcurrentaccesses:
560
Update
orientdb>UPDATECounterINCREMENTviews=1WHEREpages='/downloads/'
LOCKRECORD
Updatesusingthe RETURNkeyword:
orientdb>UPDATE♯7:0SETgender='male'RETURNAFTER@rid
orientdb>UPDATE♯7:0SETgender='male'RETURNAFTER@version
orientdb>UPDATE♯7:0SETgender='male'RETURNAFTER@this
orientdb>UPDATE♯7:0INCREMENTCounter=123RETURNBEFORE$current.Counter
orientdb>UPDATE♯7:0SETgender='male'RETURNAFTER$current.exclude(
"really_big_field")
orientdb>UPDATE♯7:0ADDout_Edge=♯12:1RETURNAFTER$current.outE("Edge")
Intheeventthatasinglefieldisreturned,OrientDBwrapstheresult-setinarecordstoringthevalueinthefield result.Thisavoids
introducinganewserialization,asthereisnoprimitivevaluescollectionserializationinthebinaryprotocol.Additionally,itprovides
usefulfieldslike versionand ridfromtheoriginalrecordincorrespondingfields.Thenewsyntaxallowsforoptimizationofclientservernetworktraffic.
FormoreinformationonSQLsyntax,see SELECT.
Limitationsofthe UPSERTClause
The UPSERTclauseonlyguaranteesatomicitywhenyouusea UNIQUEindexandperformthelook-upontheindexthroughthe WHERE
condition.
orientdb>UPDATEClientSETid=23UPSERTWHEREid=23
Here,youmusthaveauniqueindexon Client.idtoguaranteeuniquenessonconcurrentoperations.
561
Delete
DELETE
Removesoneormorerecordsfromthedatabase.Youcanrefinethesetofrecordsthatitremovesusingthe WHEREclause.
NOTE:Don'tuse DELETEtoremoveVerticesorEdges.Insteadusethe DELETEVERTEXor DELETEEDGEcommands,which
ensurestheintegrityofthegraph.
S yntax:
DELETEFROM<Class>|CLUSTER:<cluster>|INDEX:<index>[LOCK<default|record>][RETURN<returning>]
[WHERE<Condition>*][LIMIT<MaxRecords>][TIMEOUT<timeout>]
LOCKDetermineshowthedatabaselockstherecordbetweenloadanddelete.Ittakesoneofthefollowingvalues:
DEFAULTDefinesnolocksduringthedelete.Inthecaseofconcurrentdeletes,theM VCCthrowsanexception.
RECORDDefinesrecordlocksduringthedelete.
RETURNDefineswhatvaluesthedatabasereturns.Ittakesoneofthefollowingvalues:
COUNTReturnsthenumberofdeletedrecords.Thisisthedefaultoption.
BEFOREReturnsthenumberofrecordsbeforetheremoval.
WHEREFilterstotherecordsyouwanttodelete.
LIMITDefinesthemaximumnumberofrecordstodelete.
TIMEOUTDefinesthetimeperiodtoallowtheoperationtorun,beforeittimesout.
Examples:
Deleteallrecodswiththesurname unknown,ignoringcase:
orientdb>DELETEFROMProfileWHEREsurname.toLowerCase()='unknown'
Formoreinformation,seeSQLcommands.
562
M atch
SQL- MATCH
Queriesthedatabaseinadeclarativemanner,usingpatternmatching.Thisfeaturewasintroducedinversion2.2.
S implifiedS yntax
MATCH
{
[class:<class>],
[as:<alias>],
[where:(<whereCondition>)]
}
.<functionName>(){
[class:<className>],
[as:<alias>],
[where:(<whereCondition>)],
[while:(<whileCondition>)]
[maxDepth:<number>]
}*
RETURN<alias>[,<alias>]*
LIMIT<number>
<class>Definesavalidtargetclass.
as:<alias>Definesanaliasforanodeinthepattern.
<whereCondition>Definesafilterconditiontomatchanodeinthepattern.ItsupportsthenormalSQL WHEREclause.Youcan
alsousethe $currentMatchand $matchedcontextvariables.
<functionName>Definesagraphfunctiontorepresenttheconnectionbetweentwonodes.Forinstance, out(), in(), outE(),
inE(),etc.
<whileCondition>Definesaconditionthatthestatementmustmeettoallowthetraversalofthispath.Itsupportsthenormal
SQL WHEREclause.Youcanalsousethe $currentMatch, $matchedand $depthcontextvariables.Formoreinformation,see
DeepTraversalWhileCondition,below.
<maxDepth>Definesthemaximumdepthforthissinglepath.
RETURN<alias>Defineselementsinthepatternthatyouwantreturned.Itcanuseoneofthefollowing:
Aliasesdefinedinthe as:block.
$matchesIndicatingalldefinedaliases.
$pathsIndicatingthefulltraversedpaths.
BNFS yntax
MatchStatement:=(<MATCH>MatchExpression(<COMMA>MatchExpression)*<RETURN>Identifier(<COMMA>Identifier)*(Lim
it)?)
MatchExpression:=(MatchFilter((MatchPathItem|MultiMatchPathItem))*)
MatchPathItem:=(MethodCall(MatchFilter)?)
MatchPathItemFirst:=(FunctionCall(MatchFilter)?)
MultiMatchPathItem:=(<DOT><LPAREN>MatchPathItemFirst(MatchPathItem)*<RPAREN>(MatchFilter)?)
MatchFilter:=(<LBRACE>(MatchFilterItem(<COMMA>MatchFilterItem)*)?<RBRACE>)
MatchFilterItem:=((<CLASS><COLON>Expression)|(<AS><COLON>Identifier)|(<WHERE><COLON><LPAREN>(WhereClau
se)<RPAREN>)|(<WHILE><COLON><LPAREN>(WhereClause)<RPAREN>)|(<MAXDEPTH><COLON>Integer))
Examples
Thefollowingexamplesarebasedonthissampledata-setfromtheclass People:
563
M atch
FindallpeoplewiththenameJohn:
orientdb>MATCH{class:Person,as:people,where:(name='John')}
RETURNpeople
--------people
--------#12:0
#12:1
---------
FindallpeoplewiththenameJohnandthesurnameSmith:
564
M atch
orientdb>MATCH{class:Person,as:people,where:(name='John'AND
surname='Smith')}RETURNpeople
------people
------#12:1
-------
FindpeoplenamedJohnwiththeirfriends:
orientdb>MATCH{class:Person,as:person,where:
(name='John')}.both('Friend'){as:friend}
RETURNperson,friend
--------+--------people|friend
--------+--------#12:0|#12:1
#12:0|#12:2
#12:0|#12:3
#12:1|#12:0
#12:1|#12:2
--------+---------
Findfriendsoffriends:
orientdb>MATCH{class:Person,as:person,where:(name='John'AND
surname='Doe')}.both('Friend').both('Friend')
{as:friendOfFriend}RETURNperson,friendOfFriend
--------+---------------people|friendOfFriend
--------+---------------#12:0|#12:0
#12:0|#12:1
#12:0|#12:2
#12:0|#12:3
#12:0|#12:4
--------+----------------
Findpeople,excludingthecurrentuser:
565
M atch
orientdb>MATCH{class:Person,as:person,where:(name='John'AND
surname='Doe')}.both('Friend').both('Friend'){as:friendOfFriend,
where:($matched.person!=$currentMatch)}
RETURNperson,friendOfFriend
--------+---------------people|friendOfFriend
--------+---------------#12:0|#12:1
#12:0|#12:2
#12:0|#12:3
#12:0|#12:4
--------+----------------
Findfriendsoffriendstothesixthdegreeofseparation:
orientdb>MATCH{class:Person,as:person,where:(name='John'AND
surname='Doe')}.both('Friend'){as:friend,
where:($matched.person!=$currentMatch)while:($depth<6)}
RETURNperson,friend
--------+--------people|friend
--------+--------#12:0|#12:0
#12:0|#12:1
#12:0|#12:2
#12:0|#12:3
#12:0|#12:4
--------+---------
Findingfriendsoffriendstosixdegreesofseparation,sinceaparticulardate:
orientdb>MATCH{class:Person,as:person,
where:(name='John')}.(bothE('Friend'){
where:(date<?)}.bothV()){as:friend,
while:($depth<6)}RETURNperson,friend
Inthiscase,thecondition $depth<6referstotraversingtheblock bothE('Friend')sixtimes.
Findfriendsofmyfriendswhoareaslomyfriends,usingmultiplepaths:
orientdb>MATCH{class:Person,as:person,where:(name='John'AND
surname='Doe')}.both('Friend').both('Friend'){as:friend},
{as:person}.both('Friend'){as:friend}
RETURNperson,friend
--------+-------people|friend
--------+-------#12:0|#12:1
#12:0|#12:2
--------+--------
Inthiscase,thestatementmatchestwoexpression:thefirsttofriendsoffriends,thesecondtodirectfriends.Eachexpression
sharesthecommonaliases( personand friend).Tomatchthewholestatement,theresultmustmatchbothexpressions,where
thealiasvaluesforthefirstexpressionarethesameasthatofthesecond.
566
M atch
FindcommonfriendsofJohnandJenny:
orientdb>MATCH{class:Person,where:(name='John'AND
surname='Doe')}.both('Friend'){as:friend}.both('Friend')
{class:Person,where:(name='Jenny')}RETURNfriend
-------friend
-------#12:1
--------
Thesame,withtwomatchexpressions:
orientdb>MATCH{class:Person,where:(name='John'AND
surname='Doe')}.both('Friend'){as:friend},
{class:Person,where:(name='Jenny')}.both('Friend')
{as:friend}RETURNfriend
ContextVariables
Whenrunningthesequeries,youcanuseanyofthefollowingcontextvariables:
Variable
Description
$matched
Givesthecurrentmatchedrecord.Youmustexplicitlydefinetheattributesforthisrecordinordertoaccess
them.Youcanusethisinthe where:and while:conditionstorefertocurrentpartialmatchesoraspart
ofthe RETURNvalue.
$currentMatch
Givesthecurrentcompletenodeduringthematch.
$depth
Givesthetraversaldepth,followingasinglepathitemwherea while:conditionisdefined.
UseCases
ExpandingAttributes
Youcanrunthisstatementasasub-queryinsideofanotherstatement.Doingthisallowsyoutoobtaindetailsandaggregatedatafrom
theinner SELECTquery.
orientdb>SELECTperson.nameASname,person.surnameASsurname,
friend.nameASfriendName,friend.surnameASfriendSurname
FROM(MATCH{class:Person,as:person,
where:(name='John')}.both('Friend'){as:friend}
RETURNperson,friend)
--------+----------+------------+--------------name|surname|friendName|friendSurname
--------+----------+------------+--------------John|Doe|John|Smith
John|Doe|Jenny|Smith
John|Doe|Frank|Bean
John|Smith|John|Doe
John|Smith|Jenny|Smith
--------+----------+------------+---------------
IncompleteHierarchy
567
M atch
Considerbuildingadatabaseforacompanythatshowsahierarchyofdepartmentswithinthecompany.Forinstance,
[manager]department
(employeesindepartment)
[m0]0
(e1)
/\
/\
/\
[m1]1[m2]2
(e2,e3)(e4,e5)
/\/\
3456
(e6)(e7)(e8)(e9)
/\
[m3]78
(e10)(e11)
/
9
(e12,e13)
Thislooselyshowsthat,
Department 0isthecompanyitself,manager0( m0)istheCEO
e10worksatdepartment 7,hismanageris m3
e12worksatdepartment 9,thisdepartmenthasnodirectmanager,so e12'smanageris m3(theuppermanager)
Inthiscase,youwouldusethefollowingquerytofindoutwho'sthemanagertoaparticularemployee:
orientdb>SELECTEXPAND(manager)FROM(MATCH{class:Employee,
where:(name=?)}.out('WorksAt').out('ParentDepartment')
{while:(out('Manager').size()==0),
where:(out('Manager').size()>0)}.out('Manager')
{as:manager}RETURNmanager)
DeepTraversal
M atchpathitemsactinadifferentmanners,dependingonwhetherornotyouuse while:conditionsinthestatement.
Forinstance,considerthefollowinggraph:
[name='a']-FriendOf->[name='b']-FriendOf->[name='c']
Runningthefollowingstatementonthisgraphonlyreturns b:
orientdb>MATCH{class:Person,where:(name='a')}.out("FriendOf")
{as:friend}RETURNfriend
-------friend
-------b
--------
Whatthismeansisthatittraversesthepathitem out("FriendOf")exactlyonce.Itonlyreturnstheresultofthattraversal.
Ifyouadda whilecondition:
568
M atch
orientdb>MATCH{class:Person,where:(name='a')}.out("FriendOf")
{as:friend,while:($depth
--------friend
--------a
b
---------
Includinga while:conditiononthematchpathitemcausesOrientDBtoevaluatethisitemaszerotontimes.Thatmeansthatit
returnsthestartingnode,( a,inthiscase),astheresultofzerotraversal.
Toexcludethestartingpoint,youneedtoadda where:condition,suchas:
orientdb>MATCH{class:Person,where:(name='a')}.out("FriendOf")
{as:friend,while:($depth0)}
RETURNfriend
Asageneralrule,
whileConditions:Definethisifitmustexecutethenexttraversal,(itevaluatesatlevelzero,ontheoriginnode).
whereCondition:Definethisifthecurrentelement,(theoriginnodeatthezeroiterationtherightnodeontheiterationisgreater
thanzero),mustbereturnedasaresultofthetraversal.
Forinstance,supposethatyouhaveagenealogicaltree.Inthetree,youwanttoshowaperson,grandparentandthegrandparentofthat
grandparent,andsoon.Theresult:sayingthatthepersonisatlevelzero,parentsatlevelone,grandparentsatleveltwo,etc.,you
wouldseeallancestorsonevenlevels.Thatis, level%2==0.
Togetthis,youmightusethefollowingquery:
orientdb>MATCH{class:Person,where:(name='a')}.out("Parent")
{as:ancestor,while:(true)where:($depth%2=0)}
RETURNancestor
Bestpractices
Queriescaninvolvemultipleoperations,basedonthedomainmodelandusecase.Insomecases,likeprojectionandaggregation,you
caneasilymanagethemwitha SELECTquery.Withothers,suchaspatternmatchinganddeeptraversal, MATCHstatementsaremore
appropriate.
Use SELECTand MATCHstatementstogether(thatis,throughsub-queries),togiveeachstatementthecorrectresponsibilities.Here,
FilteringRecordAttributesforaSingleClass
Filteringbasedonrecordattributesforasingleclassisatrivialoperationthroughbothstatements.Thatis,findingallpeoplenamed
Johncanbewrittenas:
orientdb>SELECTFROMPersonWHEREname='John'
Youcanalsowriteitas,
orientdb>MATCH{class:Person,as:person,where:(name='John')}
RETURNperson
Theefficiencyremainsthesame.Bothqueriesuseanindex.With SELECT,youobtainexpandedrecords,whilewith MATCH,youonly
obtaintheRecordID's.
569
M atch
FilteringonRecordAttributesofConnectedElements
Filteringbasedontherecordattributesofconnectedelements,suchasneighboringvertices,cangrowtrickwhenusing SELECT,while
with MATCHitissimple.
Forinstance,findallpeoplelivinginRomethathaveafriendcalledJohn.Therearethreedifferentwaysyoucanwritethis,using
SELECT:
orientdb>SELECTFROMPersonWHEREBOTH('Friend').nameCONTAINS'John'
ANDout('LivesIn').nameCONTAINS'Rome'
orientdb>SELECTFROM(SELECTBOTH('Friend')FROMPersonWHEREname
'John')WHEREout('LivesIn').nameCONTAINS'Rome'
orientdb>SELECTFROM(SELECTin('LivesIn')FROMCityWHEREname='Rome')
WHEREBOTH('Friend').nameCONTAINS'John'
Inthefirstversion,thequeryismorereadable,butitdoesnotuseindexes,soitislessoptimalintermsofexecutiontime.Thesecond
andthirduseindexesiftheyexist,(on Person.nameor City.name,bothinthesub-query),butthey'rehardertoread.Whichindex
theyusedependsonlyonthewayyouwritethequery.Thatis,ifyouonlyhaveanindexon City.nameandnot Person.name,the
secondversiondoesn'tuseanindex.
Usinga MATCHstatement,thequerybecomes:
orientdb>MATCH{class:Person,where:(name='John')}.both("Friend")
{as:result}.out('LivesIn'){class:City,where:(name='Rome')}
RETURNresult
Here,thequeryexecutoroptimizesthequeryforyou,choosingindexeswheretheyexist.M oreover,thequerybecomesmorereadable,
especiallyincomplexcases,suchasmultiplenested SELECTqueries.
TRAVERSEAlternative
Therearesimilarlimitationstousing TRAVERSE.Youmaybenefitfromusing MATCHasanalternative.
Forinstance,considerasimple TRAVERSEstatement,like:
orientdb>TRAVERSEout('Friend')FROM(SELECTFROMPersonWHEREname='John')
WHILE$depth<3
Usinga MATCHstatement,youcanwritethesamequeryas:
orientdb>MATCH{class:Person,where:(name='John')}.both("Friend")
{as:friend,while:($depth<3)}RETURNfriend
Consideracasewhereyouhavea sincedatepropertyontheedge Friend.Youwanttotraversetherelationshiponlyforedges
wherethe sincevalueisgreaterthanagivendate.Ina TRAVERSEstatement,youmightwritethequeryas:
orientdb>TRAVERSEbothE('Friend')[since>date('2012-07-02','yyyy-MM-dd')].bothV()
FROM(SELECTFROMPersonWHEREname='John')WHILE$depth<3
Unforunately,thisstatementDOESN"TWORKinthecurrentrelease.However,youcangettheresultsyouwantusinga MATCH
statement:
570
M atch
orientdb>MATCH{class:Person,where:(name='John')}.(bothE("Friend")
{where:(since>date('2012-07-02','yyyy-MM-dd'))}.bothV())
{as:friend,while:($depth<3)}RETURNfriend
ProjectionsandGroupingOperations
Projectionsandgroupingoperationsarebetterexpressedwitha SELECTquery.Ifyouneedtofilteranddoprojectionoraggregationin
thesamequery,youcanuse SELECTand MATCHinthesamestatement.
Thisisparticularimportantwhenyouexpectaresultthatcontainsattributesfromdifferentconnectedrecords(cartesianproduct).FOr
instance,toretrievenames,theirfriendsandthedatesincetheybecamefriends:
orientdb>SELECTperson.nameASname,friendship.sinceASsince,friend.name
ASfriendFROM(MATCH{class:Person,as:person}.bothE('Friend')
{as:friendship}.bothV(){as:friend,
where:($matched.person!=$currentMatch)}
RETURNperson,friendship,friend)
571
Commands
SQLCommands
CRUD
Graph
S chema
Indexes
Database
Utility
SELECT
CREATE
VERTEX
CREATE
CLASS
CREATE
INDEX
CREATECLUSTER
CREATELINK
INSERT
CREATE
EDGE
ALTER
CLASS
REBUILD
INDEX
ALTERCLUSTER
FIND
REFERENCES
UPDATE
DELETE
VERTEX
DROPCLASS
DROP
INDEX
DROPCLUSTER
EXPLAIN
DELETE
DELETE
EDGE
CREATE
PROPERTY
ALTERDATABASE
GRANT
TRAVERSE
M ATCH
ALTER
PROPERTY
CREATEDATABASE
(consoleonly)
REVOKE
DROP
PROPERTY
DROPDATABASE
(consoleonly)
CREATE
FUNCTION
TRUNCATE
CLASS
TRUNCATE
CLUSTER
OPTIM IZEDATABASE
TRUNCATE
RECORD
572
AlterClass
SQL- ALTERCLASS
Updatesattributesonanexistingclassintheschema.
S yntax
ALTERCLASS<class><attribute-name><attribute-value>
<class>Definestheclassyouwanttochange.
<attribute-name>Definestheattributeyouwanttochange.Foralistofsupportedattributes,seethetablebelow.
<attribute-value>Definesthevalueyouwanttoset.
Examples
Defineasuper-class:
orientdb>ALTERCLASSEmployeeSUPERCLASSPerson
Definemultipleinheritances:
orientdb>ALTERCLASSEmployeeSUPERCLASSPerson,ORestricted
Thisfeaturewasintroducedinversion2.1.
Addasuper-class:
orientdb>ALTERCLASSEmployeeSUPERCLASS+Person
Thisfeaturewasintroducedinversion2.1.
Removeasuper-class:
orientdb>ALTERCLASSEmployeeSUPERCLASS-Person
Thisfeaturewasintroducedinversion2.1.
Updatetheclassnamefrom Accountto Seller:
orientdb>ALTERCLASSAccountNAMESeller
Updatetheoversizefactorontheclass Account:
orientdb>ALTERCLASSAccountOVERSIZE2
Addaclustertotheclass Account.
orientdb>ALTERCLASSAccountADDCLUSTERaccount2
Intheeventthattheclusterdoesnotexist,itautomaticallycreatesit.
Removeaclusterfromtheclass AccountwiththeID 34:
orientdb>ALTERCLASSAccountREMOVECLUSTER34
Addcustomproperties:
573
AlterClass
orientdb>ALTERCLASSPostCUSTOMonCreate.fields=_allowRead,_allowUpdate
orientdb>ALTERCLASSPostCUSTOMonCreate.identityType=role
Createanewclusterfortheclass Employee,thensettheclusterselectionstrategyto balanced:
orientdb>CREATECLUSTERemployee_1
orientdb>ALTERCLASSEmployeeADDCLUSTERemployee_1
orientdb>ALTERCLASSEmployeeCLUSTERSELECTIONbalanced
Converttheclass TheClasstoanabstractclass:
orientdb>ALTERCLASSTheClassABSTRACTtrue
Formoreinformationsee CREATECLASS, DROPCLASS, ALTERCLUSTERcommands.Formoreinformationonothercommands,
see ConsoleandSQLcommands.
SupportedAttributes
Attribute
Type
S upport
Description
NAME
String
Changestheclassname.
SHORTNAME
String
Definesashortname,(thatis,analias),fortheclass.Use NULLtoremovea
shortnameassignment.
SUPERCLASS
String
Definesasuper-classfortheclass.Use NULLtoremoveasuper-class
assignment.Beginningwithversion2.1,itsupportsmultipleinheritances.To
addanewclass,youcanusethesyntax +<class>,toremoveituse <class>.
OVERSIZE
Decimal
number
Definestheoversizefactor.
ADDCLUSTER
String
Addsaclustertotheclass.Iftheclusterdoesn'texist,itcreatesaphysical
cluster.Addingclusterstoaclassisalsousefulinstoringrecordsin
distributedservers.Formoreinformation,seeDistributedSharding.
REMOVECLUSTER
String
Removesaclusterfromaclass.Itdoesnotdeletethecluster,onlyremovesit
fromtheclass.
Enalbesordisablesstrictmode.Wheninstrictmode,youworkinschemafullmodeandcannotaddnewpropertiestoarecordifthey'repartofthe
class'schemadefinition.
STRICTMODE
1.7
CLUSTERSELECTION
Definescustomproperties.Propertynamesandvaluesmustfollowthe
syntax <property-name>=<value>withoutspacesbetweenthenameand
value.
CUSTOM
ABSTRACT
Definestheselectionstrategyinchoosingwhichclusteritusesfornew
records.Onclasscreationitinheritsthesettingfromthedatabase.Formore
information,seeClusterSelection.
Boolean
Convertsclasstoanabstractclassortheopposite.
JavaAPI
InadditiontoupdatingaclassthroughtheconsoleorSQL,youcanalsochangeitthroughtheJavaAPI,usingeithertheGraphor
DocumentAPI.
GraphAPI:
574
AlterClass
//ADDACLUSTERTOAVERTEXCLASS
graph.getVertexType("Customer").addCluster("customer_usa");
//ADDACLUSTERTOANEDGECLASS
graph.getEdgeType("WorksAt").addCluster("WorksAt_2015");
DocumentAPI
db.getMetadata().getSchema().getClass("Customer").addCluster("customer_usa")
History
2.1
Addedsupportformultipleinheritance.
1.7
Addedsupportfor CLUSTERSELECTIONthatsetsthestrategyusedonselectingtheclustertousewhencreatingnewrecords.
575
AlterCluster
SQL- ALTERCLUSTER
Updatesattributesonanexistingcluster.
S yntax
ALTERCLUSTER<cluster><attribute-name><attribute-value>
<cluster>Definestheclusteryouwanttochange.YoucanuseitslogicalnameorID.Beginningwithversion2.2,youcanusethe
wildcard *toupdatemultipleclusterstogether.
<attribute-name>Definestheattributeyouwanttochange.Foralistofsupportedattributes,seethetablebelow.
<attribute-value>Definesthevalueyouwanttoset.
Examples
Changethenameofacluster,usingitsname:
orientdb>ALTERCLUSTERprofileNAMEprofile2
Changethenameofacluster,usingitsID:
orientdb>ALTERCLUSTER9NAMEprofile2
Updatetheclusterconflictstrategyto automerge:
orientdb>ALTERCLUSTERVCONFLICTSTRATEGYautomerge
Putcluster V_2012offline:
orientdb>ALTERCLUSTERV_2012STATUSOFFLINE
Updatemultipleclusterswithasimilarname:
orientdb>ALTERCLUSTERemployee*statusoffline
Formoreinformationsee, CREATECLUSTER, DROPCLUSTER, ALTERCLUSTERcommands.Formoreinformationonother
commands,seeConsoleandSQLcommands.
SupportedAttributes
576
AlterCluster
Name
Type
S upport
Description
String
Changestheclustername.
String
Changestheclusterstatus.Allowedvaluesare ONLINEand
OFFLINE.Bydefault,clustersareonline.Whenoffline,OrientDB
nolongeropensthephysicalfilesforthecluster.Youmayfind
thisusefulwhenyouwanttoarchiveolddataelsewhereand
restorewhenneeded.
COMPRESSION
String
Definesthecompressiontypetouse.Allowedvaluesare
NOTHING, SNAPPY, GZIP,andanyothercompressiontypes
registeredinthe OCompressionFactoryclass.OrientDBclassthe
compress()methodeachtimeitsavestherecordtothestorage,
andthe uncompress()methodeachtimeitloadstherecordfrom
storage.Youcanalsousethe OCompressioninterfacetomanage
encryption.
USE_WAL
Boolean
DefineswhetheritusestheJournal(WriteAheadLog)when
OrientDBoperatesagainstthecluster.
RECORD_GROW_FACTOR
Integer
Definesthegrowfactortosavemorespaceonrecordcreation.
Youmayfindthisusefulwhenyouupdatetherecordwith
additionalinformation.Inlargerrecords,thisavoids
defragmentation,asOrientDBdoesn'thavetofindnewspacein
theeventofupdateswithmoredata.
RECORD_OVERFLOW_GROW_FACTOR
Integer
Definesgrowfactoronupdates.Whenitreachesthesizelimit,is
usesthissettingtogetmorespace,(factor>1).
String
Definesthestrategyitusestohandleconflictsintheeventthat
OrientDBM VCCfindsanupdateoradeleteoperationitexecutes
againstanoldrecord.Ifyoudon'tdefineastrategyattheclusterlevel,itusesthedatabase-levelconfiguration.Formore
informationonsupportedstrategies,seethesectionbelow.
NAME
STATUS
CONFLICTSTRATEGY
2.0+
SupportedConflictStrategies
S trategy
Description
version
Throwsanexceptionwhenversionsaredifferent.Thisisthedefaultsetting.
content
Intheeventthattheversionsaredifferent,itchecksforchangesinthecontent,otherwiseitusesthehighest
versiontoavoidthrowinganexception.
automerge
M ergesthechanges.
ToknowmoreaboutotherSQLcommands,takealookatSQLcommands.
577
AlterDatabase
SQL- ALTERDATABASE
Updatesattributesonthecurrentdatabase.
S yntax
ALTERDATABASE<attribute-name><attribute-value>
<attribute-name>Definestheattributethatyouwanttochange.Foralistofsupportedattributes,seethesectionbelow.
<attribute-value>Definesthevalueyouwanttoset.
Examples
DisablenewSQLstrictparser:
orientdb>ALTERDATABASECUSTOMstrictSQL=false
UpdateaGraphdatabasethatwascreatedbeforeversion1.4:
orientdb>ALTERDATABASECUSTOMuseLightweightEdges=FALSE
orientdb>ALTERDATABASECUSTOMuseClassForEdgeLabel=FALSE
orientdb>ALTERDATABASECUSTOMuseClassForVertexLabel=FALSE
orientdb>ALTERDATABASECUSTOMuseVertexFieldsForEdgeLabel=FALSE
Version1.4introducedLightweightEdges,whichwasdisabledbydefaultbeginninginversion2.0.Usetheabovecommands
tomaintaincompatibilitywhenusingolderdatabaseswithnewerversionsofOrientDB.
Tocreateadatabase,seethe CREATEDATABASE.Toremoveadatabase,seethe DROPDATABASEcommand.Formoreinformation
onothercommands,seeConsoleandSQLcommands.
SupportedAttributes
S TATUS database'sstatusbetween:
CLOS EDtosetclosedstatus
IMPORTINGtosetimportingstatus
OPENtosetopenstatus
DEFAULTCLUS TERIDtosetthedefaultcluster.Bydefaultis2="default"
DATEFORMATsetsthedefaultdateformat.LookatJavaDateFormatformoreinformation.Defaultis"yyyy-M M -dd"
DATETIMEFORMATsetsthedefaultdatetimeformat.LookatJavaDateFormatformoreinformation.Defaultis"yyyy-M M ddHH:mm:ss"
TIMEZONEsetthedefaulttimezone.LookatJavaDateTimeZonesformoreinformation.DefaultistheJVM 'sdefaulttimezone
LOCALECOUNTRYsetsthedefaultlocalecountry.LookatJavaLocalesformoreinformation.DefaultistheJVM 'sdefault
localecountry.Example:"GB"
LOCALELANGUAGEsetsthedefaultlocalelanguage.LookatJavaLocalesformoreinformation.DefaultistheJVM 'sdefault
localelanguage.Example:"en"
CHARS ETsetthedefaultcharsetcharset.LookatJavaCharsetformoreinformation.DefaultistheJVM 'sdefaultcharset.
Example:"utf8"
CLUS TERS ELECTIONsetsthedefaultstrategyusedonselectingtheclusterwheretocreatenewrecords.Thissettingisreadon
classcreation.Aftercreation,eachclasshasownmodifiablestrategy.Supportedstrategiesare:
default,usesalwaystheClass's defaultClusterIdproperty.Thiswasthedefaultbefore1.7
round-robin,puttheClass'sconfiguredclustersinaringandreturnsadifferentclustereverytimerestartingfromthefirst
whentheringiscompleted
balanced,checkstherecordsinalltheclustersandreturnsthesmallercluster.Thisallowstheclustertohaveallthe
underlyingclustersbalancedonsize.Onaddinganewclustertoanexistentclass,thenewemptyclusterwillbefilledbefore
578
AlterDatabase
theothersbecausemoreemptythentheothers.Indistributedconfigurationwhenconfigureclustersondifferentserversthis
settingallowstokeeptheserverbalancedwiththesameamountofdata.Calculationofclustersizeismadeevery5ormore
secondstoavoidtoslowdowninsertion
MINIMUMCLUS TERS ,astheminimumnumberofclusterstocreateautomaticallywhenanewclassiscreated.Bydefaultis1,
butonmultiCPU/corehavingmultipleclusters/filesimprovesread/writeperformance
CONFLICTS TRATEGY,(sincev2.0)isthenameofthestrategyusedtohandleconflictswhenOrientDB'sM VCCfindsan
updateordeleteoperationexecutedagainstanoldrecord.Thestrategyisappliedfortheentiredatabase,butsingleclusterscan
haveownstrategy(useALTERCLUSTERcommandforthis).Whileit'spossibletoinjectcustomlogicbywritingaJavaclass,the
outoftheboxmodesare:
version,thedefault,throwanexceptionwhenversionsaredifferent
content,incasetheversionisdifferentchecksifthecontentischanged,otherwiseusethehighestversionandavoid
throwingexception
automerge,mergesthechanges
CUS TOMsetscustomproperties
VALIDATION,(Sincev2.2)disableorenablethevalidationfortheentiredatabase.Thissettingisnotpersistent,soatthenext
restartthevalidationisactive(Default).Disablingthevalidationsometimesisneededincaseofremoteimportdatabase.
History
1.7
Addssupportfor CLUSTERSELECTIONthatsetsthestrategyusedonselectingtheclusterwheretocreatenewrecords.
Adds MINIMUMCLUSTERStopre-createXclusterseverytimeanewclassiscreated.
579
AlterProperty
SQL- ALTERPROPERTY
Updatesattributesontheexistingpropertyandclassintheschema.
S yntax
ALTERPROPERTY<class>.<property><attribute-name><attribute-value>
<class>Definestheclasstowhichthepropertybelongs.
<property>Definesthepropertyyouwanttoupdate.
<attribute-name>Definestheattributeyouwanttochange.
<attribute-value>Definesthevalueyouwanttosetontheattribute.
Examples
Changethenameoftheproperty ageintheclass Accountto born:
orientdb>ALTERPROPERTYAccount.ageNAMEborn
Updateapropertytomakeitmandatory:
orientdb>ALTERPROPERTYAccount.ageMANDATORYTRUE
DefineaRegularExpressionasconstraint:
orientdb>ALTERPROPERTYAccount.genderREGEXP"[M|F]"
Defineafieldascase-insensitivetocomparisons:
orientdb>ALTERPROPERTYEmployee.nameCOLLATEci
Defineacustomfieldonaproperty:
orientdb>ALTERPROPERTYFoo.bar1customstereotype=visible
Setthedefaultvalueforthecurrentdate:
orientdb>ALTERPROPERTYClient.createdDEFAULTsysdate()
Defineaunqiueidthatcannotbechangedaftercreation:
orientdb>ALTERPROPERTYClient.idDEFAULTuuid()READONLY
orientdb>ALTERPROPERTYClient.idREADONLYTRUE
SupportedAttributes
580
AlterProperty
Attribute
Type
S upport
Description
LINKEDCLASS
String
Definesthelinkedclassname.Use NULLtoremoveanexistingvalue.
LINKEDTYPE
String
Definesthelinktype.Use NULLtoremoveanexistingvalue.
MIN
Integer
Definestheminimumvalueasaconstraint.Use NULLtoremoveanexisting
constraint.OnStringattributes,itdefinestheminimumlengthofthestring.On
Integerattributes,itdefinestheminimumvalueforthenumber.OnDateattributes,
theearliestdateaccepted.Formulti-valueattributes(lists,setsandmaps),it
definesthefewestnumberofentries.
MANDATORY
Boolean
Defineswhetherthepropretyrequiresavalue.
MAX
Integer
Definesthemaximumvalueasaconstraint.Use NULLtoremoveanexisting
constraint.OnStringattributes,itdefinesthegreatestlengthofthestring.On
Integerattributes,itdefinesthemaximumvalueforthenumber.OnDate
attributes,thelastdateaccepted.Formulti-valueattributes(lists,setsandmaps),
itdefinesthehighestnumberofentries.
NAME
String
Definesthepropertyname.
NOTNULL
Boolean
Defineswhetherthepropertycanhaveanullvalue.
REGEX
String
DefinesaRegularExpressionasconstraint.Use NULLtoremoveanexisting
constraint.
TYPE
String
Definesapropertytype.
COLLATE
String
Setscollatetooneofthedefinedcomparisonstrategies.Bydefault,itissetto
case-sensitive( cs).Youcanalsosetittocase-insensitive( ci).
READONLY
Boolean
Defineswhetherthepropertyvalueisimmutable.Thatis,ifitispossibleto
changeitafterthefirstassignment.Usewith DEFAULTtohaveimmutablevalues
oncreation.
CUSTOM
String
Definescustomproperties.Thesyntaxforcustompropertiesis <custom-name>=
<custom-value>,suchas stereotype=icon.
DEFAULT
Definesthedefaultvalueorfunction.Featureintroducedinversion2.1,(seethe
sectionaboveforexamples).
Whenaltering NAMEor TYPEthiscommandrunsadataupdatethatmaytakesometime,dependingontheamountofdata.Don'tshut
thedatabasedownduringthismigration.
Tocreateaproperty,usethe CREATEPROPERTYcommand,toremoveapropertythe DROPPROPERTYcommand.Formore
informationonothercommands,seeConsoleandSQLcommands.
581
AlterSequence
SQL-ALTER SEQUENCE
Changesthesequence.Usingthisparameteryoucanchangeallsequenceoptions,exceptforthesequencetype.
Thisfeaturewasintroducedinversion2.2.
S yntax
ALTERSEQUENCE<sequence>[START<start-point>][INCREMENT<increment>][CACHE<cache>]
<sequence>Definesthesequenceyouwanttochange.
STARTDefinestheinitialsequencevalue.
INCREMENTDefinesthevaluetoincrementwhenitcalls .next().
CACHEDefinesthenumberofvaluestocache,intheeventthatthesequenceisofthetype CACHED.
Examples
Alterasequence,resettingthestartvalueto 1000:
orientdb>ALTERSEQUENCEidseqSTART1000
Formoreinformation,see
CREATESEQUENCE
DROPSEQUENCE
SequencesandAuto-increment
SQLCommands.
582
CreateClass
SQL- CREATECLASS
Createsanewclassintheschema.
S yntax
CREATECLASS<class>[EXTENDS<super-class>][CLUSTER<cluster-id>*][CLUSTERS<total-cluster-number>][ABSTRACT]
<class>Definesthenameoftheclassyouwanttocreate.Youmustusealetter,underscoreordollarforthefirstcharacter,forall
othercharactersyoucanusealphanumericcharacters,underscoresanddollar.
<super-class>Definesthesuper-classyouwanttoextendwiththisclass.
<cluster-id>Definesinacomma-separatedlisttheID'softheclustersyouwantthisclasstouse.
<total-cluster-number>Definesthetotalnumberofclustersyouwanttocreateforthisclass.Thedefaultvalueis 1.This
featurewasintroducedinversion2.1.
ABSTRACTDefineswhethertheclassisabstract.Forabstractclasses,youcannotcreateinstancesoftheclass.
Intheeventthataclusterofthesamenameexistsinthecluster,thenewclassusesthisclusterbydefault.Ifyoudonotdefineacluster
inthecommandandaclusterofthisnamedoesnotexist,OrientDBcreatesone.Thenewclusterhasthesamenameastheclass,butin
lower-case.
Whenworkingwithmultiplecores,itisrecommendedthatyouusemultipleclusterstoimproveconcurrencyduringinserts.Tochange
thenumberofclusterscreatedbydefault, ALTERDATABASEcommandtoupdatethe minimumclustersproperty.Beginningwithversion
2.1,youcanalsodefinethenumberofclustersyouwanttocreateusingthe CLUSTERSoptionwhenyoucreatetheclass.
Examples
Createtheclass Account:
orientdb>CREATECLASSAccount
Createtheclass Cartoextend Vehicle:
orientdb>CREATECLASSCarEXTENDSVehicle
Createtheclass Car,usingtheclusterIDof 10:
orientdb>CREATECLASSCarCLUSTER10
Createtheclass Personasanabstractclass:
orientdb>CREATECLASSPersonABSTRACT
ClusterSelectionStrategies
Whenyoucreateaclass,itinheritstheclusterselectionstrategydefinedatthedatabase-level.Bydefaultthisissettoround-robin.You
canchangethedatabasedefaultusingthe ALTERDATABASEcommandandtheselectionstrategyfortheclassusingthe ALTERCLASS
command.
SupportedStrategies:
583
CreateClass
S trategy
Description
default
Selectstheclusterusingtheclassproperty defaultClusterId.Thiswasthedefaultselectionstrategybefore
version1.7.
roundrobin
Selectsthenextclusterinacircularorder,restartingoncecomplete.
balanced
Selectsthesmallestcluster.Allowstheclasstohaveallunderlyingclustersbalancedonsize.Whenaddinganew
clustertoanexistingclass,itfillsthenewclusterfirst.Whenusingadistributeddatabase,thiskeepstheservers
balancedwiththesameamountofdata.Itcalculatestheclustersizeeveryfivesecondsormoretoavoidslowdownsoninsertion.
Formoreinformation,see
ALTERCLASS
DROPCLASS
CREATECLUSTER
SQLCommands
ConsoleCommands
584
CreateCluster
SQL- CREATECLUSTER
Createsanewclusterinthedatabase.Oncecreated,youcanusetheclustertosaverecordsbyspecifyingitsnameduringsaves.Ifyou
wanttoaddthenewclustertoaclass,followitscreationwiththe ALTERCLASScommand,usingthe ADDCLUSTERoption.
S yntax
CREATECLUSTER<cluster>[ID<cluster-id>]
<cluster>Definesthenameoftheclusteryouwanttocreate.Youmustusealetterforthefirstcharacter,forallothercharacters,
youcanusealphanumericcharacters,underscoresanddashes.
<cluster-id>DefinesthenumericIDyouwanttouseforthecluster.
Examples
Createthecluster account:
orientdb>CREATECLUSTERaccount
Formoreinformationsee,
DROPCLUSTER
SQLCommands
ConsoleCommands
585
CreateEdge
SQL- CREATEEDGE
Createsanewedgeinthedatabase.
S yntax
CREATEEDGE<class>[CLUSTER<cluster>]FROM<rid>|(<query>)|[<rid>]*TO<rid>|(<query>)|[<rid>]*
[SET<field>=<expression>[,]*]|CONTENT{<JSON>}
[RETRY<retry>[WAIT<pauseBetweenRetriesInMs]][BATCH<batch-size>]
<class>Definestheclassnamefortheedge.Usethedefaultedgeclass Eintheeventthatyoudon'twanttousesub-types.
<cluster>Definestheclusterinwhichyouwanttostoretheedge.
JSONProvidesJSONcontenttosetastherecord.Usethisinsteadofenteringdatafieldbyfield.
RETRYDefinethenumberofretriestoattemptintheeventofconflict,(optimisticapproach).
WAITDefinesthetimetodelaybetweenretriesinmilliseconds.
BATCHDefineswhetheritbreaksthecommanddownintosmallerblocksandthesizeofthebatches.Thishelpstoavoidmemory
issueswhenthenumberofverticesistoohigh.Bydefault,itissetto 100.Thisfeaturewasintroducedinversion2.1.3.
EdgesandVerticesformthemaincomponentsofaGraphdatabase.OrientDBsupportspolymorphismonedges.Thebaseclassforan
edgeis E.
Beginningwithversion2.1,whennoedgesarecreatedOrientDBthrowsa OCommandExecutionExceptionerror.Thismakesiteasierto
integrateedgecreationintransactions.Insuchcases,ifthesourceortargetverticesdon'texist,itrollsbackthetransaction.(Priorto2.1,
nosucherroristhrown.)
Examples
Createanedgeoftheclass Ebetweentwovertices:
orientdb>CREATEEDGEFROM#10:3TO#11:4
Createanewedgetypeandanedgeofthenewtype:
orientdb>CREATECLASSE1EXTENDSE
orientdb>CREATEEDGEE1FROM#10:3TO#11:4
Createanedgeinaspecificcluster:
orientdb>CREATEEDGEE1CLUSTEREuropeEdgesFROM#10:3TO#11:4
Createanedgeanddefineitsproperties:
orientdb>CREATEEDGEFROM#10:3TO#11:4SETbrand='fiat'
Createanedgeofthetype E1anddefineitsproperties:
orientdb>CREATEEDGEE1FROM#10:3TO#11:4SETbrand='fiat',name='wow'
Createedgesofthetype WatchedbetweenallactionmoviesinthedatabaseandtheuserLuca,usingsub-queries:
orientdb>CREATEEDGEWatchedFROM(SELECTFROMaccountWHEREname='Luca')TO
(SELECTFROMmoviesWHEREtype.name='action')
CreateanedgeusingJSONcontent:
586
CreateEdge
orientdb>CREATEEDGEEFROM#22:33TO#22:55CONTENT{"name":"Jay",
"surname":"Miner"}
Formoreinformation,see
CREATEVERTEX
ControlVerticesVersionIncrement
CreatinganddeletingedgescausesOrientDBtoupdateversionsinvolvedinthevertices.Toavoidthisbehavior,usetheBonsai
Structure.
Bydefault,OrientDBusesBonsaiassoonasitreachesthethresholdtooptimizeoperation.ToalwaysuseBonsaionyourdatabase,
eithersetthisconfigurationontheJVM orinthe orientdb-server-config.xmlconfigurationfile.
$java-DridBag.embeddedToSbtreeBonsaiThreshold=-1
Alternatively,inyourJavaapplicationusethefollowingcallbeforeopeningthedatabase:
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
Formoreinformation,seeConcurrencyonAddingEdges.
Whenrunningadistributeddatabase,edgecreationcansometimesbedoneintwosteps,(thatis,createand
update).ThiscanbreaksomeconstraintsdefinedintheEdgeattheclass-level.Toavoidsuchproblems,disable
theconstraintsintheEdgeclass.BearinmindthatindistributedmodeS BTreeindexalgorithmisnot
supported.Youmustset ridBag.embeddedToSbtreeBonsaiThreashold=Integer.Max\_VALUEtoavoidreplicationerrrors
History
2.0
DisablesLightweightEdgesinnewdatabasesbydefault.Thiscommandnowcreatesaregularedge.
1.4
CommandusestheBlueprintsAPI.IfyouareinJavausingthe OGraphDatabaseAPI,youmayexperiencesomedifferencesin
howOrientDBmanagesedges.
ToforcethecommandtoworkwiththeolderAPI,changetheGraphDBsettings,asdescribedinGraphbackwards
compatibility.
1.2
ImplementssupportforqueryandcollectionofRecordID'sinthe FROM...TOclause.
1.1
Initialversion.
587
CreateFunction
SQL- CREATEFUNCTION
CreatesanewServer-sidefunction.YoucanexecuteFunctionsfromSQL,HTTPandJava.
S yntax
CREATEFUNCTION<name><code>
[PARAMETERS[<comma-separatedlistofparameters'name>]]
[IDEMPOTENTtrue|false]
[LANGUAGE<language>]
<name>Definesthefunctionname.
<code>Definesthefunctioncode.
PARAMETERSDefinesacomma-separatedlistofparametersboundtotheexecutionheap.Youmustwrapyourparameterslistin
squarebrackets[].
IDEMPOTENTDefineswhetherthefunctioncanchangethedatabasestatus.ThisisusefulgiventhatHTTPGETcancall
IDEMPOTENTfunctions,whileothersarecalledbyHTTPPOST.Bydefault,itissetto FALSE.
LANGUAGEDefinesthelanguagetouse.Bydefault,itissettoJavaScript.
Examples
Createafunction test()inJavaScript,whichtakesnoparameters:
orientdb>CREATEFUNCTIONtest"print('\nTest!')"
Createafunction test(a,b)inJavaScript,whichtakes2parameters:
orientdb>CREATEFUNCTIONtest"returna+b;"PARAMETERS[a,b]
Createafunction allUsersButAdmininSQL,whichtakeswithnoparameters:
orientdb>CREATEFUNCTIONallUsersButAdmin"SELECTFROMouserWHEREname<>
'admin'"LANGUAGESQL
Formoreinformation,see
Functions
SQLCommands
ConsoleCommands
588
CreateIndex
SQL- CREATEINDEX
Createsanewindex.Indexescanbe
UniqueWheretheydon'tallowduplicates.
NotUniqueWheretheyallowduplicates.
FullTextWheretheyindexanysinglewordoftext.
ThereareseveralindexalgorithmsavailabletodeterminehowOrientDBindexesyourdatabase.Formoreinformationonthese,
seeIndexes.
S yntax
CREATEINDEX<name>[ON<class>(<property>)]<index-type>[<key-type>]
METADATA[{<json>}]
<name>Definesthelogicalnamefortheindex.Ifaschemaalreadyexists,youcanuse <class>.<property>tocreateautomatic
indexesboundtotheschemaproperty.Becauseofthis,youcannotusetheperiod" ."characterinindexnames.
<class>Definestheclasstocreateanautomaticindexfor.Theclassmustalreadyexist.
<property>Definesthepropertyyouwanttoautomaticallyindex.Thepropertymustalreadyexist.
IfthepropertyisoneoftheM aptypes,suchas LINKMAPor EMBEDDEDMAP,youcanspecifythekeysorvaluestousein
indexgeneration,usingthe BYKEYor BYVALUEclause.
<index-type>Definestheindextypeyouwanttouse.Foracompletelist,seeIndexes.
<key-type>Definesthekeytype.Withautomaticindexes,thekeytypeisautomaticallyselectedwhenthedatabasereadsthe
targetschemaproperty.Formanualindexes,whennotspecified,itselectsthekeyatrun-timeduringthefirstinsertionbyreading
thetypeoftheclass.Increatingcompositeindexes,itusesacomma-separatedlistoftypes.
METADATADefinesadditionalmetadatathroughJSON.
Tocreateanautomaticindexboundtotheschemaproperty,usethe ONclause,orusea <class>.<property>namefortheindex.In
ordertocreateanindex,theschemamustalreadyexistinyourdatabase.
Intheeventthatthe ONand <key-type>clausesbothexist,thedatabasevalidatesthespecifiedpropertytypes.Iftheproperty
typesdon'tequalthosespecifiedinthekeytypelist,itthrowsanexception.
Youcanuselistkeytypeswhencreatingmanualcompositeindexes,butbearinmindthatsuchindexesarenotyetfully
supported.
Examples
Createamanualindextostoredates:
orientdb>CREATEINDEXmostRecentRecordsUNIQUEDATE
Createanautomaticindexboundtothenewproperty idintheclass User:
orientdb>CREATEPROPERTYUser.idBINARY
orientdb>CREATEINDEXUser.idUNIQUE
Createaseriesautomaticindexesforthe thumbspropertyintheclass Movie:
orientdb>CREATEINDEXthumbsAuthorONMovie(thumbs)UNIQUE
orientdb>CREATEINDEXthumbsAuthorONMovie(thumbsBYKEY)UNIQUE
orientdb>CREATEINDEXthumbsValueONMovie(thumbsBYVALUE)UNIQUE
Createaseriesofpropertiesandonthemcreateacompositeindex:
589
CreateIndex
orientdb>CREATEPROPERTYBook.authorSTRING
orientdb>CREATEPROPERTYBook.titleSTRING
orientdb>CREATEPROPERTYBook.publicationYearsEMBEDDEDLISTINTEGER
orientdb>CREATEINDEXbooksONBook(author,title,publicationYears)UNIQUE
Createanindexonanedge'sdaterange:
orientdb>CREATECLASSFileEXTENDSV
orientdb>CREATECLASSHasEXTENDSE
orientdb>CREATEPROPERTYHas.startedDATETIME
orientdb>CREATEPROPERTYHas.endedDATETIME
orientdb>CREATEINDEXHas.started_endedONHas(started,ended)NOTUNIQUE
Youcancreateindexesonedgeclassesonlyiftheycontainthebeginandenddaterangeofvalidity.Thisisusecaseisvery
commonwithhistoricalgraphs,suchastheexampleabove.
Usingtheaboveindex,retrievealltheedgesthatexistedintheyear2014:
orientdb>SELECTFROMHasWHEREstarted>='2014-01-0100:00:00.000'AND
ended<'2015-01-0100:00:00.000'
Usingtheaboveindex,retrievealledgesthatexistedin2014andwritethemtotheparentfile:
orientdb>SELECToutV()FROMHasWHEREstarted>='2014-01-0100:00:00.000'
ANDended<'2015-01-0100:00:00.000'
Usingtheaboveindex,retrieveallthe2014edgesandconnectthemtochildrenfiles:
orientdb>SELECTinV()FROMHasWHEREstarted>='2014-01-0100:00:00.000'
ANDended<'2015-01-0100:00:00.000'
Createanindexthatincludesnullvalues.
Bydefault,indexesignorenullvalues.Queriesagainstnullvaluesthatuseanindexreturnsnoentries.Toindexnullvalues,see {
ignoreNullValues:false}asmetadata.
orientdb>CREATEINDEXaddressesONEmployee(address)NOTUNIQUE
METADATA{ignoreNullValues:false}
Formoreinformation,see
DROPINDEX
Indexes
SQLcommands
590
CreateLink
SQL- CREATELINK
Createsalinkbetweentwosimplevalues.
S yntax
CREATELINK<link>TYPE[<link-type>]FROM<source-class>.<source-property>TO<destination-class>.<destination-property>[INV
ERSE]
<link>Definesthepropertyforthelink.Whennotexpressed,thelinkoverwritesthe <destination-property>field.
<link-type>Definesthetypeforthelink.Intheeventofaninverserelationship,(themostcommon),youcanspecify LINKSET
or LINKLISTfor1-nrelationships.
<source-class>Definestheclasstolinkfrom.
<source-property>Definesthepropertytolinkfrom.
<destination-class>Definestheclasstolinkto.
<destination-property>Definesthepropertytolinkto.
INVERSEDefineswhethertocreateaconnectionontheoppositedirection.Thisoptioniscommonwhencreating1-nrelationships
fromaRelationaldatabase,wheretheyaremappedattheoppositedirection.
Example
Createaninverselinkbetweentheclasses Commentsand Post:
orientdb>CREATELINKcommentsTYPELINKSETFROMComments.PostIdTOPosts.Id
INVERSE
Formoreinformation,see
Relationships
ImportingfromRelationalDatabases
SQLCommands
ConversionfromRelationalDatabases
YoumayfindthisusefulwhenimporteddatafromaRelationaldatabase.IntheRelationalworld,thedatabaseuseslinkstoresolve
foreignkeys.Ingeneral,thisisnotthewaytocreatelinks,butratherawaytoconverttwovaluesintwodifferentclassesintoalink.
Asanexample,consideraRelationaldatabasewherethetable Posthasa1-nrelationshipwiththetable Comment.Thatis Post1-->*Comment,suchas:
591
CreateLink
reldb>SELECT*FROMPost;
+----+----------------+
|Id|Title|
+----+----------------+
|10|NoSQLmovement|
+----+----------------+
|20|NewOrientDB|
+----+----------------+
reldb>SELECT*FROMComment;
+----+--------+--------------+
|Id|PostID|Text|
+----+--------+--------------+
|0|10|First|
+----+--------+--------------+
|1|10|Second|
+----+--------+--------------+
|21|10|Another|
+----+--------+--------------+
|41|20|Firstagain|
+----+--------+--------------+
|82|20|SecondAgain|
+----+--------+--------------+
InOrientDB,insteadofaseparatetablefortherelationship,youuseadirectrelationshipasyourobjectmodel.M eaningthatthe
databasenavigatesfrom Postto Commentandnotviceversa,aswithRelationaldatabases.Todoso,youwouldalsoneedtocreate
thelinkwiththe INVERSEoption.
592
CreateProperty
SQL- CREATEPROPERTY
Createsanewpropertyintheschema.Itrequiresthattheclassforthepropertyalreadyexistonthedatabase.
S yntax
CREATEPROPERTY<class>.<property><type>[<link-type>|<link-class>][UNSAFE]
<class>Definestheclassforthenewproperty.
<property>Definesthelogicalnamefortheproperty.
<type>Definesthepropertydatatype.Forsupportedtypes,seethetablebelow.
<link-type>Definesthecontainedtypeforcontainerpropertydatatypes.Forsupportedlinktypes,seethetablebelow.
<link-class>Definesthecontainedclassforcontainerpropertydatatypes.Forsupportedlinktypes,seethetablebelow.
UNSAFEDefineswhetheritchecksexistingrecords.Onlargerdatabases,withmillionsofrecords,thiscouldtakeagreatdealof
time.Skipthecheckwhenyouaresurethepropertyisnew.Introducedinversion2.0.
Whenyoucreateaproperty,OrientDBchecksthedataforpropertyandtype.Intheeventthatpersistentdatacontains
incompatiblevaluesforthespecifiedtype,thepropertycreationfails.Itappliesnootherconstraintsonthepersistentdata.
Examples
Createtheproperty nameofthestringtypeintheclass User:
orientdb>CREATEPROPERTYUser.nameSTRING
Createapropertyformedfromalistofstringscalled tagsintheclass Profile:
orientdb>CREATEPROPERTYProfile.tagsEMBEDDEDLISTSTRING
Createtheproperty friends,asanembeddedmapinacircularreference:
orientdb>CREATEPROPERTYProfile.friendsEMBEDDEDMAPProfile
Formoreinformation,see
DROPPROPERTY
SQLCommands
ConsoleCommands
SupportedTypes
OrientDBsupportsthefollowingdatatypesforstandardproperties:
BOOLEAN
SHORT
DATE
BYTE
INTEGER
LONG
STRING
LINK
DOUBLE
FLOAT
BINARY
EMBEDDED
Itsupportsthefollowingdatatypesforcontainerproperties.
EMBEDDEDLIST
EMBEDDEDSET
EMBEDDEDMAP
LINKLIST
LINKSET
LINKMAP
Forthesedatatypes,youcanoptionallydefinethecontainedtypeandclass.Thesupportedlinktypesarethesameasthestandard
propertydatatypesabove.
593
CreateProperty
594
CreateSequence
SQL- CREATESEQUENCE
Createsanewsequence.Commandintroducedinversion2.2.
S yntax
CREATESEQUENCE<sequence>TYPE<CACHED|ORDERED>[START<start>]
[INCREMENT<increment>][CACHE<cache>]
<sequence>Logicalnameforthesequencetocache.
TYPEDefinesthesequencetype.Supportedtypesare,
CACHEDForsequenceswhereitcachesNitemsoneachnodetoimproveperformancewhenyourequiremanycallstothe
.next()method.(Bearinmind,thismanycreateholeswithnumeration).
ORDEREDForsequenceswhereitdrawsonanewvaluewitheachcalltothe .next()method.
STARTDefinestheinitialvalueofthesequence.
INCREMENTDefinestheincrementforeachcallofthe .next()method.
CACHEDefinesthenumberofvaluetopre-cache,intheeventthatyouusethecachedsequencetype.
Examples
Createanewsequencetohandleidnumbers:
orientdb>CREATESEQUENCEidseqTYPEORDERED
Usethenewsequencetoinsertidvalues
orientdb>INSERTINTOAccountSETid=sequence('idseq').next()
Formoreinformation,see
ALTERSEQUENCE
DROPSEQUENCE
SequencesandAuto-increment
SQLcommands.
595
CreateUser
SQL- CREATEUSER
Createsauserinthecurrentdatabase,usingthespecifiedpasswordandanoptionalrole.Whentheroleisunspecified,itdefaultsto
writer.
Thecommandwasintroducedinversion2.2.Itisasimplewrapperaroundthe OUserand ORoleclasses.M oreinformationis
availableatSecurity.
S yntax
CREATEUSER<user>IDENTIFIEDBY<password>[ROLE<role>]
<user>Definesthelogicalnameoftheuseryouwanttocreate.
<password>Definesthepasswordtouseforthisuser.
ROLEDefinestheroleyouwanttosetfortheuser.Formultipleroles,usethefollowingsyntax: ['author','writer'].
Examples
Createanewadminusercalled Foowiththepassword bar:
orientdb>CREATEUSERFooIDENTIFIEDBYbarROLEadmin
Createanewusercalled Barwiththepassword foo:
orientdb>CREATEUSERBarIDENTIFIEDBYFoo
Formoreinformation,see
Security
DROPUSER
SQLCommands
596
CreateVertex
SQL- CREATEVERTEX
Createsanewvertexinthedatabase.
TheVertexandEdgearethemaincomponentsofaGraphdatabase.OrientDBsupportspolymorphismonvertices.Thebaseclassfora
vertexis V.
S yntax
CREATEVERTEX[<class>][CLUSTER<cluster>][SET<field>=<expression>[,]*]
<class>Definestheclasstowhichthevertexbelongs.
<cluster>Definestheclusterinwhichitstoresthevertex.
<field>Definesthefieldyouwanttoset.
<expression>Definestheexpresstosetforthefield.
|----|----||
|NOTE:Whenusingadistributeddatabase,youcancreatevertexesthroughtwosteps(creation
andupdate).Doingsocanbreakconstraintsdefinedattheclass-levelforvertices.Toavoidtheseissues,disableconstraintsinthevertex
class.|
Examples
Createanewvertexonthebaseclass V:
orientdb>CREATEVERTEX
Createanewvertexclass,thencreateavertexinthatclass:
orientdb>CREATECLASSV1EXTENDSV
orientdb>CREATEVERTEXV1
Createanewvertexwithinaparticularcluster:
orientdb>CREATEVERTEXV1CLUSTERrecent
Createanewvertex,definingitsproperties:
orientdb>CREATEVERTEXSETbrand='fiat'
Createanewvertexoftheclass V1,definingitsproperties:
orientdb>CREATEVERTEXV1SETbrand='fiat',name='wow'
CreateavertexusingJSONcontent:
orientdb>CREATEVERTEXEmployeeCONTENT{"name":"Jay","surname":"Miner"}
597
CreateVertex
Formoreinformation,see
CREATEEDGE
SQLCommands
History
1.4
CommandbeginsusingtheBlueprintsAPI.WhenusingJavawiththeOGraphDatabaseAPI,youmayexperienceunexpected
resultsinhowitmanagesedges.
ToforcethecommandtoworkwiththeolderAPI,updatetheGraphDBsettings,usethe ALTERDATABASEcommand.
1.1
Initialimplementationoffeature.
598
M oveVertex
SQL- MOVEVERTEX
M ovesoneormoreverticesintoadifferentclassorcluster.
Followingthemove,theverticesuseadifferentRecordID.Thecommandupdatesalledgestousethemovedvertices.Whenusinga
distributeddatabase,ifyouspecifyacluster,itmovestheverticestotheserverownerofthetargetcluster.
S yntax
MOVEVERTEX<source>TO<destination>[SET[<field>=<value>]*[,]][MERGE<JSON>]
[BATCH<batch-size>]
<source>Definesthevertexyouwanttomove.Itsupportsthefollowingvalues,
VertexUsingtheRecordIDofasinglevertex.
ArrayUsinganarrayofrecordID'sforverticesyouwanttomove.
<destination>Defineswhereyouwanttomovethevertexto.Itsupportsthefollowingvalues,
ClassUsing CLASS:<class>withtheclassyouwanttomovethevertexinto.
ClusterUsing CLUSTER:<cluster>withtheclusteryouwanttomovethevertexinto.
SETClausetosetvaluesonfieldsduringthetransition.
MERGEClausetosetvaluesonfieldsduringthetransition,throughJSON.
BATCHDefinesthebatchsize,allowingyoutoexecutethecommandinsmallerblockstoavoidmemoryproblemswhenmovinga
largenumberofvertices.
WARNING:Thiscommandupdatesallconnectededges,butnotthelinks.WhenusingtheGraphAPI,
itisrecommendthatyoualwaysuseedgesconnectedtoverticesandneverlinks.
Examples
M oveasinglevertexfromitscurrentpositiontotheclass Provider:
orientdb>MOVEVERTEX#34:232TOCLASS:Provider
M oveanarrayofverticesbytheirrecordID'stotheclass Provider:
orientdb>MOVEVERTEX[#34:232,#34:444]TOCLASS:Provider
M oveasetofverticestotheclass Provider,definingthoseyouwanttomovewithasubquery:
orientdb>MOVEVERTEX(SELECTFROMVWHEREcity='Rome')TOCLASS:Provider
M oveavertexfromitscurrentpositiontotheEuropeancluster
orientdb>MOVEVERTEX#3:33TOCLUSTER:providers_europe
Youmayfindthisusefulwhenusingadistributeddatabase,whereyoucanmoveverticesontodifferentservers.
M oveasetofverticestotheclass Provider,whiledoingsoupdatetheproperty movedOntothecurrentdate:
orientdb>MOVEVERTEX(SELECTFROMVWHEREtype='provider')TOCLASS:Provider
SETmovedOn=Date()
Notethesimilaritiesthissyntaxhaswiththe UPDATEcommand.
599
M oveVertex
M ovethevertexusingasubquery,usingJSONupdatethepropertiesduringthetransition:
orientdb>MOVEVERTEX(SELECTFROMUser)TOCLUSTER:users_europeBATCH50
M ovethesameverticesasaboveusingonlyonetransaction:
orientdb>MOVEVERTEX(SELECTFROMUser)TOCLUSTER:users_europeBATCH-1
Formoreinformation,see
CREATEVERTEX
CREATEEDGE
SQLCommands
UseCases
RefactoringGraphsthroughSub-types
It'saverycommonsituationwhereyoubeginmodelingyourdomainoneway,butfindlaterthatyouneedmoreflexibility.
Forinstance,saythatyoustartoutwithavertexclasscalled Person.Afterusingthedatabaseforseveralmonths,populatingitwith
newvertices,youdecidethatyouneedtosplittheseverticesintotwonewclasses,orsub-types,called Customerand Provider,
(rendering Personintoanabstractclass).
Createthenewclassesforyoursub-types:
orientdb>CREATECLASSCustomerEXTENDSPerson
orientdb>CREATECLASSProviderEXTENDSPerson
M ovetheprovidersandcustomersfrom Personintotheirrespectivesub-types:
orientdb>MOVEVERTEX(SELECTFROMPersonWHEREtype='Customer')TO
CLASS:Customer
orientdb>MOVEVERTEX(SELECTFROMPersonWHEREtype='Provider')TO
CLASS:Provider
M aketheclass Personanabstractclass:
orientdb>ALTERCLASSPersonABSTRACTTRUE
MovingVerticesontoDifferentServers
WithOrientDB,youcanscaleyourinfrastructureupbyaddingnewservers.Whenyouaddanewserver,OrientDBautomatically
createsanewclusterwiththenameoftheclassplusthenodename.Forinstance, customer_europe.
Thebestpracticewhenyouneedtoscaleupispartitioning,especiallyonwrites.Ifyouhaveagraphwith Customerverticesandyou
wanttomovesomeoftheseontoadifferentserver,youcanmovethemtotheclusterownedbytheserver.
Forinstance,moveallcustomersthatliveinItaly,GermanyortheUnitedKingdomontothecluster customer_europe,whichis
assignedtothenode Europe.ThismeansthataccesstoEuropeancustomersisfasterwithapplicationsconnectedtotheEuropean
node.
orientdb>MOVEVERTEX(SELECTFROMCustomerWHERE['Italy','Germany','UK']IN
out('city').out('country'))TOCLUSTER:customer_europe
600
M oveVertex
History
2.0
Initialimplementationofthefeature.
601
Updateedge
SQL- UPDATEEDGE
Updatesedgerecordsinthecurrentdatabase.Thisistheequivalentofthe UPDATEcommand,withtheadditionofcheckingand
maintaininggraphconsistencywithvertices,intheeventthatyouupdatethe outand inproperties.
BearinmindthatOrientDBcanalsoworkinschema-lessmode,allowingyoutocreatefieldsonthefly.Furthermore,thatitworkson
collectionsandnecessarilyincludessomeextensionstothestandardSQLforhandlingcollections.
Thiscommandwasintroducedinversion2.2.
S yntax
UPDATEEDGE<edge>
[SET|INCREMENT|ADD|REMOVE|PUT<field-name>=<field-value>[,]*]|[CONTENT|MERGE<JSON>]
[RETURN<returning>[<returning-expression>]]
[WHERE<conditions>]
[LOCKdefault|record]
[LIMIT<max-records>][TIMEOUT<timeout>]
<edge>Definestheedgethatyouwanttoupdate.Youcanchoosebetween:
ClassUpdatingedgesbyclass.
ClusterUpdatingedgesbycluster,using CLUSTERprefix.
RecordIDUpdatingedgesbyRecordID.
SETUpdatesthefieldtothegivenvalue.
INCREMENTIncrementsthegivenfieldbythevalue.
ADDDefinesanitemtoaddtoacollectionoffields.
REMOVEDefinesanitemtoremovefromacollectionoffields.
PUTDefinesanentrytoputintoamapfield.
RETURNDefinestheexpressionyouwanttoreturnafterrunningtheupdate.
COUNTReturnsthenumberofupdatedrecords.Thisisthedefaultoperator.
BEFOREReturnstherecordsbeforetheupdate.
AFTERReturnstherecordsaftertheupdate.
WHEREDefinesthefilterconditions.
LOCKDefineshowtherecordlocksbetweentheloadandupdate.Youcanchoosebetweenthefollowinglockstrategies:
DEFAULTDisableslocking.Usethisintheeventofconcurrentupdates.Itthrowsanexceptionintheeventofconflict.
RECORDLockstherecordduringtheupdate.
LIMITDefinesthemaximumnumberofrecordstoupdate.
Examples
Changetheedgeendpoint:
orientdb>UPDATEEDGEFriendSETout=(SELECTFROMPersonWHEREname='John')
WHEREfoo='bar'
Formoreinformation,see
UPDATE
SQLCommands
602
DeleteEdge
SQL- DELETEEDGE
Removesedgesfromthedatabase.Thisistheequivalentofthe DELETEcommand,withtheadditionofcheckingandmaintaining
consistencywithverticesbyremovingallcross-referencestotheedgefromboththe inand outvertexproperties.
S yntax
DELETEEDGE
(<rid>
|
[<rid>(,<rid>)*]
|
([FROM(<rid>|<select_statement>)][TO(<rid>|<select_statement>)])
|
[<class>]
(
[WHERE<conditions>]
[LIMIT<MaxRecords>]
[BATCH<batch-size>]
FROMDefinesthestartingpointvertexoftheedgetodelete.
TODefinestheendingpointvertexoftheedgetodelete.
WHEREDefinesthefilteringconditions.
LIMITDefinesthemaximumnumberofedgestodelete.
BATCHDefinestheblocksizefortheoperation,allowingyoutobreaklargetransactionsdownintosmallerunitstoreduce
resourcedemands.Itsdefaultis 100.Featureintroducedin2.1.
Examples
Deleteedgeswherethedataisapropertythatmightexistinoneormoreedgesbetweentwovertices:
orientdb>DELETEEDGEFROM#11:101TO#11:117WHEREdate>="2012-01-15"
Deleteedgesfilteringbytheedgeclass:
orientdb>DELETEEDGEFROM#11:101TO#11:117WHERE@class='Owns'ANDcomment
LIKE"regexofforbiddenwords"
Deleteedgefilteringbytheedgeclassanddate:
orientdb>DELETEEDGEOwnsWHEREdate<"2011-11"
Notethatthissyntaxisfasterthanfilteringtheclassthroughthe WHEREclause.
Deleteedgeswhere in.priceshowstheconditiononthe tovertexfortheedge:
orientdb>DELETEEDGEOwnsWHEREdate<"2011-11"ANDin.price>=202.43
Deleteedgesinblocksofonethousandpertransaction.
orientdb>DELETEEDGEOwnsWHEREdate<"2011-11"BATCH1000
Thisfeaturewasintroducedinversion2.1.
Formoreinformation,see
DELETE
SQLCommands
603
DeleteEdge
UseCases
ControlingVertexVersionIncrements
CreatinganddeletingedgescausesOrientDBtoincrementversionsontheinvolvedvertices.Youcanpreventthisoperationby
implementingtheBonsaiStructure.
Bydefault,OrientDBonlyusesBonsaiassoonasitreachesthethreshold,inordertooptimizeoperation.ToalwaysuseBonsai,
configureitontheJVM orinthe orientdb-server-config.xmlconfigurationfile.
$javac...-DridBag.embeddedToSbtreeBonsaiThreshold=-1
ToimplementitinJava,addthefollowinglinetoyourapplicationatapointbeforeopeningthedatabase:
OGlobalConfiguration.RID_BAG_EMBEDDED_TO_SBTREEBONSAI_THRESHOLD.setValue(-1);
Formoreinformation,seeConcurrencyonAddingEdges.
NOTE:Whenusingadistributeddatabase,OrientDBdoesnotsupportS BTreeindexes.Inthese
environments,youmustset ridBag.embeddedToSbtreeBonsaiThreshold=Integer.MAX\_VALUEtoavoidreplication
errors._
DeletingEdgesfromaSub-query
ConsiderasituationwhereyouhaveanedgewithaRecordIDof #11:0thatyouwanttodelete.Inattemptingtodoso,yourunthe
followingquery:
orientdb>DELETEEDGEFROM(SELECTFROM#11:0)
Thisdoesnotdeletetheedge.Todeleteedgesusingsub-queries,youhavetouseasomewhatdifferentsyntax.Forinstance,
orientdb>DELETEEDGEEWHERE@ridIN(SELECTFROM#11:0)
Thisremovestheedgefromyourdatabase.
DeletingEdgesthroughJava
Whena Usernodefollowsa companynode,wecreateanedgebetweentheuserandthecompanyofthetype followCompanyand
CompanyFollowedByclasses.WecanthenremovetherelevantedgesthroughJava.
node1isUsernode,
node2iscompanynode
OGraphDatabaserawGraph=orientGraph.getRawGraph();
String[]arg={"followCompany,"CompanyFollowedBy"};
Set<OIdentifiable>edges=rawGraph.getEdgesBetweenVertexes(node1,node2,null,arg);
for(OIdentifiableoIdentifiable:edges){
**rawGraph.removeEdge(oIdentifiable);
}
History
2.1
Implementssupportfortheoption BATCHclause
604
DeleteEdge
1.4
CommandimplementstheBlueprintsAPI.IntheeventthatyouareworkinginJavausingtheOGraphDatabaseAPI,youmay
experiencesomeunexpectedresultsinhowedgesaremanagedbetweenversions.ToforcethecommandtousetheolderAPI,
changetheGraphDBsettings,asdescribedonthe[ ALTERDATABASE])SQL-Alter-Database.md)commandexamples.
1.1
Firstimplementationofthefeature.
605
DeleteVertex
SQL- DELETEVERTEX
Removesverticesfromthedatabase.Thisistheequivalentofthe DELETEcommand,withtheadditionofcheckingandmaintaining
consistencywithedges,removingallcross-referencestothedeletedvertexinalledgesinvolved.
S yntax
DELETEVERTEX<vertex>[WHERE<conditions>][LIMIT<MaxRecords>>][BATCH<batch-size>]
<vertex>Definesthevertexthatyouwanttoremove,usingitsClass,RecordID,orthroughasub-queryusingthe FROM(<subquery)clause.
WHEREFilterconditiontodeterminewhichrecordsthecommandremoves.
LIMITDefinesthemaximumnumberofrecordstoremove.
BATCHDefineshowmanyrecordsthecommandremovesatatime,allowingyoutobreaklargetransactionsintosmallerblocksto
saveonmemoryusage.Bydefault,itoperatesonblocksof100.
Example
Removethevertexanddisconnectallverticesthatpointtowardsit:
orientdb>DELETEVERTEX#10:231
Removealluseraccountsmarkedwithanincomingedgeontheclass BadBehaviorInForum:
orientdb>DELETEVERTEXAccountWHEREin.@ClassCONTAINS
'BadBehaviorInForum'
Removeallverticesfromtheclass EmailMessagesmarkedwiththeproperty isSpam:
orientdb>DELETEVERTEXEMailMessageWHEREisSpam=TRUE
Removeverticesoftheclass Attachment,wherethevertexhasanedgeoftheclass HasAttachmentwheretheproperty dateis
setbefore1990andthevertex Emailconnectedtoclass Attachmentwiththeconditionthatitsproperty fromissetto
bob@example.com:
orientdb>DELETEVERTEXAttachmentWHEREin[@Class='HasAttachment'].date
<="1990"ANDin.out[@Class="Email"].from='some...@example.com'
Removeverticesinblocksofonethousand:
orientdb>DELETEVERTEXvBATCH1000
Thisfeaturewasintroducedinversion2.1.
History
Version2.1
Introducestheoptional BATCHclauseformanagingbatchsizeontheoperation.
Version1.4
CommandbeginsusingtheBlueprintsAPI.WhenworkinginJavausingtheOGraphDatabaseAPI,youmayexperiencedifferences
606
DeleteVertex
inhowthedatabasemanagesedges.ToforcethecommandtoworkwiththeolderAPI,changetheGraphDBsettingsusing ALTER
DATABASE.
Version1.1
Initialversion.
607
DropClass
SQL- DROPCLASS
Removesaclassfromtheschema.
S yntax
DROPCLASS<class>[UNSAFE]
<class>Definestheclassyouwanttoremove.
UNSAFEDefineswhetherthecommanddropsnon-emptyedgeandvertexclasses.Note,thiscandisruptdataconsistency.Besure
tocreateabackupbeforerunningit.
NOTE:Bearinmind,thattheschemamustremaincoherent.Forinstance,avoidremovingcalssesthataresuper-classesto
others.Thisoperationwon'tdeletetheassociatedcluster.
Examples
Removetheclass Account:
orientdb>DROPCLASSAccount
Formoreinformation,see
CREATECLASS
ALTERCLASS
ALTERCLUSTER
SQLCommands
ConsoleCommands
608
DropCluster
SQL- DROPCLUSTER
Removestheclusterandallofitscontent.Thisoperationispermanentandcannotberolledback.
S yntax
DROPCLUSTER<cluster-name>|<cluster-id>
<cluster-name>Definesthenameoftheclusteryouwanttoremove.
<cluster-id>DefinestheIDoftheclusteryouwanttoremove.
Examples
Removethecluster Account:
orientdb>DROPCLUSTERAccount
Formoreinformation,see
CREATECLUSTER
ALTERCLUSTER
DROPCLASS
SQLCommands
ConsoleCommands
609
DropIndex
SQL- DROPINDEX
Removesanindexfromapropertydefinedintheschema.
S yntax
DROPINDEX<index>|<class>.<property>
<index>Definesthenameoftheindex.
<class>Definestheclasstheindexuses.
<property>Definesthepropertytheindexuses.
Examples
Removetheindexonthe Idpropertyofthe Usersclass:
orientdb>DROPINDEXUsers.Id
Formoreinformation,see
CREATEINDEX
Indexes
SQLCommands
610
DropProperty
SQL- DROPPROPERTY
Removesapropertyfromtheschema.Doesnotremovethepropertyvaluesintherecords,itjustchangestheschemainformation.
Recordscontinuetohavethepropertyvalues,ifany.
S yntax
DROPPROPERTY<class>.<property>[FORCE]
<class>Definestheclasswherethepropertyexists.
<property>Definesthepropertyyouwanttoremove.
FORCEIncaseoneormoreindexesaredefinedontheproperty,thecommandwillthrowanexception.UseFORCEtodrop
indexestogetherwiththeproperty
Examples
Removethe namepropertyfromtheclass User:
orientdb>DROPPROPERTYUser.name
Formoreinformation,see
CREATEPROPERTY
SQLCommands
ConsoleCommands
611
DropSequence
SQL- DROPSEQUENCE
Removesasequence.Thisfeaturewasintroducedinversion2.2.
S yntax
DROPSEQUENCE<sequence>
<sequence>Definesthenameofthesequenceyouwanttoremove.
Examples
Removethesequence idseq:
orientdb>DROPSEQUENCEidseq
Formoreinformation,see
CREATESEQUENCE
DROPSEQUENCE
Sequencesandautoincrement
SQLcommands
612
DropUser
SQL- DROPUSER
Removesauserfromthecurrentdatabase.Thisfeaturewasintroducedinversion2.2
S yntax
DROPUSER<user>
<user>Definestheuseryouwanttoremove.
NOTE:Thisisawrapperontheclass OUser.Formoreinformation,seeSecurity.
Examples
Removetheuser Foo:
orientdb>DROPUSERFoo
Formoreinformation,see,
CREATEUSER
SQLcommands
613
Explain
SQL- EXPLAIN
ProfilesanycommandandreturnsaJSONdataontheresultofitsexecution.Youmayfindthisusefultoseewhyqueriesarerunning
slow.Useitasakeywordbeforeanycommandthatyouwanttoprofile.
S yntax
EXPLAIN<command>
<command>Definesthecommandthatyouwanttoprofile.
Examples
Profileaquerythatexecutesonaclasswithoutindexes:
orientdb>EXPLAINSELECTFROMAccount
Profiledcommand'{documentReads:1126,documentReadsCompatibleClass:1126,
recordReads:1126,elapsed:209,resultType:collection,resultSize:1126}'
in0,212000sec(s).
Profileaquerythatexecutesonaclasswithindexes:
orientdb>EXPLAINSELECTFROMProfileWHEREname='Luca'
Profiledcommand'{involvedIndexes:[1],indexReads:1,resultType:collection
resultSize:1,documentAnalyzedCompatibleClass:1,elapsed:1}'
in0,002000sec(s).
Formoreinformation,see
SQLCommands
UnderstandingtheProfile
Whenyourunthiscommand,itreturnsJSONdatacontainingallofthefollowingprofilemetrics:
Metric
Description
elapsed
Timetoexecuteinseconds.Theprecisionisthenanosecond.
resultType
Theresult-type: collection, document,or number.
resultSize
Numberofrecordsretrieved,incaseswheretheresult-typeis collection.
recordReads
Numberofrecordsreadfromdisk.
documentReads
Numberofdocumentsreadfromdisk.Thismetricmaydifferfrom recordReadsinthe
eventthatotherkindsofrecordsarepresentinthecommandtarget.Forinstance,ifyou
havedocumentsandrecordbytesinthesameclusteritmayskipmanyrecords.Thatsaid,
incaseofscans,itisrecommendedthatyoustoredifferentrecordsinseparateclusters.
documentAnalyzedCompatibleClass
Numberofdocumentsanalyzedintheclass.Forinstance,ifyouusethesameclusterin
documentsfortheclasses Accountand Invoice,itwouldskiprecordsoftheclass
Invoicewhenyoutargettheclass Account.Incaseofscans,itisrecommendedthat
youstoredifferentclassesinseparateclusters.
involvedIndexes
Indexesinvolvedinthecommand.
indexReads
Numberofrecordsreadfromtheindex.
614
FindReferences
SQL- FINDREFERENCES
SearchesrecordsinthedatabasethatcontainlinkstothegivenRecordIDinthedatabaseorasubsetofthespecifiedclassandcluster,
returningthematchingRecordID's.
S yntax
FINDREFERENCES<record-id>|(<sub-query>)[class-list]
<record-id>DefinestheRecordIDyouwanttofindlinkstointhedatabase.
<sub-query>Definesasub-queryfortheRecordID'syouwanttofindlinkstointhedatabase.Thisfeaturewasintroducedin
version1.0rc9.
<class-list>Definesacomma-separatedlistofclassesorclustersthatyouwanttosearch.
Thiscommandreturnsadocumentcontainingtwofields:
Field
Description
rid
RecordIDsearched.
referredBy
SetofRecordID'sreferencedbytheRecordIDsearched,ifany.Intheeventthatnorecordsreferencethe
searchedRecordID,itreturnsanemptyset.
Examples
Findrecordsthatcontainalinkto #5:0:
orientdb>FINDREFERENCES5:0
RESULT:
------+----------------rid|referredBy
------+----------------#5:0|[#10:23,#30:4]
------+-----------------
Findreferencestothedefaultclusterrecord
orientdb>FINDREFERENCES(SELECTFROMCLUSTER:default)
Findallrecordsintheclasses Profileand AnimalTypethatcontainalinkto #5:0:
orientdb>FINDREFERENCES5:0[Profile,AnimalType]
Findallrecordsinthecluster profileandclass AnimalTypethatcontainalinkto #5:0:
orientdb>FINDREFERENCES5:0[CLUSTER:profile,AnimalType]
Formoreinformation,see
SQLCommands
615
Grant
SQL- GRANT
Changesthepermissionofarole,grantingitaccesstooneormoreresources.Toremoveaccesstoaresourcefromtherole,seethe
REVOKEcommand.
S yntax
GRANT<permission>ON<resource>TO<role>
<permission>Definesthepermissionyouwanttogranttotherole.
<resource>Definestheresourceonwhichyouwanttograntthepermissions.
<role>Definestheroleyouwanttograntthepermissions.
Examples
Grantpermissiontoupdateanyrecordinthecluster accounttotherole backoffice:
orientdb>GRANTUPDATEONdatabase.cluster.accountTObackoffice
Formoreinformation,see
`REVOKE
SQLCommands
SupportedPermissions
Usingthiscommand,youcangrantthefollowingpermissionstoarole.
Permission
Description
NONE
Grantsnopermissionsontheresource.
CREATE
Grantscreatepermissionsontheresource,suchasthe CREATECLASSor CREATECLUSTERcommands.
READ
Grantsreadpermissionsontheresource,suchasthe SELECTquery.
UPDATE
Grantsupdatepermissionsontheresource,suchasthe UPDATEor UPDATEEDGEcommands.
DELETE
Grantsdeletepermissionsontheresource,suchasthe DROPINDEXor DROPSEQUENCEcommands.
ALL
Grantsallpermissionsontheresource.
SupportedResources
Usingthiscommand,youcangrantpermissionsonthefollowingresources.
616
Grant
Resource
Description
database
Grantsaccessonthecurrentdatabase.
database.class.
<class>
Grantsaccessonrecordscontainedintheindicatedclass.Use **toindicateallclasses.
database.cluster.
<cluster>
Grantsaccesstorecordscontainedintheindicatedcluster.Use **toindicateallclusters.
database.query
Grantstheabilitytoexecuteaquery,( READissufficient).
database.command.
<command>
Grantstheabilitytoexecutethegivencommand.Use CREATEfor INSERT, READfor SELECT,
UPDATEfor UPDATEand DELETEfor DELETE.
database.config.
<permission>
Grantsaccesstotheconfiguration.Validpermissionsare READand UPDATE.
database.hook.record
Grantstheabilitytosethooks.
server.admin
Grantstheabilitytoaccessserverresources.
617
OptimizeDatabase
SQL- OPTIMIZEDATABASE
Optimizesthedatabaseforparticularoperations.
S yntax
OPTIMIZEDATABASE[-lwedges][-noverbose]
-lwedgesConvertsregularedgesintoLightweightEdges.
-noverboseDisablesoutput.
Currently,thiscommandonlysupportsoptimizationforLightweightEdges.Additionaloptimizationoptionsareplannedfor
futurereleasesofOrientDB.
Examples
ConvertregularedgesintoLightweightEdges:
orientdb>OPTIMIZEDATABASE-lwedges
Formoreinformation,see
LightweightEdges
SQLCommands
ConsoleCommands
618
RebuildIndex
SQL- REBUILDINDEXES
Rebuildsautomaticindexes.
S yntax
REBUILDINDEX<index>
<index>Definestheindexthatyouwanttorebuild.Use *torebuildallautomaticindexes.
NOTE:Duringtherebuild,anyidempotentqueriesmadeagainsttheindex,skiptheindexandperformsequentialscans.This
meansthatqueriesrunslowerduringthisoperation.Non-idempotentcommands,suchas INSERT, UPDATE,and DELETEare
blockedwaitinguntiltheindexesarerebuilt.
Examples
Rebuildanindexonthe nickpropertyontheclass Profile:
orientdb>REBUILDINDEXProfile.nick
Rebuildallindexes:
orientdb>REBUILDINDEX*
Formoreinformation,see
CREATEINDEX
DROPINDEX
Indexes
SQLcommands
619
Revoke
SQL- REVOKE
Changespermissionsofarole,revokingaccesstooneormoreresources.Togiveaccesstoaresourcetotherole,seethe GRANT
command.
S yntax
REVOKE<permission>ON<resource>FROM<role>
<permission>Definesthepermissionyouwanttorevokefromtherole.
<resource>Definestheresourceonwhichyouwanttorevokethepermissions.
<role>Definestheroleyouwanttorevokethepermissions.
Examples
Revokepermissiontodeleterecordsonanyclustertotherole backoffice:
orientdb>REVOKEDELETEONdatabase.cluster.*TObackoffice
Formoreinformation,see
SQLcommands.
SupportedPermissions
Usingthiscommand,youcangrantthefollowingpermissionstoarole.
Permission
Description
NONE
Revokesnopermissionsontheresource.
CREATE
Revokescreatepermissionsontheresource,suchasthe CREATECLASSor CREATECLUSTERcommands.
READ
Revokesreadpermissionsontheresource,suchasthe SELECTquery.
UPDATE
Revokesupdatepermissionsontheresource,suchasthe UPDATEor UPDATEEDGEcommands.
DELETE
Revokesdeletepermissionsontheresource,suchasthe DROPINDEXor DROPSEQUENCEcommands.
ALL
Revokesallpermissionsontheresource.
SupportedResources
Usingthiscommand,youcangrantpermissionsonthefollowingresources.
620
Revoke
Resource
Description
database
Revokesaccessonthecurrentdatabase.
database.class.
<class>
Revokesaccessonrecordscontainedintheindicatedclass.Use **toindicateallclasses.
database.cluster.
<cluster>
Revokesaccesstorecordscontainedintheindicatedcluster.Use **toindicateallclusters.
database.query
Revokestheabilitytoexecuteaquery,( READissufficient).
database.command.
<command>
Revokestheabilitytoexecutethegivencommand.Use CREATEfor INSERT, READfor SELECT,
UPDATEfor UPDATEand DELETEfor DELETE.
database.config.
<permission>
Revokesaccesstotheconfiguration.Validpermissionsare READand UPDATE.
database.hook.record
Revokestheabilitytosethooks.
server.admin
Revokestheabilitytoaccessserverresources.
621
Traverse
SQL- TRAVERSE
Retrievesconnectedrecordscrossingrelationships.ThisworkswithboththeDocumentandGraphAPI's,meaningthatyoucan
traverserelationshipsbetweensayinvoicesandcustomersonagraph,withouttheneedtomodelthedomainusingtheGraphAPI.
Inmanycases,youmayfinditmoreefficienttouse SELECT,whichcanresultinshorterandfasterqueries.
Formoreinformation,see TRAVERSEversus SELECTbelow.
S yntax
TRAVERSE<[class.]field>|*|any()|all()
[FROM<target>]
[MAXDEPTH<number>]
WHILE<condition>
[LIMIT<max-records>]
[STRATEGY<strategy>]
<fields>Definesthefieldsyouwanttotraverse.
<target>Definesthetargetyouwanttotraverse.Thiscanbeaclass,oneormoreclusters,asingl
Download PDF
Similar pages