The Neo4j Manual v14M06
The Neo4j Team neo4jorg lthttpneo4jorggtneotechnologycom lthttpneotechnologycomgt
The Neo4j Manual v14M06by The Neo4j Team neo4jorg lthttpneo4jorggt neotechnologycom lthttpneotechnologycomgtCopyright copy 2011 Neo Technology
License Creative Commons 30This book is presented in open source and licensed through Creative Commons 30 You are free to copy distribute transmit andor adapt the work Thislicense is based upon the following conditions
Attribution You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or youruse of the work)
Share Alike If you alter transform or build upon this work you may distribute the resulting work only under the same similar or a compatible license
Any of the above conditions can be waived if you get permission from the copyright holder
In no way are any of the following rights affected by the license
bull Your fair dealing or fair use rights
bull The authorrsquos moral rights
bull Rights other persons may have either in the work itself or in how the work is used such as publicity or privacy rights
NoteFor any reuse or distribution you must make clear to the others the license terms of this work The best way to do this is with a direct link tothis page httpcreativecommonsorglicensesby-sa30 lthttpcreativecommonsorglicensesby-sa30gt
iii
Table of ContentsIntroduction viii
1 Who should read this ix2 Neo4j highlights x
I Reference Documentation 11 Installation amp Deployment 2
11 Deployment Scenarios 312 System Requirements 413 Installation 514 Upgrading 715 Usage Data Collector 9
2 Configuration amp Performance 1121 Caches in Neo4j 1222 JVM Settings 1723 File system tuning for high IO 1824 Compressed storage of short strings 19
3 Transaction management 2031 Interaction cycle 2132 Isolation levels 2233 Default locking behavior 2334 Deadlocks 2435 Delete semantics 25
4 Cypher Query Language 2641 Identifiers 2842 Start 2943 Match 3144 Where 3445 Return 3646 Aggregation 3847 Order by 4148 Skip 4349 Limit 44
5 Neo4j Server 4551 Server Installation 4652 Server Configuration 4853 Setup for remote debugging 5054 Starting the Neo4j server in high availability mode 5155 Using the server with an embedded database 5356 Server Plugins 5457 Tuning the server performance 5758 Unmanaged Extensions 58
6 REST API 6061 Service root 6162 Nodes 6263 Relationships 6664 Relationship types 7065 Node properties 7166 Relationship properties 74
The Neo4j Manual v14M06
iv
67 Indexes 7568 Traversals 7969 Built-in Graph Algorithms 105610 Batch operations 108611 Gremlin Plugin 113612 Cypher Plugin 118
7 Indexing 11971 Introduction 12072 Create 12173 Delete 12274 Add 12375 Remove 12476 Update 12577 Search 12678 Relationship indexes 12879 Scores 129710 Configuration and fulltext indexes 130711 Extra features for Lucene indexes 131712 Batch insertion 133713 Auto Indexing 134
8 Graph Algorithms 13881 Introduction 139
9 High Availability 14091 Architecture 14192 Setup and configuration 14293 How Neo4j HA operates 144
10 Operations 145101 Backup 146102 Security 148103 Monitoring 149
II Tutorials 15411 Graph Database Concepts 155
111 What is a Graph Database 156112 Comparing Database Models 160113 The Neo4j Graph Database 163
12 Using Neo4j embedded in Java applications 167121 Include Neo4j in your project 168122 Hello world 170123 User database with index 172124 Traversal 174125 Domain entities 183126 Graph Algorithm examples 184127 Reading a management attribute 186
III Tools 18713 Web Administration 188
131 Dashboard tab 189132 Data tab 190133 Console tab 191134 The Server Info tab 193
The Neo4j Manual v14M06
v
14 Neo4j Shell 194141 Starting the shell 195142 Passing options and arguments 197143 Enum options 198144 Filters 199145 Node titles 200146 How to use (individual commands) 201147 Extending the shell Adding your own commands 204148 An example shell session 205
IV Troubleshooting 20615 Troubleshooting guide 20716 Community support 208
A Manpages 209neo4j 210neo4j-shell 212neo4j-coordinator 214neo4j-coordinator-shell 215
vi
List of Figures51 Neo4j Coordinator MBeans View 5291 Typical setup when running multiple Neo4j instances in HA mode 141101 Connecting JConsole to the Neo4j Java process 149102 Neo4j MBeans View 150111 RDBMS 160112 Graph Database as RDBMS 160113 Key-Value Store 161114 Graph Database as Key-Value Store 161115 Document Store 162116 Graph Database as Document Store 162121 Node space view of users 172122 Matrix node space view 174123 User roles node space view 175124 The example graph 179125 Social network data model 180126 Andreas Kolleggers status updates 181131 Web Administration Dashboard 189132 Entity charting 189133 Status indicator panels 189134 Browsing and manipulating data 190135 Editing properties 190136 Traverse data with Gremlin 191137 Query data with Cypher 191138 Interact over HTTP 192139 JMX Attributes 193
vii
List of Tables11 Neo4j deployment options 312 Neo4j editions 521 Guidelines for heap size 1751 neo4j-wrapperconf JVM tuning properties 5771 Lucene indexing configuration parameters 13091 HighlyAvailableGraphDatabase configuration parameters 143101 MBeans exposed by the Neo4j Kernel 150102 MBean Memory Mapping 151103 MBean Locking 151104 MBean Transactions 151105 MBean Cache 151106 MBean Configuration 151107 MBean Primitive count 152108 MBean XA Resources 152109 MBean Store file sizes 1521010 MBean Kernel 1531011 MBean High Availability 153111 Using relationship direction and type 164112 Property value types 165
viii
Introduction
This is a reference manual The material is practical technical and focused on answering specificquestions It addresses how things work what to do and what to avoid to successfully run Neo4j in aproduction environment After a brief introduction each topic area assumes general familiarity as itaddresses the particular details of Neo4j
The goal is to be thumb-through and rule-of-thumb friendly
Each section should stand on its own so you can hop right to whatever interests you When possiblethe sections distill rules of thumb which you can keep in mind whenever you wander out of thehouse without this manual in your back pocket
Introduction
ix
1 Who should read thisThe topics should be relevant to architects administrators developers and operations personnel Youshould already know about Neo4j and using graphs to store data If you are completely new to Neo4jplease check out httpneo4jorg first
Introduction
x
2 Neo4j highlightsAs a robust scalable and high-performance database Neo4j is suitable for lightweight projects or fullenterprise deployment
It features
bull true ACID transactions
bull high availability
bull scales to billions of nodes and relationships
bull high speed querying through traversals
Proper ACID behavior is the foundation of data reliability Neo4j enforces that all mutating operationsoccur within a transaction guaranteeing consistent data This robustness extends from single instanceembedded graphs to multi-server high availability installations For details see Chapter 3 Transactionmanagement
Reliable graph storage can easily be added to any application A property graph can scale in sizeand complexity as the application evolves with little impact on performance Whether starting newdevelopment or augmenting existing functionality Neo4j is only limited by physical hardware
A single server instance can handle a graph of billions of nodes and relationships When datathroughput is insufficient the graph database can be distributed among multiple servers in a highavailability configuration See Chapter 9 High Availability to learn more
The graph database storage shines when storing richly-connected data Querying is performed throughtraversals which can perform millions of joins per second
Part I Reference Documentation
2
Chapter 1 Installation amp Deployment
Installation amp Deployment
3
11 Deployment ScenariosNeo4j can be embedded into your application run as a standalone server or deployed on severalmachines to provide high availability
Table 11 Neo4j deployment options
Single Instance Multiple Instances
Embedded EmbeddedGraphDatabase HighlyAvailableGraphDatabase
Standalone Neo4j Server Neo4j Server highavailability mode
111 ServerNeo4j is normally accessed as a standalone server either directly through a REST interface or througha language-specific driver More information about Neo4j server is found in Chapter 5 Neo4j ServerFor running the server in high availability mode see Section 54 ldquoStarting the Neo4j server in highavailability moderdquo
112 EmbeddedNeo4j can be embedded directly in a server application by including the appropriateJava libraries When programming you can refer to the GraphDatabaseServicelthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdb
GraphDatabaseServicehtmlgt API To switch from a single instance to multiplehighly available instances simply switch from the concrete EmbeddedGraphDatabaselthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jkernel
EmbeddedGraphDatabasehtmlgt to the HighlyAvailableGraphDatabase lthttpcomponentsneo4jorgneo4j-enterprise14M06apidocsorgneo4jkernel
HighlyAvailableGraphDatabasehtmlgt
Installation amp Deployment
4
12 System RequirementsMemory constrains graph size disk IO constrains readwrite performance as always
121 CPUPerformance is generally memory or IO bound for large graphs and compute bound for graphs whichfit in memory
MinimumIntel 486
RecommendedIntel Core i7
122 MemoryMore memory allows even larger graphs but runs the risk of inducing larger Garbage Collectionoperations
Minimum1GB
Recommended4-8GB
123 DiskAside from capacity the performance characteristics of the disk are the most important when selectingstorage
MinimumSCSI EIDE
RecommendedSSD w SATA
124 FilesystemFor proper ACID behavior the filesystem must support flush (fsync fdatasync)
Minimumext3 (or similar)
Recommendedext4 ZFS
125 SoftwareNeo4j is Java-based
Java16+
Operating SystemsLinux Windows XP Mac OS X
Installation amp Deployment
5
13 InstallationNeo4j can be installed as a server running either as a headless application or system service For Javadevelopers it is also possible to use Neo4j as a library embedded in your application
For information on installing Neo4j as a server see Section 51 ldquoServer Installationrdquo
The following table outlines the available editions and their names for use with dependencymanagement tools
TipFollow the links in the table for details on dependency configuration with Apache MavenApache Buildr Apache Ivy and Groovy Grape
Table 12 Neo4j editions
Edition Dependency Description License
Community orgneo4jneo4j lthttpsearchmavenorgsearch|gav|1|g3A22orgneo4j2220AND20a3A22neo4j22gt
a high performancefully ACIDtransactional graphdatabase
GPLv3
Advanced orgneo4jneo4j-advanced lthttpsearchmavenorgsearch|gav|1|g3A22orgneo4j2220AND20a3A22neo4j-advanced22gt
adding advancedmonitoring
AGPLv3
Enterprise orgneo4jneo4j-enterprise lthttpsearchmavenorgsearch|gav|1|g3A22orgneo4j2220AND20a3A22neo4j-enterprise22gt
adding online backupand High Availabilityclustering
AGPLv3
NoteThe listed dependeices do not contain the implementation but pulls it in transitively
For more information regarding licensing see the Licensing Guide lthttpneo4jorglicensing-guidegt
131 Embedded InstallationThe latest release is always available from httpneo4jorgdownload included as part of the Neo4jdownload packages After selecting the appropriate version for your platform embed Neo4j in yourJava application by including the Neo4j library jars in your build Either take the jar files from the lib
Installation amp Deployment
6
directory of the download or directly use the artifacts available from Maven Central Repository 1Stable and milestone releases are available there
For information on how to use Neo4j as a dependency with Maven and other dependencymanagement tools see the following table
NoteThe listed dependencies do not contain the implementation but pulls it in transitively
Maven dependency
ltprojectgt
ltdependenciesgt
ltdependencygt
ltgroupIdgtorgneo4jltgroupIdgt
ltartifactIdgtneo4jltartifactIdgt
ltversiongt$neo4j-versionltversiongt
ltdependencygt
ltdependenciesgt
ltprojectgt
Where $neo4j-version is the intended version and the artifactId is one of neo4j neo4j-advanced neo4j-enterprise
1httprepo1mavenorgmaven2orgneo4j
Installation amp Deployment
7
14 UpgradingNormally a properly shutdown Neo4j database can be upgraded directly to a new minor version Adatabase can be upgraded from a minor version to the next eg 11 ndashgt 12 and 12 ndashgt 13 but youcan not jump directly from 11 ndashgt 13 The upgrade process is a one way step databases cannot bedowngraded
However some upgrades make significant changes to the database store Neo4j will refuse to startwhen a significant upgrade is required requiring explicit upgrade configuration
141 Normal UpgradeTo perform a normal upgrade (for minor changes to the database store)
1 download the newer version of Neo4j2 cleanly shutdown the database to upgrade if it is running3 startup the database with the newer version of Neo4j
142 Special UpgradeTo perform a special upgrade (for significant changes to the database store)
1 make sure the database you are upgrading has been cleanly shut down2 set the Neo4j configuration parameter allow_store_upgrade=true3 start the database4 the upgrade will happen during startup and the process is done when the database has been
successfully started5 allow_store_upgrade=true configuration parameter should be removed set to false or
commented out
143 Upgrade 13 ndashgt 14
WarningUpgrading from 13 ndashgt 14 is done automatically but will in that process upgrade Luceneindexes to Lucene version 310 That Lucene index upgrade is irreversible
144 Upgrade 13M03 ndashgt 13M04
WarningUpgrading from 13M03 ndashgt 13M04 must be done explicitly since store format haschanged between those two versions
The store format as well as logical log format have changed between these two versions to allow forbigger stores
145 Upgrade 12 ndashgt 13
WarningUpgrading from 12 ndashgt 13 must be done explicitly since store format has changed betweenthose two versions
The store format as well as logical log format have changed between these two versions to allow forbigger stores
Installation amp Deployment
8
ImportantAlthough id ranges has been increased the space used to store the database will notincrease compared to the previous version
Upgrading between these two version needs to be performed explicitly using a configurationparameter at startup (see Special Upgrade)
CautionUpgrade cannot be performed if either the number of relationship types or the configuredblock size for either the dynamic array store or string store is greater than 65534
CautionIndexes created using the old IndexServiceLuceneIndexService are no longer accessibleout of the box in 13 in favor of the integrated index An automatic upgrade isnrsquot possibleso a full rebuild of the index data into the integrated index framework is requiredFor reference the legacy index can be downloaded from the Neo4j repository httpm2neo4jorgorgneo4jneo4j-legacy-index
146 Upgrade 11 ndashgt 12Upgrading from Neo4j 11 to Neo4j 12 is a normal upgrade
Installation amp Deployment
9
15 Usage Data CollectorThe Neo4j Usage Data Collector is a sub-system that gathers usage data reporting it to the UDC-server at udcneo4jorg It is easy to disable and does not collect any data that is confidential Formore information about what is being sent see below
The Neo4j team uses this information as a form of automatic effortless feedback from the Neo4jcommunity We want to verify that we are doing the right thing by matching download statistics withusage statistics After each release we can see if there is a larger retention span of the server software
The data collected is clearly stated here If any future versions of this system collect additional datawe will clearly announce those changes
The Neo4j team is very concerned about your privacy We do not disclose any personally identifiableinformation
151 Technical InformationTo gather good statistics about Neo4j usage UDC collects this information
bull Kernel version - the build number and if there are any modifications to the kernel
bull Store id - it is a randomized globally unique id created at the same time a database is created
bull Ping count - UDC holds an internal counter which is incremented for every ping and reset for everyrestart of the kernel
bull Source - this is either neo4j or maven If you downloaded Neo4j from the Neo4j website itrsquosneo4j if you are using Maven to get Neo4j it will be maven
bull Java version - the referrer string shows which version of Java is being used
After startup UDC waits for ten minutes before sending the first ping It does this for two reasonsfirst we donrsquot want the startup to be slower because of UDC and secondly we want to keep pingsfrom automatic tests to a minimum The ping to the UDC servers is done with a HTTP GET
152 How to disable UDCWersquove tried to make it extremely easy to disable UDC In fact the code for UDC is not even includedin the kernel jar but as a completely separate component
There are three ways you can disable UDC
1 The easiest way is to just remove the neo4j-udc-jar file By doing this the kernel will not loadUDC and no pings will be sent
2 If you are using Maven and want to make sure that UDC is never installed in your system adependency element like this will do that
ltdependencygt
ltgroupIdgtorgneo4jltgroupIdgt
ltartifactIdgtneo4jltartifactIdgt
ltversiongt$neo4j-versionltversiongt
ltexclusionsgt
ltexclusiongt
ltgroupIdgtorgneo4jltgroupIdgt
ltartifactIdgtneo4j-udcltartifactIdgt
ltexclusiongt
ltexclusionsgt
ltdependencygt
Where $neo4j-version is the Neo4j version in use
Installation amp Deployment
10
3 Lastly if you are using a packaged version of Neo4j and do not want to make any change tothe jars a system property setting like this will also make sure that UDC is never activated -Dneo4jextudcdisable=true
11
Chapter 2 Configuration amp Performance
In order to get optimum performance out of Neo4j for your application there are a few parameters thatcan be tweaked The two main components that can be configured are the Neo4j caches and the JVMthat Neo4j runs in The following sections describe how to tune these
Configuration amp Performance
12
21 Caches in Neo4jNeo4j utilizes two different types of caches A file buffer cache and an object cache The file buffercache caches the storage file data in the same format as it is stored on the durable storage mediaThe object cache caches the nodes relationships and properties in a format that is optimized for hightraversal speeds and transactional mutation
211 File buffer cache
Quick info
bull The file buffer cache is sometimes called low level cache or file system cachebull It caches the Neo4j data as stored on the durable mediabull It uses the operating system memory mapping features when possiblebull Neo4j will configure the cache automatically as long as the heap size of the JVM is
configured properly
The file buffer cache caches the Neo4j data in the same format as it is represented on the durablestorage media The purpose of this cache layer is to improve both read and write performance Thefile buffer cache improves write performance by writing to the cache and deferring durable write untilthe logical log is rotated This behavior is safe since all transactions are always durably written to thelogical log which can be used to recover the store files in the event of a crash
Since the operation of the cache is tightly related to the data it stores a short description of the Neo4jdurable representation format is necessary background Neo4j stores data in multiple files and relieson the underlying file system to handle this efficiently Each Neo4j storage file contains uniform fixedsize records of a particular type
Store file Record size Contents
nodestore 9 B Nodes
relstore 33 B Relationships
propstore 25 B Propertiesfor nodes andrelationships
stringstore 133 B Values of stringproperties
arraystore 133 B Values of arrayproperties
For strings and arrays where data can be of variable length data is stored in one or more 120Bchunks with 13B record overhead The sizes of these blocks can actually be configured when thestore is created using the string_block_size and array_block_size parameters The size of eachrecord type can also be used to calculate the storage requirements of a Neo4j graph or the appropriatecache size for each file buffer cache Note that some strings can be stored without using the stringstore see Section 24 ldquoCompressed storage of short stringsrdquo
Neo4j uses multiple file buffer caches one for each different storage file Each file buffer cachedivides its storage file into a number of equally sized windows Each cache window contains an evennumber of storage records The cache holds the most active cache windows in memory and tracks hit
Configuration amp Performance
13
vs miss ratio for the windows When the hit ratio of an uncached window gets higher than the missratio of a cached window the cached window gets evicted and the previously uncached window iscached instead
Configuration
Parameter Possible values Effect
use_memory_mapped_buffers true or false If set to true Neo4j will usethe operating systems memorymapping functionality for thefile buffer cache windows If setto false Neo4j will use its ownbuffer implementation In this casethe buffers will reside in the JVMheap which needs to be increasedaccordingly The default value forthis parameter is true except onWindows
neostore nodestore db
mapped_memory
The maximum amount of memoryto use for the file buffer cache ofthe node storage file
neostore relationshipstore
db mapped_memory
The maximum amount of memoryto use for the file buffer cache ofthe relationship store file
neostore propertystore db
index keys mapped_memory
The maximum amount of memoryto use for the file buffer cache ofthe something-something file
neostore propertystore db
index mapped_memory
The maximum amount of memoryto use for the file buffer cache ofthe something-something file
neostore propertystore db
mapped_memory
The maximum amount of memoryto use for the file buffer cache ofthe property storage file
neostore propertystore db
strings mapped_memory
The maximum amount of memoryto use for the file buffer cache ofthe string property storage file
neostore propertystore db
arrays mapped_memory
The maximum amount ofmemory to use for memorymapped buffers for this filebuffer cache The defaultunit is MiB for other unitsuse any of the following
suffixes B k M or G
The maximum amount of memoryto use for the file buffer cache ofthe array property storage file
string_block_size
The number ofbytes per block
Specifies the block size for storingstrings This parameter is onlyhonored when the store is createdotherwise it is ignored Note thateach character in a string occupiestwo bytes meaning that a blocksize of 120 (the default size) willhold a 60 character long string
Configuration amp Performance
14
Parameter Possible values Effect
before overflowing into a secondblock Also note that each blockcarries an overhead of 13 bytesThis means that if the block size is120 the size of the stored recordswill be 133 bytes
array_block_size Specifies the block size for storingarrays This parameter is onlyhonored when the store is createdotherwise it is ignored The defaultblock size is 120 bytes and theoverhead of each block is the sameas for string blocks ie 13 bytes
dump_configuration true or false If set to true the currentconfiguration settings will bewritten to the default systemoutput mostly the console or thelogfiles
When memory mapped buffers are used (use_memory_mapped_buffers = true) the heap size ofthe JVM must be smaller than the total available memory of the computer minus the total amountof memory used for the buffers When heap buffers are used (use_memory_mapped_buffers =false) the heap size of the JVM must be large enough to contain all the buffers plus the runtime heapmemory requirements of the application and the object cache
When reading the configuration parameters on startup Neo4j will automatically configure theparameters that are not specified The cache sizes will be configured based on the available memoryon the computer how much is used by the JVM heap and how large the storage files are
212 Object cache
Quick info
bull The object cache is sometimes called high level cache
bull It caches the Neo4j data in a form optimized for fast traversal
The object cache caches individual nodes and relationships and their properties in a form that isoptimized for fast traversal of the graph The content of this cache are objects with a representationgeared towards supporting the Neo4j object API and graph traversals Reading from this cache is 5 to10 times faster than reading from the file buffer cache This cache is contained in the heap of the JVMand the size is adapted to the current amount of available heap memory
Nodes and relationships are added to the object cache as soon as they are accessed The cachedobjects are however populated lazily The properties for a node or relationship are not loaded untilproperties are accessed for that node or relationship String (and array) properties are not loaded untilthat particular property is accessed The relationships for a particular node is also not loaded until therelationships are accessed for that node Eviction from the cache happens in an LRU manner when thememory is needed
Configuration amp Performance
15
Configuration
The main configuration parameter for the object cache is the cache_type parameter This specifieswhich cache implementation to use for the object cache The available cache types are
cache_type Description
none Do not use a high level cache No objects will be cached
soft Provides optimal utilization of the available memory Suitable for high performancetraversal May run into GC issues under high load if the frequently accessed parts ofthe graph does not fit in the cache
This is the default cache implementation
weak Provides short life span for cached objects Suitable for high throughput applicationswhere a larger portion of the graph than what can fit into memory is frequentlyaccessed
strong This cache will cache all data in the entire graph It will never release memory heldby the cache Provides optimal performance if your graph is small enough to fit inmemory
Heap memory usage
This table can be used to calculate how much memory the data in the object cache will occupy on a64bit JVM
Object Size Comment
344 B Size for each node (not counting its relationships or properties)
48 B Object overhead
136 B Property storage (ArrayMap 48B HashMap 88B)
136 B Relationship storage (ArrayMap 48B HashMap 88B)
Node
24 B Location of first next set of relationships
208 B Size for each relationship (not counting its properties)
48 B Object overhead
Relationship
136 B Property storage (ArrayMap 48B HashMap 88B)
116 B Size for each property of a node or relationship
32 B Data element - allows for transactional modification and keeps trackof on disk location
48 B Entry in the hash table where it is stored
12 B Space used in hash table accounts for normal fill ratio
Property
24 B Property key index
108 B Size for each relationship type for a node that has a relationship ofthat type
48 B Collection of the relationships of this type
48 B Entry in the hash table where it is stored
Relationships
12 B Space used in hash table accounts for normal fill ratio
Configuration amp Performance
16
Object Size Comment
Relationships 8 B Space used by each relationship related to a particular node (bothincoming and outgoing)
Primitive 24 B Size of a primitive property value
String 64+B Size of a string property value 64 + 2len(string) B (64 bytesplus two bytes for each character in the string)
Configuration amp Performance
17
22 JVM SettingsProperly configuring memory utilization of the JVM is crucial for optimal performance As anexample a poorly configured JVM could spend all CPU time performing garbage collection (blockingall threads from performing any work) Requirements such as latency total throughput and availablehardware have to be considered to find the right setup In production Neo4j should run on a multicoreCPU platform with the JVM in server mode
221 Configuring heap size and GCA large heap allows for larger node and relationship caches mdash which is a good thing mdash but largeheaps can also lead to latency problems caused by full garbage collection The different high levelcache implementations available in Neo4j together with a suitable JVM configuration of heap size andgarbage collection (GC) should be able to handle most workloads
The default cache (soft reference based LRU cache) works best with a heap that never gets full agraph where the most used nodes and relationships can be cached If the heap gets too full there is arisk that a full GC will be triggered the larger the heap the longer it can take to determine what softreferences should be cleared
Using the strong reference cache means that all the nodes and relationships being used must fit in theavailable heap Otherwise there is a risk of getting out-of-memory exceptions The soft reference andstrong reference caches are well suited for applications were the overal throughput is important
The weak reference cache basically needs enough heap to handle the peak load of theapplication mdash peak load multiplied by the average memory required per request It is well suited forlow latency requirements were GC interuptions are not acceptable
When running Neo4j on Windows keep in mind that the memory mapped buffers are allocated onheap by default so need to be taken into consideration when determining heap size
Table 21 Guidelines for heap size
Number ofprimitives
RAM size Heapconfiguration
Reserved RAMfor the OS
10M 2GB 512MB the rest
100M 8GB+ 1-4GB 1-2GB
1B+ 16GB-32GB+ 4GB+ 1-2GB
The recommended garbage collector to use when running Neo4j in production is the Concurrent Markand Sweep Compactor turned on by supplying -XX+UseConcMarkSweepGC as a JVM parameter
Configuration amp Performance
18
23 File system tuning for high IOIn order to support the high IO load of small transactions from a database the underlying file systemshould be tuned Symptoms for this are low CPU load with high iowait In this case there are a coupleof tweaks possible on Linux systems
bull Disable access-time updates noatimenodiratime flags for disk mount command or in the etcfstab for the database disk volume mount
bull Tune the IO scheduler for high disk IO on the database disk
Configuration amp Performance
19
24 Compressed storage of short stringsNeo4j will classify your strings and store them accordingly If a string is classified as a short string itwill be stored without indirection in the property store This means that there will be no string recordscreated for storing that string Additionally when no string record is needed to store the propertyit can be read and written in a single lookup This leads to improvements in performance and lowerstorage overhead
For a string to be classified as a short string one of the following must hold
bull It is encodable in UTF-8 or Latin-1 7 bytes or less
bull It is alphanumerical and 10 characters or less (9 if using accented european characters)
bull It consists of only upper case or only lower case characters including the punctuation charactersspace underscore period dash colon or slash Then it is allowed to be up to 12 characters
bull It consists of only numerical characters inlcuding the punctuation characters plus comma singlequote space period or dash Then it is allowed to be up to 15 characters
20
Chapter 3 Transaction management
In order to fully maintain data integrity and ensure good transactional behavior Neo4j supports theACID properties
bull atomicity - if any part of a transaction fails the database state is left unchanged
bull consistency - any transaction will leave the database in a consistent state
bull isolation - during a transaction modified data cannot be accessed by other operations
bull durability - the DBMS can always recover the results of a committed transaction
Specifically
bull All modifications to Neo4j data must be wrapped in transactions
bull The default isolation level is READ_COMMITTED
bull Data retrieved by traversals is not protected from modification by other transactions
bull Non-repeatable reads may occur (ie only write locks are acquired and held until the end of thetransaction)
bull One can manually acquire write locks on nodes and relationships to achieve higher level ofisolation (SERIALIZABLE)
bull Locks are acquired at the Node and Relationship level
bull Deadlock detection is built into the core transaction management
Transaction management
21
31 Interaction cycleAll write operations that work with the graph must be performed in a transaction Transactions arethread confined and can be nested as ldquoflat nested transactionsrdquo Flat nested transactions means thatall nested transactions are added to the scope of the top level transaction A nested transaction canmark the top level transaction for rollback meaning the entire transaction will be rolled back To onlyrollback changes made in a nested transaction is not possible
When working with transactions the interaction cycle looks like this
1 Begin a transaction
2 Operate on the graph performing write operations
3 Mark the transaction as successful or not
4 Finish the transaction
It is very important to finish each transaction The transaction will not release the locks or memoryit has acquired until it has been finished The idiomatic use of transactions in Neo4j is to use a try-finally block starting the transaction and then try to perform the write operations The last operationin the try block should mark the transaction as successful while the finally block should finish thetransaction Finishing the transaction will perform commit or rollback depending on the successstatus
CautionAll modifications performed in a transaction are kept in memory This means that verylarge updates have to be split into several top level transactions to avoid running out ofmemory It must be a top level transaction since splitting up the work in many nestedtransactions will just add all the work to the top level transaction
In an environment that makes use of thread pooling other errors may occur when failing to finish atransaction properly Consider a leaked transaction that did not get finished properly It will be tiedto a thread and when that thread gets scheduled to perform work starting a new (what looks to be a)top level transaction it will actually be a nested transaction If the leaked transaction state is ldquomarkedfor rollbackrdquo (which will happen if a deadlock was detected) no more work can be performed on thattransaction Trying to do so will result in error on each call to a write operation
Transaction management
22
32 Isolation levelsBy default a read operation will read the last committed value unless a local modification within thecurrent transaction exist The default isolation level is very similar to READ_COMMITTED reads do notblock or take any locks so non-repeatable reads can occur It is possible to achieve a stronger isolationlevel (such as REPETABLE_READ and SERIALIZABLE) by manually acquiring read and write locks
Transaction management
23
33 Default locking behavior
bull When adding changing or removing a property on a node or relationship a write lock will be takenon the specific node or relationship
bull When creating or deleting a node a write lock will be taken for the specific node
bull When creating or deleting a relationship a write lock will be taken on the specific relationship andboth its nodes
The locks will be added to the transaction and released when the transaction finishes
Transaction management
24
34 DeadlocksSince locks are used it is possible for deadlocks to happen Neo4j will however detect any deadlock(caused by acquiring a lock) before they happen and throw an exception Before the exception isthrown the transaction is marked for rollback All locks acquired by the transaction are still being heldbut will be released when the transaction is finished (in the finally block as pointed out earlier) Oncethe locks are released other transactions that were waiting for locks held by the transaction causing thedeadlock can proceed The work performed by the transaction causing the deadlock can then be retriedby the user if needed
Experiencing frequent deadlocks is an indication of concurrent write requests happening in such away that it is not possible to execute them while at the same time live up to the intended isolationand consistency The solution is to make sure concurrent updates happen in a reasonable way Forexample given two specific nodes (A and B) adding or deleting relationships to both these nodes inrandom order for each transaction will result in deadlocks when there are two or more transactionsdoing that concurrently One solution is to make sure that updates always happens in the same order(first A then B) Another solution is to make sure that each threadtransaction does not have anyconflicting writes to a node or relationship as some other concurrent transaction This can for examplebe achieved by letting a single thread do all updates of a specific type
ImportantDeadlocks caused by the use of other synchronization than the locks managed byNeo4j can still happen Since all operations in the Neo4j API are thread safe unlessspecified otherwise there is no need for external synchronization Other code that requiressynchronization should be synchronized in such a way that it never performs any Neo4joperation in the synchronized block
Transaction management
25
35 Delete semanticsWhen deleting a node or a relationship all properties for that entity will be automatically removed butthe relationships of a node will not be removed
CautionNeo4j enforces a constraint (upon commit) that all relationships must have a validstart node and end node In effect this means that trying to delete a node that still hasrelationships attached to it will throw an exception upon commit It is however possibleto choose in which order to delete the node and the attached relationships as long as norelationships exist when the transaction is committed
The delete semantics can be summarized in the following bullets
bull All properties of a node or relationship will be removed when it is deleted
bull A deleted node can not have any attached relationships when the transaction commits
bull It is possible to acquire a reference to a deleted relationship or node that has not yet beencommitted
bull Any write operation on a node or relationship after it has been deleted (but not yet committed) willthrow an exception
bull After commit trying to acquire a new or work with an old reference to a deleted node or relationshipwill throw an exception
26
Chapter 4 Cypher Query Language
CautionThis is an experimental feature
A new query language code-named ldquoCypherrdquo has been added to Neo4j It allows for expressive andefficient querying of the graph store without having to write traversers in code
Cypher is designed to be a humane query language suitable for both developers and (importantly wethink) operations professionals who want to make ad-hoc queries on the database Its constructs arebased on English prose and neat iconography which helps to make it (somewhat) self-explanatory
Cypher is inspired by a number of different approaches and builds upon established practices forexpressive querying Most of the keywords like WHERE and ORDER BY are inspired by SQL lthttpenwikipediaorgwikiSQLgt Pattern matching borrows expression approaches from SPARQL lthttpenwikipediaorgwikiSPARQLgt Regular expression matching is implemented using the Scalaprogramming language lthttpwwwscala-langorggt
Cypher is a declarative language It focuses on the clarity of expressing what to retrieve from a graphnot how to do it in contrast to imperative languages like Java and Scala and scripting languages likeGremlin lthttpgremlintinkerpopcomgt (supported via the Section 611 ldquoGremlin Pluginrdquo) and theJRuby Neo4j bindings lthttpneo4jrubyforgeorggt This makes the concern of how to optimizequeries in implementation detail not exposed to the user
The query language is comprised of several distinct parts
Letrsquos see three of them in action
For example here is a query which finds a user called John in an index and then traverses the graphlooking for friends of Johns friends (though not his direct friends) before returning both John and anyfriends-of-friends that are found
Next up we will add filtering to set all four parts in motion
In this next example we take a list of users (by node ID) and traverse the graph looking for thoseother users that have an outgoing friend relationship returning only those followed users who areolder than 18
In Java using the query language looks something like this
db = new ImpermanentGraphDatabase()
Cypher Query Language
27
engine = new ExecutionEngine( db )
CypherParser parser = new CypherParser()
ExecutionEngine engine = new ExecutionEngine(db)
Query query = parserparse( start n=(0) where 1=1 return n )
ExecutionResult result = engineexecute( query )
assertThat( resultcolumns() hasItem( n ) )
IteratorltNodegt n_column = resultcolumnAs( n )
assertThat( asIterable( n_column ) hasItem(dbgetNodeById(0)) )
assertThat( resulttoString() containsString(Node[0]) )
Cypher Query Language
28
41 IdentifiersWhen you reference parts of the pattern you do so by naming them
start identifier=(0) return identifier
Identifiers are can be lower or upper case and may contain underscore If other characters are neededyou can use the ` sign Same rules apply to property names
start a=(0) return a`propertywithperiods`
Cypher Query Language
29
42 StartEvery query describes a pattern and in that pattern one can have multiple bound points A boundpoint is a relationship or a node that form the starting points for a pattern match You can either bindpoints by id or by index lookups
421 Node by idIncluding a node as a start point is done by using parenthesis
Query
start n=(0) return n
The reference node is returned
Result
+-----------+
| n |
+-----------+
| Node[0] |
+-----------+
1 rows 0 ms
422 Multiple nodes by idMultiple nodes are selected by listing them separated by commas
Query
start n=(1 2 3) return n
The nodes listed in the START statement
Result
+--------------------+
| n |
+--------------------+
| Node[1]name-gtA |
| Node[2]name-gtB |
| Node[3]name-gtC |
+--------------------+
3 rows 1 ms
423 Node by index lookupIf the start point can be found by index lookups it can be done like this (index-name key value)Like this
Query
start n=(nodesnameA) return n
The node indexed with name A is returned
Result
+--------------------+
| n |
+--------------------+
| Node[1]name-gtA |
+--------------------+
1 rows 1 ms
Cypher Query Language
30
424 Node by index queryIf the start point can be found by index queries it can be done like this (index-name query)Thisallows you to write more advanced index queries
Query
start n=(nodesnameA) return n
The node indexed with name A is returned
Result
+--------------------+
| n |
+--------------------+
| Node[1]name-gtA |
+--------------------+
1 rows 0 ms
425 Multiple start pointsSometimes you want to bind multiple start points Just list them separated by commas
Query
start a=(1) b=(2) return ab
Both the A and the B node are returned
Result
+-----------------------------------------+
| a | b |
+-----------------------------------------+
| Node[1]name-gtA | Node[2]name-gtB |
+-----------------------------------------+
1 rows 1 ms
Cypher Query Language
31
43 MatchIn the match part of a query the pattern is described The description of the pattern is made up of oneor more paths separated by commas
All parts of the pattern must be directly or indirectly bound to a start point
431 Related nodesThe symbol mdash means related to without regard to type or direction
Query
start n=(3) match (n)--(x) return x
All nodes related to A are returned
Result
+--------------------+
| x |
+--------------------+
| Node[4]name-gtB |
| Node[1]name-gtD |
| Node[5]name-gtC |
+--------------------+
3 rows 1 ms
432 Outgoing relationshipsWhen the direction of a relationship is interesting it is shown by using --gt or lt-- like this
Query
start n=(3) match (n)--gt(x) return x
All nodes that A has outgoing relationships to
Result
+--------------------+
| x |
+--------------------+
| Node[4]name-gtB |
| Node[5]name-gtC |
+--------------------+
2 rows 2 ms
433 Directed relationships and identifierIf an identifier is needed either for filtering on properties of the relationship or to return therelationship this is how you introduce the identifier
Query
start n=(3) match (n)-[r]-gt() return r
All outgoing relationships from node A
Result
+---------------+
| r |
+---------------+
| KNOWS[0] |
Cypher Query Language
32
| BLOCKS[1] |
+---------------+
2 rows 1 ms
434 Match by relationship typeWhen you know the relationship type you want to match on you can specify it by using a colon
Query
start n=(3) match (n)-[BLOCKS]-gt(x) return x
All nodes that are BLOCKed by A
Result
+--------------------+
| x |
+--------------------+
| Node[5]name-gtC |
+--------------------+
1 rows 1 ms
435 Match by relationship type and use an identifierIf you both want to introduce an identifier to hold the relationship and specify the relationship typeyou want just add them both like this
Query
start n=(3) match (n)-[rBLOCKS]-gt() return r
All BLOCK relationship going out from A
Result
+---------------+
| r |
+---------------+
| BLOCKS[1] |
+---------------+
1 rows 1 ms
436 Multiple relationshipsRelationships can be expressed by using multiple statements in the form of ()--() or they can bestringed together like this
Query
start a=(3) match (a)-[KNOWS]-gt(b)-[KNOWS]-gt(c) return abc
The three nodes in the path
Result
+--------------------------------------------------------------+
| a | b | c |
+--------------------------------------------------------------+
| Node[3]name-gtA | Node[4]name-gtB | Node[2]name-gtE |
+--------------------------------------------------------------+
1 rows 1 ms
437 Complex matchingUsing Cypher you can also express more complex patterns to match on like a diamond shape pattern
Cypher Query Language
33
Query
start a=(3)
match (a)-[KNOWS]-gt(b)-[KNOWS]-gt(c) (a)-[BLOCKS]-(d)-[KNOWS]-(c)
return abcd
The four nodes in the path
Result
+-----------------------------------------------------------------------------------+
| a | b | c | d |
+-----------------------------------------------------------------------------------+
| Node[3]name-gtA | Node[4]name-gtB | Node[2]name-gtE | Node[5]name-gtC |
+-----------------------------------------------------------------------------------+
1 rows 1 ms
Cypher Query Language
34
44 WhereIf you need filtering apart from the pattern of the data that you are looking for you can add clauses inthe where part of the query
441 Boolean operationsYou can use the expected boolean operators AND and OR and also the boolean function NOT()
Query
start n=(2 1) where (nage lt 30 and nname = Tobias) or not(nname = Tobias) return n
The node
Result
+-----------------------------------------------+
| n |
+-----------------------------------------------+
| Node[2]name-gtAndresage-gt36belt-gtwhite |
| Node[1]name-gtTobiasage-gt25 |
+-----------------------------------------------+
2 rows 1 ms
442 Filter on node propertyTo filter on a property write your clause after the WHERE keyword
Query
start n=(2 1) where nage lt 30 return n
The node
Result
+---------------------------------+
| n |
+---------------------------------+
| Node[1]name-gtTobiasage-gt25 |
+---------------------------------+
1 rows 4 ms
443 Regular expressionsYou can match on regular expressions by using =~ regexp like this
Query
start n=(2 1) where nname =~ Tob return n
The node named Tobias
Result
+---------------------------------+
| n |
+---------------------------------+
| Node[1]name-gtTobiasage-gt25 |
+---------------------------------+
1 rows 0 ms
444 Filtering on relationship typeYou can put the exact relationship type in the MATCH pattern but sometimes you want to be able todo more advanced filtering on the type You can use the special property TYPE to compare the type
Cypher Query Language
35
with something else In this example the query does a regular expression comparison with the nameof the relationship type
Query
start n=(2) match (n)-[r]-gt() where r~TYPE =~ K return r
The relationship that has a type whose name starts with K
Result
+--------------+
| r |
+--------------+
| KNOWS[0] |
+--------------+
1 rows 1 ms
445 Property existsTo only include nodesrelationships that have a property just write out the identifier and the propertyyou expect it to have
Query
start n=(2 1) where nbelt return n
The node named Andres
Result
+-----------------------------------------------+
| n |
+-----------------------------------------------+
| Node[2]name-gtAndresage-gt36belt-gtwhite |
+-----------------------------------------------+
1 rows 1 ms
Cypher Query Language
36
45 ReturnIn the return part of your query you define which parts of the pattern you are interested in It can benodes relationships or properties on these
451 Return nodesTo return a node list it in the return statemenet
Query
start n=(2) return n
The node
Result
+--------------------+
| n |
+--------------------+
| Node[2]name-gtB |
+--------------------+
1 rows 0 ms
452 Return relationshipsTo return a relationship just include it in the return list
Query
start n=(1) match (n)-[rKNOWS]-gt(c) return r
The relationship
Result
+--------------+
| r |
+--------------+
| KNOWS[0] |
+--------------+
1 rows 0 ms
453 Relationship typeWhen you want to output the relationship type and not the whole relationship you can use ~TYPE
Query
start n=(1) match (n)-[r]-gt() return r~TYPE
The relationship type of r
Result
+--------+
| r~TYPE |
+--------+
| KNOWS |
| BLOCKS |
+--------+
2 rows 1 ms
454 Return propertyTo return a property use the dot separator like this
Cypher Query Language
37
Query
start n=(1) return nname
The the value of the property name
Result
+--------+
| nname |
+--------+
| A |
+--------+
1 rows 1 ms
455 Identifier with uncommon charactersTo introduce a placeholder that is made up of characters that are outside of the english alphabet youcan use the ` to enclose the identifier like this
Query
start `This isnt a common identifier`=(1)
return `This isnt a common identifier``ltlt__gtgt`
The node indexed with name A is returned
Result
+-------------------------------------------+
| This isnt a common identifierltlt__gtgt |
+-------------------------------------------+
| Yes |
+-------------------------------------------+
1 rows 0 ms
456 Optional propertiesIf a property might or might not be there you can select it optionally by adding a questionmark to theidentifier like this
Query
start n=(1 2) return nage
The age when the node has that property or null if the property is not there
Result
+--------+
| nage |
+--------+
| 55 |
| ltnullgt |
+--------+
2 rows 1 ms
Cypher Query Language
38
46 AggregationTo calculate aggregated data Cypher offers aggregation much like SQLrsquos GROUP BY If anyaggregation functions are found in the RETURN statement all the columns without aggregatingfunctions are used as the grouping key
461 COUNTCOUNT is used to count the number of rows COUNT can be used in two forms - COUNT() whichjust counts the number of matching rows and COUNT(ltidentifiergt) which counts the number ofnon-null values in ltidentifiergt
462 Count nodesTo count the number of nodes for example the number of nodes connected to one node you can usecount()
Query
start n=(2) match (n)--gt(x) return n count()
The start node and the count of related nodes
Result
+--------------------------------------------+
| n | count() |
+--------------------------------------------+
| Node[2]name-gtAproperty-gt13 | 3 |
+--------------------------------------------+
1 rows 2 ms
463 Count entitiesInstead of counting the number of results with count() it might be more expressive to include thename of the identifier you care about
Query
start n=(2) match (n)--gt(x) return count(x)
The number of connected nodes from the start node
Result
+----------+
| count(x) |
+----------+
| 3 |
+----------+
1 rows 1 ms
464 Count non null valuesYou can count the non-null values by using count(ltidentifiergt)
Query
start n=(2341) return count(nproperty)
The count of related nodes
Result
+-------------------+
Cypher Query Language
39
| count(nproperty) |
+-------------------+
| 3 |
+-------------------+
1 rows 1 ms
465 SUMThe SUM aggregation function simply sums all the numeric values it encounters Null values aresilently dropped This is an example of how you can use SUM
Query
start n=(234) return sum(nproperty)
The sum of all the values in the property property
Result
+-----------------+
| sum(nproperty) |
+-----------------+
| 90 |
+-----------------+
1 rows 1 ms
466 AVGAVG calculates the average of a numeric column
Query
start n=(234) return avg(nproperty)
The average of all the values in the property property
Result
+-----------------+
| avg(nproperty) |
+-----------------+
| 300 |
+-----------------+
1 rows 1 ms
467 MAXMAX find the largets value in a numeric column
Query
start n=(234) return max(nproperty)
The largest of all the values in the property property
Result
+-----------------+
| max(nproperty) |
+-----------------+
| 44 |
+-----------------+
1 rows 1 ms
468 MINMIN takes a numeric property as input and returns the smallest value in that column
Cypher Query Language
40
Query
start n=(234) return min(nproperty)
The smallest of all the values in the property property
Result
+-----------------+
| min(nproperty) |
+-----------------+
| 13 |
+-----------------+
1 rows 1 ms
Cypher Query Language
41
47 Order byTo sort the output use the Order by clause Note that you can not sort on nodes or relationships juston properties on these
471 Order nodes by propertyORDER BY is used to sort the output
Query
start n=(312) return n order by nname
The nodes sorted by their name
Result
+----------------------------------------+
| n |
+----------------------------------------+
| Node[1]name-gtAage-gt34length-gt170 |
| Node[2]name-gtBage-gt34 |
| Node[3]name-gtCage-gt32length-gt185 |
+----------------------------------------+
3 rows 1 ms
472 Order nodes by multiple propertiesYou can order by multiple properties by stating each identifier in the ORDER BY statement Cypherwill sort the result by the first identifier listed and for equals values go to the next property in theorder by and so on
Query
start n=(312) return n order by nage nname
The nodes sorted first by their age and then by their name
Result
+----------------------------------------+
| n |
+----------------------------------------+
| Node[3]name-gtCage-gt32length-gt185 |
| Node[1]name-gtAage-gt34length-gt170 |
| Node[2]name-gtBage-gt34 |
+----------------------------------------+
3 rows 1 ms
473 Order nodes in descending orderBy adding DESC[ENDING] after the identifier to sort on the sort will be done in reverse order
Query
start n=(312) return n order by nname DESC
The nodes sorted by their name reversely
Result
+----------------------------------------+
| n |
+----------------------------------------+
| Node[3]name-gtCage-gt32length-gt185 |
Cypher Query Language
42
| Node[2]name-gtBage-gt34 |
| Node[1]name-gtAage-gt34length-gt170 |
+----------------------------------------+
3 rows 1 ms
474 Ordering nullWhen sorting the result set null will always come at the end of the result set for ascending sortingand first when doing descending sort
Query
start n=(312) return nlength n order by nlength
The nodes sorted by the length property with a node without that property last
Result
+---------------------------------------------------+
| nlength | n |
+---------------------------------------------------+
| 170 | Node[1]name-gtAage-gt34length-gt170 |
| 185 | Node[3]name-gtCage-gt32length-gt185 |
| ltnullgt | Node[2]name-gtBage-gt34 |
+---------------------------------------------------+
3 rows 1 ms
Cypher Query Language
43
48 SkipSkip enables the return of only subsets of the total result By using skip the result set will trimmedfrom the top Please note that no guarantees are made on the order of the result unless the queryspecies the order by clause
481 Skip first threeTo return a subset of the result starting from third result use this syntax
Query
start n=(3 4 5 1 2) return n order by nname skip 3
The first three nodes are skipped and only the last two are returned
Result
+--------------------+
| n |
+--------------------+
| Node[1]name-gtD |
| Node[2]name-gtE |
+--------------------+
2 rows 1 ms
482 Return middle twoTo return a subset of the result starting from somewhere in the middle use this syntax
Query
start n=(3 4 5 1 2) return n order by nname skip 1 limit 2
Two nodes from the middle are returned
Result
+--------------------+
| n |
+--------------------+
| Node[4]name-gtB |
| Node[5]name-gtC |
+--------------------+
2 rows 1 ms
Cypher Query Language
44
49 LimitLimit enables the return of only subsets of the total result
491 Return first partTo return a subset of the result starting from the top use this syntax
Query
start n=(3 4 5 1 2) return n limit 3
The top three items are returned
Result
+--------------------+
| n |
+--------------------+
| Node[3]name-gtA |
| Node[4]name-gtB |
| Node[5]name-gtC |
+--------------------+
3 rows 3 ms
45
Chapter 5 Neo4j Server
Neo4j Server
46
51 Server InstallationNeo4j can be installed as a server running either as a headless application or system service
1 Download the latest release from httpneo4jorgdownload
bull select the appropriate version for your platform
2 Extract the contents of the archive
bull refer to the top-level extracted directory as NEO4J-HOME
3 Use the scripts in the bin directory
bull for LinuxMacOS run $NEO4J_HOMEbinneo4j start
bull for Windows double-click on NEO4J_HOMEbinNeo4jbat
4 Refer to the packaged information in the doc directory for details
511 As a Windows serviceWith administrative rights Neo4j can be installed as a Windows service
1 Click Start ndashgt All Programs ndashgt Accessories
2 Right click Command Prompt ndashgt Run as Administrator
3 Provide authorization andor the Administrator password
4 Navigate to NEO4J_HOME
5 Run binNeo4jbat install
To uninstall run binNeo4jbat remove as Administrator
To query the status of the service run binNeo4jbat query
To startstop the service from the command prompt run binNeo4jbat +action+
512 Linux ServiceNeo4j can participate in the normal system startup and shutdown process The following procedureshould work on most popular Linux distributions
1 cd $NEO4J_HOME
2 sudo binneo4j install
bull if asked enter your password to gain super-user privileges
3 service neo4j-server status
bull should indicate that the server is not running
4 service neo4j-server start
bull will start the server
During installation you will be given the option to select the user Neo4j will run as You will be asked to supply a username (defaulting to `neo4j`) and if that user is not present on the system it will be created as a system account and the `$NEO4J_HOMEdata` directory will be `chown`ed to that user
You are encouraged to create a dedicated user for running the service and for that reason it is suggested that you unpack the distribution package under `opt` or your site specific optional packages directory
Finally note that if you chose to create a new user account on uninstall you will be prompted to remove it from the system
513 Macintosh ServiceNeo4j can be installed as a Mac launchd job
1 cd $NEO4J_HOME
2 sudo binneo4j install
Neo4j Server
47
bull if asked enter your password to gain super-user privileges
3 launchctl load ~LibraryLaunchAgentswrapperneo4j-serverplist
bull needed to tell launchd about the job
4 launchctl list | grep neo
bull should reveal the launchd wrapperneo4j-server job for running the Neo4j Server
5 launchctl start wrapperneo4j-server
bull to start the Neo4j Server under launchd control
6 binneo4j status
bull should indicate that the server is running
514 Multiple Server instances on one machineNeo4j can be set up to run as several instances on one machine providing for instance severaldatabases for development To configure install two instances of the Neo4j Server in two differentdirectories Before running the Windows install or startup change in confneo4j-wrapperconf
Name of the service for the first instance
wrappername=neo4j_1
and for the second instance
Name of the service for the second instance
wrappername=neo4j_2
in order not to get name clashes installing and starting the instances as services
Also the port numbers for the web administration and the servers should be changed to non-clashingvalues in confneo4j-serverproperties
Server 1 (port 7474)
orgneo4jserverwebserverport=7474
orgneo4jserverwebadmindatauri=httplocalhost7474dbdata
orgneo4jserverwebadminmanagementuri=httplocalhost7474dbmanage
Server 2 (port 7475)
orgneo4jserverwebserverport=7475
orgneo4jserverwebadmindatauri=httplocalhost7475dbdata
orgneo4jserverwebadminmanagementuri=httplocalhost7475dbmanage
Neo4j Server
48
52 Server Configuration
Quick info
bull The serverrsquos primary configuration file is found under confneo4j-serverproperties
bull The conflog4jproperties file contains the default server logging configuration
bull Low-level performance tuning parameters are found in confneo4jproperties
bull Configuraion of the deamonizing wrapper are found in confneo4j-wrapperproperties
521 Important server configurations parametersThe main configuration file for the server can be found at confneo4j-serverproperties This filecontains several important settings and although the defaults are sensible administrators might chooseto make changes (especially to the port settings)
Set the location on disk of the database directory like this
orgneo4jserverdatabaselocation=datagraphdb
NoteOn Windows systems absolute locations including drive letters need to read cdatadb
Specify the HTTP server port supporting data administrative and UI access
orgneo4jserverwebserverport=7474
Set the location of the round-robin database directory which gathers metrics on the running serverinstance
orgneo4jserverwebadminrrdblocation=datagraphdbrrd
Set the URI path for the REST data API through which the database is accessed For non-local accessuse the full URI of your server eg httpexampleorg7575database For local access use a relativeURI eg dbdata
orgneo4jserverwebadmindatauri=dbdata
Setting the management URI for the administration API that the Webadmin tool uses For non-localaccess use the full URI of your server eg httpexampleorg7575databasemanagement For localaccess use a relative URI eg dbmanage
orgneo4jserverwebadminmanagementuri=dbmanage
If you plan to connect to the Webadmin from other than localhost put in the external hostname ofyour server instead of localhost eg httpmyhost7474dbmanage Force the server to use IPv4network addresses in confneo4j-wrapperconf under the section Java Additional Parameters add anew paramter
wrapperjavaadditional3=-DjavanetpreferIPv4Stack=true
Low-level performance tuning parameters can be explicitly set by referring to the following property
orgneo4jserverdbtuningproperties=neo4jproperties
If this property isnrsquot set the server will look for a file called neo4jproperties in the same directory asthe neo4j-serverproperties file
Neo4j Server
49
If this property isnrsquot set and there is no neo4jproperties file in the default configuration directorythen the server will log a warning Subsequently at runtime the database engine will attempt tune itselfbased on the prevailing conditions
522 Neo4j Database performance configurationThe fine-tuning of the low-level Neo4j graph database engine is specified in a separate properties fileconfneo4jproperties
The graph database engine has a range of performance tuning options which are enumerated inSection 57 ldquoTuning the server performancerdquo Note that other factors than Neo4j tuning shouldbe considered when performance tuning a server including general server load memory and filecontention and even garbage collection penalties on the JVM though such considerations are beyondthe scope of this configuration document
523 Logging configurationThe logging framework in use by the Neo4j server is javautillogging lthttpdownloadoraclecomjavase6docstechnotesguidesloggingoverviewhtmlgt and isconfigured in confloggingproperties
By default it is setup to print INFO level messages both on screen and in a rolling file in datalogMost deployments will choose to use their own configuration here to meet local standards Duringdevelopment much useful information can be found in the logs so some form of logging to disk iswell worth keeping On the other hand if you want to completely silence the console output set
javautilloggingConsoleHandlerlevel=OFF
Apart from log statements originating from the Neo4j server other libraries report their messagesthrough various frameworks
Zookeeper is hardwired to use the log4j logging framework The bundled conflog4jproperties appliesfor this use only and uses a rolling appender and outputs logs by default to the datalog directory
524 Other configuration options
Enabling logging from the garbage collectorTo get garbage collection logging output you have to pass the corresponding option to the server JVMexecutable by setting in confneo4j-wrapperconf the value
wrapperjavaadditional3=-Xloggcdatalogneo4j-gclog
This line is already present and needs uncommenting Note also that logging is not directed toconsole You will find the logging statements in datalogne4j-gclog or whatever directory you set atthe option
Neo4j Server
50
53 Setup for remote debuggingIn order to configure the Neo4j server for remote debugging sessions the Java debugging parametersneed to be passed to the Java process through the configuration They live in the confneo4j-wrapperproperties file
In order to specify the parameters add a line for the additional Java arguments like this
Java Additional Parameters
wrapperjavaadditional1=-Dorgneo4jserverproperties=confneo4j-serverproperties
wrapperjavaadditional2=-Dlog4jconfiguration=fileconflog4jproperties
wrapperjavaadditional3=-agentlibjdwp=transport=dt_socketserver=ysuspend=naddress=5005 -Xdebug-Xnoagent-Djavacompiler=NONE-Xrunjdwptransport=dt_socketserver=ysuspend=naddress=5005
This configuration will start a Neo4j server ready for remote debugging attachement at localhost andport 5005 Use these parameters to attach to the process from Eclipse IntelliJ or your remote debuggerof choice after starting the server
Neo4j Server
51
54 Starting the Neo4j server in high availability mode
NoteThe High Availability features are only available in the Neo4j Enterprise Edition
To run the Neo4j server in high availability mode there are two things you need to do You have toconfigure the server to start up the database in high availability mode and you have to configure theNeo4j database for operating in high availability mode
Instructing the server to start the database in high availability mode is as easy as settingthe orgneo4jserverdatabasemode property in the server properties file (confneo-serverproperties) to ha The default value for this parameter is single which will start the databasein standalone mode without participating in a cluster still giving you Online Backup
Configuring the Neo4j database for operating in high availability mode requires specifying a fewproperties in confneo4jproperties First you need to specify hamachine_id this is a positive integerid that uniquely identifies this server in the cluster
Example hamachine_id = 1
Then you have to specify hazoo_keeper_servers this is a comma separated list of hosts and portsfor communicating with each member of the Neo4j Coordinator cluster
For example hazoo_keeper_servers = neo4j-manager-012180neo4j-manager-022180neo4j-manager-032180
You can also optionally configure the hacluster_name This is the name of the cluster thisinstance is supposed to join Accepted characters are alphabetical numerical dot dash andunderscore This configuration is useful if you have multiple Neo4j HA clusters managed by the sameCoordinator cluster
Example hacluster_name = my_neo4j_ha_cluster
541 Starting a Neo4j CoordinatorA Neo4j Coordinator cluster provides the Neo4j HA Data cluster with reliable coordination oflifecycle activities like electing the master Neo4j Server includes everything needed for running aNeo4j Coordinator
Configuration of a Coordinator is specified in these files
bull confcoordcfg - coordinator operational settings
bull datacoordinatormyid - unqiue identification of the coordinator
Once a Neo4j Coordinator instance has been configured you can use the binneo4j-coordinatorcommand to start the Neo4j Coordinator server on all desired servers with the same configuration justchanging the datacoordinatormyid to unique numbers You can check that the coordinator is up byrunning jconsole attaching to the JVM and check for orgapachezookeeper MBeans
Neo4j Server
52
Figure 51 Neo4j Coordinator MBeans View
542 Starting the Neo4j ServerOnce the desired neo4j Coordinators are up and running you are ready to start your Neo4j HAinstance using binneo4j start The details of the HA logs are available in the messageslog of thegraph database data directory normally datagraphdbmesageslog You should see an entry like thisone
Tue Apr 12 092558 CEST 2011 MasterServer communication server started and bound to 6361
Tue Apr 12 092558 CEST 2011 Started as master
Tue Apr 12 092558 CEST 2011 master-rebound set to 1
Neo4j Server
53
55 Using the server with an embedded databaseEven if you are using the Neo4j Java API directly for instance via EmbeddedGraphDatabase orHighlyAvailableGraphDatabase you can still use the features the server provides
The neo4j server exposes a class called WrappingNeoServerBootstrapper which is capable of startinga neo4j server in the same process as your application using an AbstractGraphDatabase instance youprovide
This gives your application among other things the REST API statistics gathering and the webadministration interface that comes with the server
Usage example
WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper( myDb )
srvstart()
Server is now running in background threads
srvstop()
551 Providing custom configurationYou can modify the server settings programmatically and within reason the same settings areavailable to you here as those outlined in the Server Configuration chapter
The settings that are not available (or rather that are ignored) are those that concern the underlyingdatabase such as database location and database configuration path
Custom config example
EmbeddedServerConfigurator config = new EmbeddedServerConfigurator( myDb )
configconfiguration()
setProperty( ConfiguratorWEBSERVER_PORT_PROPERTY_KEY 7575 )
WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper( myDb config )
srvstart()
Neo4j Server
54
56 Server Plugins
Quick info
bull The serverrsquos functionality can be extended by adding plugins Plugins are user-specifiedcode which extend the capabilities of the database nodes or relationships The neo4j serverwill then advertise the plugin functionality within representations as clients interact viaHTTP
Plugins provide an easy way to extend the Neo4j REST API with new functionality without the needto invent your own API Think of plugins as server-side scripts that can add functions for retrievingand manipulating nodes relationships paths properties or indices
TipIf you want to have full control over your API and are willing to put in the effort andunderstand the risks then Neo4j server also provides hooks for unmanaged extensionsbased on JAX-RS
The needed classes reside in the orgneo4jserver-api lthttpsearchmavenorgsearch|gav|1|g3A22orgneo4j2220AND20a3A22server-api22gt jar file See the linked page fordownloads and instructions on how to include it using dependency management For Maven projectsadd the Server API dependencies in your pomxml like this
ltdependencygt
ltgroupIdgtorgneo4jltgroupIdgt
ltartifactIdgtserver-apiltartifactIdgt
ltversiongt$neo4j-versionltversiongt
ltdependencygt
Where $neo4j-version is the intended version
To create a plugin your code must inherit from the ServerPlugin lthttpcomponentsneo4jorgserver-api14M06apidocsorgneo4jserverpluginsServerPluginhtmlgt class Your plugin should also
bull ensure that it can produce an (Iterable of) Node Relationship or Path
bull specify parameters
bull specify a point of extension and of course
bull contain the application logic
bull make sure that the discovery point type in the PluginTarget and the Source parameter are ofthe same type
An example of a plugin which augments the database (as opposed to nodes or relationships) follows
Get all nodes or relationships plugin
Description( An extension to the Neo4j Server for getting all nodes or relationships )
public class GetAll extends ServerPlugin
Name( get_all_nodes )
Description( Get all nodes from the Neo4j graph database )
PluginTarget( GraphDatabaseServiceclass )
public IterableltNodegt getAllNodes( Source GraphDatabaseService graphDb )
return graphDbgetAllNodes()
Neo4j Server
55
Description( Get all relationships from the Neo4j graph database )
PluginTarget( GraphDatabaseServiceclass )
public IterableltRelationshipgt getAllRelationships( Source GraphDatabaseService graphDb )
return new NestingIterableltRelationship Nodegt( graphDbgetAllNodes() )
Override
protected IteratorltRelationshipgt createNestedIterator( Node item )
return itemgetRelationships( DirectionOUTGOING )iterator()
Find the shortest path between two nodes plugin
public class ShortestPath extends ServerPlugin
Description( Find the shortest path between two nodes )
PluginTarget( Nodeclass )
public IterableltPathgt shortestPath(
Source Node source
Description( The node to find the shortest path to )
Parameter( name = target ) Node target
Description( The relationship types to follow when searching for the shortest path(s) +
Order is insignificant if omitted all types are followed )
Parameter( name = types optional = true ) String[] types
Description( The maximum path length to search for default value (if omitted) is 4 )
Parameter( name = depth optional = true ) Integer depth )
Expander expander
if ( types == null )
expander = TraversalexpanderForAllTypes()
else
expander = TraversalemptyExpander()
for ( int i = 0 i lt typeslength i++ )
expander = expanderadd( DynamicRelationshipTypewithName( types[i] ) )
PathFinderltPathgt shortestPath = GraphAlgoFactoryshortestPath(
expander depth == null 4 depthintValue() )
return shortestPathfindAllPaths( source target )
To deploy the code simply compile it into a jar file and place it onto the server classpath (whichby convention is the plugins directory under the Neo4j server home directory) The jar file mustinclude the file META-INFservicesorgneo4jserverpluginsServerPlugin with the fully qualifiedname of the implementation class In this case wersquod have only a single entry in our config file thoughmultiple entries are allowed each on a separate line
orgneo4jserverexamplesGetAll
Any other plugins in the same jar file must be listed here
The code above makes an extension visible in the database representation (via the PluginTargetannotation) whenever it is served from the Neo4j Server Simply changing the PluginTargetparameter to Nodeclass or Relationshipclass allows us to target those parts of the data model
Neo4j Server
56
should we wish The functionality extensions provided by the plugin are automatically advertisedin representations on the wire For example clients can discover the extension implemented by theabove plugin easily by examining the representations they receive as responses from the server egby performing a GET on the default database URI
curl -v httplocalhost7474dbdata
The response to the GET request will contain (by default) a JSON container that itself contains acontainer called extensions where the available plugins are listed In the following case we onlyhave the GetAll plugin registered with the server so only its extension functionality is availableExtension names will be automatically assigned based on method names if not specifically specifiedusing the Name annotation
extensions-info httplocalhost7474dbdataext
node httplocalhost7474dbdatanode
node_index httplocalhost7474dbdataindexnode
relationship_index httplocalhost7474dbdataindexrelationship
reference_node httplocalhost7474dbdatanode0
extensions_info httplocalhost7474dbdataext
extensions
GetAll
get_all_nodes httplocalhost7474dbdataextGetAllgraphdbget_all_nodes
get_all_relationships httplocalhost7474dbdataextGetAllgraphdbgetAllRelationships
Performing a GET on one of the two extension URIs gives back the meta information about theservice
curl httplocalhost7474dbdataextGetAllgraphdbget_all_nodes
extends graphdb
description Get all nodes from the Neo4j graph database
name get_all_nodes
parameters [ ]
To use it just POST to this URL with parameters as specified in the description and encoded asJSON data content Fex for calling the shortest path extension (URI gotten from a GET to httplocalhost7474dbdatanode123)
curl -X POST httplocalhost7474dbdataextGetAllnode123shortestPath -H Content-Type applicationjson -d targethttplocalhost7474dbdatanode456ampdepth=5
If everything is OK a response code 200 and a list of zero or more items will be returned If nothing isreturned (null returned from extension) an empty result and response code 204 will be returned If theextension throws an exception response code 500 and a detailed error message is returned
Extensions that do any kind of write operation will have to manage their own transactions ietransactions arenrsquot managed automatically
Through this model any plugin can naturally fit into the general hypermedia scheme that Neo4jespouses - meaning that clients can still take advantage of abstractions like Nodes Relationshipsand Paths with a straightforward upgrade path as servers are enriched with plugins (old clients donrsquotbreak)
Neo4j Server
57
57 Tuning the server performanceAt the heart of the Neo4j server is a regular Neo4j storage engine instance That engine can be tunedin the same way as the other embedded configurations using the same file format The only differenceis that the server must be told where to find the fine-tuning configuration
Quick info
bull The neo4jproperties file is a standard configuration file that databases load in order to tunetheir memory use and caching strategies
bull See Section 21 ldquoCaches in Neo4jrdquo for more information
571 Specifying Neo4j tuning propertiesThe confneo4j-serverproperties file in the server distribution is the main configuration filefor the server In this file we can specify a second properties file that contains the database tuningsettings (that is the neo4jproperties file) This is done by setting a single property to point to avalid neo4jproperties file
orgneo4jserverdbtuningproperties=neo4jproperties file
On restarting the server the tuning enhancements specified in the neo4jproperties file will beloaded and configured into the underlying database engine
572 Specifying JVM tuning propertiesTuning the standalone server is achieved by editing the neo4j-wrapperconf file in the confdirectory of NEO4J_HOME
Edit the following properties
Table 51 neo4j-wrapperconf JVM tuning properties
Property Name Meaning
wrapper java initmemory initial heap size (in MB)
wrapper java maxmemory maximum heap size (in MB)
wrapper java additional N additional literal JVM parameter where N is anumber for each
For more information on the tuning properties see Section 22 ldquoJVM Settingsrdquo
Neo4j Server
58
58 Unmanaged Extensions
Quick info
bull Danger Men at Work The unmanaged extensions are a way of deploying arbitrary JAX-RS code into the Neo4j server
bull The unmanaged extensions are exactly that unmanaged If you drop poorly tested code intothe server itrsquos highly likely yoursquoll degrade its performance so be careful
Some projects want extremely fine control over their server-side code For this wersquove introduced anunmanaged extension API
WarningThis is a sharp tool allowing users to deploy arbitrary JAX-RS lthttpenwikipediaorgwikiJAX-RSgt classes to the server and so you should be careful when thinking aboutusing this In particular you should understand that itrsquos easy to consume lots of heap spaceon the server and hinder performance if yoursquore not careful
Still if you understand the disclaimer then you load your JAX-RS classes into the Neo4j serversimply by adding adding a Context annotation to your code compiling against the JAX-RS jar andany Neo4j jars yoursquore making use of Then add your classes to the runtime classpath (just drop it inthe lib directory of the Neo4j server) In return you get access to the hosted environment of the Neo4jserver like logging through the orgneo4jserverloggingLogger
In your code you get access to the underlying GraphDatabaseService through the Contextannotation like so
public MyCoolService(Context GraphDatabaseService database)
Have fun here but be safe
Remember the unmanaged API is a very sharp tool Itrsquos all to easy to compromise the server bydeploying code this way so think first and see if you canrsquot use the managed extensions in preferenceHowever a number of context parameters can be automatically provided for you like the reference tothe database
In order to specify the mount point of your extension a full class looks like this
Unmanaged extension example
Path( helloworld )
public class HelloWorldResource
private final GraphDatabaseService database
public HelloWorldResource( Context GraphDatabaseService database )
thisdatabase = database
GET
Produces( MediaTypeTEXT_PLAIN )
Path( nodeId )
public Response hello( PathParam( nodeId ) long nodeId )
Neo4j Server
59
Do stuff with the database
return Responsestatus( StatusOK )entity(
( Hello World nodeId= + nodeId )getBytes() )build()
Build this code and place the resulting jar file (and any custom dependencies) into the$NEO4J_SERVER_HOMEplugins directory and include this class in the neo4j-serverpropertiesfile like so
Comma separated list of JAXRS packages containing JAXRS Resource one package name for each mountpoint
orgneo4jserverthirdparty_jaxrs_classes=orgneo4jexamplesserverunmanaged=examplesunmanaged
Which binds the hello method to respond to GET requests at the URI httpneo4j_serverneo4j_portexamplesunmanagedhelloworldnodeId
curl httplocalhost7474examplesunmanagedhelloworld123
which results in
Hello World nodeId=123
60
Chapter 6 REST API
The Neo4j REST API is designed with discoverability in mind so that you can start with a GET onthe Section 61 ldquoService rootrdquo and from there discover URIs to perform other requests The examplesbelow uses URIs in the examples they are subject to change in the future so for future-proofnessdiscover URIs where possible instead of relying on the current layout The default representation isjson lthttpwwwjsonorggt both for responses and for data sent with POSTPUT requests
Below follows a listing of ways to interact with the REST API You can also see a (at runtime)generated description of the API be pointing your browser to the (exact URI may vary) httplocalhost7474dbdataapplicationwadl
To interact with the JSON interface you must explicitly set the request header Acceptapplicationjson for those requests that responds with data You should also set the header Content-Typeapplicationjson if your request sends data for example when yoursquore creating a relationshipThe examples include the relevant request and response headers
REST API
61
61 Service root
611 Get service rootThe service root is your starting point to discover the REST API
Example request
bull GET httplocalhost7474dbdata
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
relationship_index httplocalhost7474dbdataindexrelationship
node httplocalhost7474dbdatanode
relationship_types httplocalhost7474dbdatarelationshiptypes
extensions_info httplocalhost7474dbdataext
node_index httplocalhost7474dbdataindexnode
reference_node httplocalhost7474dbdatanode0
extensions
FunctionalTestPlugin
methodWithArray httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithArray
methodWithIntArray httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithIntArray
methodWithIntParam httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithIntParam
reference_node_uri httplocalhost7474dbdataextFunctionalTestPlugingraphdbreference_node_uri
methodWithSet httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithSet
methodWithOptionalArray httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithOptionalArray
methodWithListAndInt httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithListAndInt
methodWithList httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithList
methodWithAllParams httplocalhost7474dbdataextFunctionalTestPlugingraphdbmethodWithAllParams
REST API
62
62 Nodes
621 Create nodeExample request
bull POST httplocalhost7474dbdatanode
bull Accept applicationjson
Example response
bull 201 Created
bull Content-Type applicationjson
bull Location httplocalhost7474dbdatanode1
outgoing_relationships httplocalhost7474dbdatanode1relationshipsout
data
traverse httplocalhost7474dbdatanode1traversereturnType
all_typed_relationships httplocalhost7474dbdatanode1relationshipsall-list|amp|types
property httplocalhost7474dbdatanode1propertieskey
self httplocalhost7474dbdatanode1
outgoing_typed_relationships httplocalhost7474dbdatanode1relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode1properties
incoming_relationships httplocalhost7474dbdatanode1relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode1connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode1pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode1getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode1createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode1getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode1clonedSubgraph
create_relationship httplocalhost7474dbdatanode1relationships
paged_traverse httplocalhost7474dbdatanode1pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode1relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode1relationshipsin-list|amp|types
622 Create node with propertiesExample request
bull POST httplocalhost7474dbdatanode
bull Accept applicationjson
bull Content-Type applicationjson
foo bar
Example response
bull 201 Created
bull Content-Length 1819
REST API
63
bull Content-Type applicationjson
bull Location httplocalhost7474dbdatanode2
outgoing_relationships httplocalhost7474dbdatanode2relationshipsout
data
foo bar
traverse httplocalhost7474dbdatanode2traversereturnType
all_typed_relationships httplocalhost7474dbdatanode2relationshipsall-list|amp|types
property httplocalhost7474dbdatanode2propertieskey
self httplocalhost7474dbdatanode2
outgoing_typed_relationships httplocalhost7474dbdatanode2relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode2properties
incoming_relationships httplocalhost7474dbdatanode2relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode2connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode2pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode2getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode2createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode2getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode2clonedSubgraph
create_relationship httplocalhost7474dbdatanode2relationships
paged_traverse httplocalhost7474dbdatanode2pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode2relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode2relationshipsin-list|amp|types
623 Get nodeNote that the response contains URItemplates for the available operations for getting properties andrelationships
Example request
bull GET httplocalhost7474dbdatanode1
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
outgoing_relationships httplocalhost7474dbdatanode1relationshipsout
data
traverse httplocalhost7474dbdatanode1traversereturnType
all_typed_relationships httplocalhost7474dbdatanode1relationshipsall-list|amp|types
property httplocalhost7474dbdatanode1propertieskey
self httplocalhost7474dbdatanode1
outgoing_typed_relationships httplocalhost7474dbdatanode1relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode1properties
incoming_relationships httplocalhost7474dbdatanode1relationshipsin
extensions
FunctionalTestPlugin
REST API
64
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode1connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode1pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode1getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode1createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode1getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode1clonedSubgraph
create_relationship httplocalhost7474dbdatanode1relationships
paged_traverse httplocalhost7474dbdatanode1pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode1relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode1relationshipsin-list|amp|types
624 Get non-existent nodeExample request
bull GET httplocalhost7474dbdatanode600000
bull Accept applicationjson
Example response
bull 404 Not Found
bull Content-Type applicationjson
message Cannot find node with id [600000] in database
exception orgneo4jserverrestwebNodeNotFoundException Cannot find node with id [600000] in database
stacktrace [ orgneo4jserverrestwebDatabaseActionsnode(DatabaseActionsjava98) orgneo4jserverrestwebDatabaseActionsgetNode(DatabaseActionsjava194) orgneo4jserverrestwebRestfulGraphDatabasegetNode(RestfulGraphDatabasejava185) sunreflectNativeMethodAccessorImplinvoke0(Native Method) sunreflectNativeMethodAccessorImplinvoke(NativeMethodAccessorImpljava39) sunreflectDelegatingMethodAccessorImplinvoke(DelegatingMethodAccessorImpljava25) javalangreflectMethodinvoke(Methodjava597) comsunjerseyserverimplmodelmethoddispatchAbstractResourceMethodDispatchProvider$ResponseOutInvoker_dispatch(AbstractResourceMethodDispatchProviderjava184) comsunjerseyserverimplmodelmethoddispatchResourceJavaMethodDispatcherdispatch(ResourceJavaMethodDispatcherjava67) comsunjerseyserverimplurirulesHttpMethodRuleaccept(HttpMethodRulejava276) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesResourceClassRuleaccept(ResourceClassRulejava83) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesRootResourceClassesRuleaccept(RootResourceClassesRulejava71) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1171) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1103) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1053) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1043) comsunjerseyspicontainerservletWebComponentservice(WebComponentjava406) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava477) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava662) javaxservlethttpHttpServletservice(HttpServletjava820) orgmortbayjettyservletServletHolderhandle(ServletHolderjava511) orgmortbayjettyservletServletHandlerhandle(ServletHandlerjava390) orgmortbayjettyservletSessionHandlerhandle(SessionHandlerjava182) orgmortbayjettyhandlerContextHandlerhandle(ContextHandlerjava765) orgmortbayjettyhandlerHandlerCollectionhandle(HandlerCollectionjava114) orgmortbayjettyhandlerHandlerWrapperhandle(HandlerWrapperjava152) orgmortbayjettyServerhandle(Serverjava326) orgmortbayjettyHttpConnectionhandleRequest(HttpConnectionjava542) orgmortbayjettyHttpConnection$RequestHandlerheaderComplete(HttpConnectionjava926) orgmortbayjettyHttpParserparseNext(HttpParserjava549) orgmortbayjettyHttpParserparseAvailable(HttpParserjava212) orgmortbayjettyHttpConnectionhandle(HttpConnectionjava404) orgmortbayjettybioSocketConnector$Connectionrun(SocketConnectorjava228) orgmortbaythreadQueuedThreadPool$PoolThreadrun(QueuedThreadPooljava582) ]
625 Delete nodeExample request
bull DELETE httplocalhost7474dbdatanode9
bull Accept applicationjson
Example response
bull 204 No Content
626 Nodes with relationships can not be deletedThe relationships on a node has to be deleted before the node can be deleted
Example request
bull DELETE httplocalhost7474dbdatanode10
bull Accept applicationjson
Example response
bull 409 Conflict
bull Content-Type applicationjson
REST API
65
message The node with id 10 cannot be deleted Check that the node is orphaned before deletion
exception orgneo4jserverrestwebOperationFailureException The node with id 10 cannot be deleted Check that the node is orphaned before deletion
stacktrace [ orgneo4jserverrestwebDatabaseActionsdeleteNode(DatabaseActionsjava214) orgneo4jserverrestwebRestfulGraphDatabasedeleteNode(RestfulGraphDatabasejava199) sunreflectNativeMethodAccessorImplinvoke0(Native Method) sunreflectNativeMethodAccessorImplinvoke(NativeMethodAccessorImpljava39) sunreflectDelegatingMethodAccessorImplinvoke(DelegatingMethodAccessorImpljava25) javalangreflectMethodinvoke(Methodjava597) comsunjerseyserverimplmodelmethoddispatchAbstractResourceMethodDispatchProvider$ResponseOutInvoker_dispatch(AbstractResourceMethodDispatchProviderjava184) comsunjerseyserverimplmodelmethoddispatchResourceJavaMethodDispatcherdispatch(ResourceJavaMethodDispatcherjava67) comsunjerseyserverimplurirulesHttpMethodRuleaccept(HttpMethodRulejava276) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesResourceClassRuleaccept(ResourceClassRulejava83) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesRootResourceClassesRuleaccept(RootResourceClassesRulejava71) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1171) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1103) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1053) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1043) comsunjerseyspicontainerservletWebComponentservice(WebComponentjava406) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava477) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava662) javaxservlethttpHttpServletservice(HttpServletjava820) orgmortbayjettyservletServletHolderhandle(ServletHolderjava511) orgmortbayjettyservletServletHandlerhandle(ServletHandlerjava390) orgmortbayjettyservletSessionHandlerhandle(SessionHandlerjava182) orgmortbayjettyhandlerContextHandlerhandle(ContextHandlerjava765) orgmortbayjettyhandlerHandlerCollectionhandle(HandlerCollectionjava114) orgmortbayjettyhandlerHandlerWrapperhandle(HandlerWrapperjava152) orgmortbayjettyServerhandle(Serverjava326) orgmortbayjettyHttpConnectionhandleRequest(HttpConnectionjava542) orgmortbayjettyHttpConnection$RequestHandlerheaderComplete(HttpConnectionjava926) orgmortbayjettyHttpParserparseNext(HttpParserjava549) orgmortbayjettyHttpParserparseAvailable(HttpParserjava212) orgmortbayjettyHttpConnectionhandle(HttpConnectionjava404) orgmortbayjettybioSocketConnector$Connectionrun(SocketConnectorjava228) orgmortbaythreadQueuedThreadPool$PoolThreadrun(QueuedThreadPooljava582) ]
REST API
66
63 RelationshipsThe general pattern to get relationships is
GET httplocalhost7474dbdatanode123relationshipsdir-list|amp|types
Where dir is one of all in out and types is an ampersand-separated list of types See the examplesbelow for more information
631 Create relationshipExample request
bull POST httplocalhost7474dbdatanode3relationships
bull Accept applicationjson
bull Content-Type applicationjson
to httplocalhost7474dbdatanode4 type LOVES
Example response
bull 201 Created
bull Content-Type applicationjson
bull Location httplocalhost7474dbdatarelationship2
start httplocalhost7474dbdatanode3
data
self httplocalhost7474dbdatarelationship2
property httplocalhost7474dbdatarelationship2propertieskey
properties httplocalhost7474dbdatarelationship2properties
type LOVES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship2methodOnRelationship
end httplocalhost7474dbdatanode4
632 Get all relationshipsExample request
bull GET httplocalhost7474dbdatanode6relationshipsall
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
[
start httplocalhost7474dbdatanode6
data
self httplocalhost7474dbdatarelationship3
REST API
67
property httplocalhost7474dbdatarelationship3propertieskey
properties httplocalhost7474dbdatarelationship3properties
type LIKES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship3methodOnRelationship
end httplocalhost7474dbdatanode7
start httplocalhost7474dbdatanode8
data
self httplocalhost7474dbdatarelationship4
property httplocalhost7474dbdatarelationship4propertieskey
properties httplocalhost7474dbdatarelationship4properties
type LIKES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship4methodOnRelationship
end httplocalhost7474dbdatanode6
start httplocalhost7474dbdatanode6
data
self httplocalhost7474dbdatarelationship5
property httplocalhost7474dbdatarelationship5propertieskey
properties httplocalhost7474dbdatarelationship5properties
type HATES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship5methodOnRelationship
end httplocalhost7474dbdatanode9
]
633 Get incoming relationshipsExample request
bull GET httplocalhost7474dbdatanode11relationshipsin
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
[
start httplocalhost7474dbdatanode13
data
self httplocalhost7474dbdatarelationship7
property httplocalhost7474dbdatarelationship7propertieskey
properties httplocalhost7474dbdatarelationship7properties
type LIKES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship7methodOnRelationship
REST API
68
end httplocalhost7474dbdatanode11
]
634 Get outgoing relationshipsExample request
bull GET httplocalhost7474dbdatanode16relationshipsout
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
[
start httplocalhost7474dbdatanode16
data
self httplocalhost7474dbdatarelationship9
property httplocalhost7474dbdatarelationship9propertieskey
properties httplocalhost7474dbdatarelationship9properties
type LIKES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship9methodOnRelationship
end httplocalhost7474dbdatanode17
start httplocalhost7474dbdatanode16
data
self httplocalhost7474dbdatarelationship11
property httplocalhost7474dbdatarelationship11propertieskey
properties httplocalhost7474dbdatarelationship11properties
type HATES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship11methodOnRelationship
end httplocalhost7474dbdatanode19
]
635 Get typed relationshipsNote that the amp needs to be escaped for example when using cURL lthttpcurlhaxxsegt from theterminal
Example request
bull GET httplocalhost7474dbdatanode21relationshipsallLIKESampHATES
bull Accept applicationjson
Example response
bull 200 OK
REST API
69
bull Content-Type applicationjson
[
start httplocalhost7474dbdatanode21
data
self httplocalhost7474dbdatarelationship12
property httplocalhost7474dbdatarelationship12propertieskey
properties httplocalhost7474dbdatarelationship12properties
type LIKES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship12methodOnRelationship
end httplocalhost7474dbdatanode22
start httplocalhost7474dbdatanode23
data
self httplocalhost7474dbdatarelationship13
property httplocalhost7474dbdatarelationship13propertieskey
properties httplocalhost7474dbdatarelationship13properties
type LIKES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship13methodOnRelationship
end httplocalhost7474dbdatanode21
start httplocalhost7474dbdatanode21
data
self httplocalhost7474dbdatarelationship14
property httplocalhost7474dbdatarelationship14propertieskey
properties httplocalhost7474dbdatarelationship14properties
type HATES
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship14methodOnRelationship
end httplocalhost7474dbdatanode24
]
636 Get relationships on a node without relationshipsExample request
bull GET httplocalhost7474dbdatanode40relationshipsall
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
[ ]
REST API
70
64 Relationship types
641 Get relationship typesExample request
bull GET httplocalhost7474dbdatarelationshiptypes
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
[foobar]
REST API
71
65 Node properties
651 Set property on nodeExample request
bull PUT httplocalhost7474dbdatanode5propertiesfoo
bull Accept applicationjson
bull Content-Type applicationjson
bar
Example response
bull 204 No Content
652 Update node propertiesExample request
bull PUT httplocalhost7474dbdatanode1properties
bull Accept applicationjson
bull Content-Type applicationjson
jim tobias
Example response
bull 204 No Content
653 Get properties for nodeExample request
bull GET httplocalhost7474dbdatanode5properties
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
foo bar
654 Get properties for node (empty result)If there are no properties there will be an HTTP 204 response
Example request
bull GET httplocalhost7474dbdatanode1properties
bull Accept applicationjson
REST API
72
Example response
bull 204 No Content
655 Property values can not be nullThis example shows the response you get when trying to set a property to null
Example request
bull POST httplocalhost7474dbdatanodebull Accept applicationjsonbull Content-Type applicationjson
foonull
Example response
bull 400 Bad Requestbull Content-Type applicationjson
message Could not set property foo unsupported type null
exception orgneo4jserverrestwebPropertyValueException Could not set property foo unsupported type null
stacktrace [ orgneo4jserverrestwebDatabaseActionsset(DatabaseActionsjava127) orgneo4jserverrestwebDatabaseActionscreateNode(DatabaseActionsjava182) orgneo4jserverrestwebRestfulGraphDatabasecreateNode(RestfulGraphDatabasejava159) sunreflectNativeMethodAccessorImplinvoke0(Native Method) sunreflectNativeMethodAccessorImplinvoke(NativeMethodAccessorImpljava39) sunreflectDelegatingMethodAccessorImplinvoke(DelegatingMethodAccessorImpljava25) javalangreflectMethodinvoke(Methodjava597) comsunjerseyserverimplmodelmethoddispatchAbstractResourceMethodDispatchProvider$ResponseOutInvoker_dispatch(AbstractResourceMethodDispatchProviderjava184) comsunjerseyserverimplmodelmethoddispatchResourceJavaMethodDispatcherdispatch(ResourceJavaMethodDispatcherjava67) comsunjerseyserverimplurirulesHttpMethodRuleaccept(HttpMethodRulejava276) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesResourceClassRuleaccept(ResourceClassRulejava83) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesRootResourceClassesRuleaccept(RootResourceClassesRulejava71) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1171) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1103) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1053) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1043) comsunjerseyspicontainerservletWebComponentservice(WebComponentjava406) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava477) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava662) javaxservlethttpHttpServletservice(HttpServletjava820) orgmortbayjettyservletServletHolderhandle(ServletHolderjava511) orgmortbayjettyservletServletHandlerhandle(ServletHandlerjava390) orgmortbayjettyservletSessionHandlerhandle(SessionHandlerjava182) orgmortbayjettyhandlerContextHandlerhandle(ContextHandlerjava765) orgmortbayjettyhandlerHandlerCollectionhandle(HandlerCollectionjava114) orgmortbayjettyhandlerHandlerWrapperhandle(HandlerWrapperjava152) orgmortbayjettyServerhandle(Serverjava326) orgmortbayjettyHttpConnectionhandleRequest(HttpConnectionjava542) orgmortbayjettyHttpConnection$RequestHandlercontent(HttpConnectionjava943) orgmortbayjettyHttpParserparseNext(HttpParserjava756) orgmortbayjettyHttpParserparseAvailable(HttpParserjava212) orgmortbayjettyHttpConnectionhandle(HttpConnectionjava404) orgmortbayjettybioSocketConnector$Connectionrun(SocketConnectorjava228) orgmortbaythreadQueuedThreadPool$PoolThreadrun(QueuedThreadPooljava582) ]
656 Property values can not be nestedNesting properties is not supported You could for example store the nested json as a string instead
Example request
bull POST httplocalhost7474dbdatanodebull Accept applicationjsonbull Content-Type applicationjson
foo bar baz
Example response
bull 400 Bad Requestbull Content-Type applicationjson
message Could not set property foo unsupported type bar=baz
exception orgneo4jserverrestwebPropertyValueException Could not set property foo unsupported type bar=baz
stacktrace [ orgneo4jserverrestwebDatabaseActionsset(DatabaseActionsjava127) orgneo4jserverrestwebDatabaseActionscreateNode(DatabaseActionsjava182) orgneo4jserverrestwebRestfulGraphDatabasecreateNode(RestfulGraphDatabasejava159) sunreflectNativeMethodAccessorImplinvoke0(Native Method) sunreflectNativeMethodAccessorImplinvoke(NativeMethodAccessorImpljava39) sunreflectDelegatingMethodAccessorImplinvoke(DelegatingMethodAccessorImpljava25) javalangreflectMethodinvoke(Methodjava597) comsunjerseyserverimplmodelmethoddispatchAbstractResourceMethodDispatchProvider$ResponseOutInvoker_dispatch(AbstractResourceMethodDispatchProviderjava184) comsunjerseyserverimplmodelmethoddispatchResourceJavaMethodDispatcherdispatch(ResourceJavaMethodDispatcherjava67) comsunjerseyserverimplurirulesHttpMethodRuleaccept(HttpMethodRulejava276) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesResourceClassRuleaccept(ResourceClassRulejava83) comsunjerseyserverimplurirulesRightHandPathRuleaccept(RightHandPathRulejava133) comsunjerseyserverimplurirulesRootResourceClassesRuleaccept(RootResourceClassesRulejava71) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1171) comsunjerseyserverimplapplicationWebApplicationImpl_handleRequest(WebApplicationImpljava1103) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1053) comsunjerseyserverimplapplicationWebApplicationImplhandleRequest(WebApplicationImpljava1043) comsunjerseyspicontainerservletWebComponentservice(WebComponentjava406) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava477) comsunjerseyspicontainerservletServletContainerservice(ServletContainerjava662) javaxservlethttpHttpServletservice(HttpServletjava820) orgmortbayjettyservletServletHolderhandle(ServletHolderjava511) orgmortbayjettyservletServletHandlerhandle(ServletHandlerjava390) orgmortbayjettyservletSessionHandlerhandle(SessionHandlerjava182) orgmortbayjettyhandlerContextHandlerhandle(ContextHandlerjava765) orgmortbayjettyhandlerHandlerCollectionhandle(HandlerCollectionjava114) orgmortbayjettyhandlerHandlerWrapperhandle(HandlerWrapperjava152) orgmortbayjettyServerhandle(Serverjava326) orgmortbayjettyHttpConnectionhandleRequest(HttpConnectionjava542) orgmortbayjettyHttpConnection$RequestHandlercontent(HttpConnectionjava943) orgmortbayjettyHttpParserparseNext(HttpParserjava756) orgmortbayjettyHttpParserparseAvailable(HttpParserjava212) orgmortbayjettyHttpConnectionhandle(HttpConnectionjava404) orgmortbayjettybioSocketConnector$Connectionrun(SocketConnectorjava228) orgmortbaythreadQueuedThreadPool$PoolThreadrun(QueuedThreadPooljava582) ]
657 Delete all properties from nodeExample request
bull DELETE httplocalhost7474dbdatanode2propertiesbull Accept applicationjson
Example response
REST API
73
bull 204 No Content
REST API
74
66 Relationship properties
661 Update relationship propertiesExample request
bull PUT httplocalhost7474dbdatarelationship0properties
bull Accept applicationjson
bull Content-Type applicationjson
jim tobias
Example response
bull 204 No Content
REST API
75
67 IndexesAn index can contain either nodes or relationships
NoteTo create an index with default configuration simply start using it by adding nodesrelationships to it It will then be automatically created for you
What default configuration means depends on how you have configured your database If you havenrsquotchanged any indexing configuration it means the indexes will be using a Lucene-based backend
If you want to customize the index settings see Section 672 ldquoCreate node index with configurationrdquo
671 Create node index
NoteInstead of creating the index this way you can simply start to use it and it will be createdautomatically
Example request
bull POST httplocalhost7474dbdataindexnode
bull Accept applicationjson
bull Content-Type applicationjson
name favorites
Example response
bull 201 Created
bull Content-Type applicationjson
bull Location httplocalhost7474dbdataindexnodefavorites
template httplocalhost7474dbdataindexnodefavoriteskeyvalue
672 Create node index with configurationThis request is only necessary if you want to customize the index settings If you are happy with thedefaults you can just start indexing nodesrelationships as non-existent indexes will automaticallybe created as you do See Section 710 ldquoConfiguration and fulltext indexesrdquo for more information onindex configuration
Example request
bull POST httplocalhost7474dbdataindexnode
bull Accept applicationjson
bull Content-Type applicationjson
namefulltext configtypefulltextproviderlucene
Example response
REST API
76
bull 201 Created
bull Content-Type applicationjson
bull Location httplocalhost7474dbdataindexnodefulltext
template httplocalhost7474dbdataindexnodefulltextkeyvalue
provider lucene
type fulltext
673 Delete node indexExample request
bull DELETE httplocalhost7474dbdataindexnodekvnode
bull Accept applicationjson
Example response
bull 204 No Content
674 List node indexeshellip
GET $orgneo4jserverrestwebindexnode
throws PropertyValueException
Example request
bull GET httplocalhost7474dbdataindexnode
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
favorites
template httplocalhost7474dbdataindexnodefavoriteskeyvalue
provider lucene
type exact
675 List node indexes (empty result)This is an example covering the case where no node index exists
Example request
bull GET httplocalhost7474dbdataindexnode
bull Accept applicationjson
Example response
REST API
77
bull 204 No Content
676 Add node to indexAssociates a node with the given keyvalue pair in the given index
NoteSpaces in the URI have to be escaped
CautionThis does not overwrite previous entries If you index the same keyvalueitemcombination twice two index entries are created To do update-type operations you needto delete the old entry before adding a new one
Example request
bull POST httplocalhost7474dbdataindexnodefavoriteskeythe20value
bull Accept applicationjson
bull Content-Type applicationjson
httplocalhost7474dbdatanode0
Example response
bull 201 Created
bull Content-Type applicationjson
bull Location httplocalhost7474dbdataindexnodefavoriteskeythe20value0
indexed httplocalhost7474dbdataindexnodefavoriteskeythe20value0
outgoing_relationships httplocalhost7474dbdatanode0relationshipsout
data
traverse httplocalhost7474dbdatanode0traversereturnType
all_typed_relationships httplocalhost7474dbdatanode0relationshipsall-list|amp|types
property httplocalhost7474dbdatanode0propertieskey
self httplocalhost7474dbdatanode0
outgoing_typed_relationships httplocalhost7474dbdatanode0relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode0properties
incoming_relationships httplocalhost7474dbdatanode0relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode0connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode0pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode0getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode0createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode0getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode0clonedSubgraph
create_relationship httplocalhost7474dbdatanode0relationships
paged_traverse httplocalhost7474dbdatanode0pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode0relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode0relationshipsin-list|amp|types
REST API
78
677 Find node by exact match
NoteSpaces in the URI have to be escaped
Example request
bull GET httplocalhost7474dbdataindexnodefavoriteskeythe20value
bull Accept applicationjson
Example response
bull 200 OK
bull Content-Type applicationjson
[
indexed httplocalhost7474dbdataindexnodefavoriteskeythe20value0
outgoing_relationships httplocalhost7474dbdatanode0relationshipsout
data
traverse httplocalhost7474dbdatanode0traversereturnType
all_typed_relationships httplocalhost7474dbdatanode0relationshipsall-list|amp|types
property httplocalhost7474dbdatanode0propertieskey
self httplocalhost7474dbdatanode0
outgoing_typed_relationships httplocalhost7474dbdatanode0relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode0properties
incoming_relationships httplocalhost7474dbdatanode0relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode0connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode0pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode0getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode0createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode0getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode0clonedSubgraph
create_relationship httplocalhost7474dbdatanode0relationships
paged_traverse httplocalhost7474dbdatanode0pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode0relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode0relationshipsin-list|amp|types
]
REST API
79
68 TraversalsTraversals are performed from a start node The traversal is controlled by the URI and the body sentwith the request
responseTypeThe kind of objects in the response is determined by traversereturnType in the URLreturnType can have one of these valuesbull node
bull relationship
bull path
bull fullpath
To decide how the graph should be traversed you can use these parameters in the request body
orderDecides in which order to visit nodes Possible valuesbull breadth_first
bull depth_first
relationshipsDecides which relationship types and directions should be followed The direction can be one ofbull all
bull in
bull out
uniquenessDecides how uniqueness should be calculated Possible valuesbull node_global
bull none
bull relationship_global
bull node_path
bull relationship_path
prune_evaluatorDecides whether the traverser should continue down that path or if it should be pruned so that thetraverser wonrsquot continue down that path You can write your own prune evaluator or use the built-in none prune evaluator
return filterDecides whether the current position should be included in the result You can provide your owncode for this or use one of the built-in filtersbull all
bull all_but_start_node
max_depthIs a short-hand way of specifying a prune evaluator which prunes after a certain depth If notspecified a max depth of 1 is used and if a prune evaluator is specified instead of a max depthno max depth limit is set
The position object in the body of the return filter and prune evaluator is a Path lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbPathhtmlgt objectrepresenting the path from the start node to the current traversal position
REST API
80
Out of the box the REST API supports JavaScript code in filtersevaluators See the examples for theexact syntax of the request
681 Traversal using a return filterIn this example the none prune evaluator is used and a return filter is supplied The result is to bereturned as nodes and the max depth is set to 3
Example request
bull POST httplocalhost7474dbdatanode20traversenodebull Accept applicationjsonbull Content-Type applicationjson
order breadth_first
return_filter
body positionendNode()getProperty(name)toLowerCase()contains(t)
language javascript
prune_evaluator
name none
language builtin
uniqueness node_global
max depth 3
relationships [
direction all
type knows
direction all
type loves
]
Example response
bull 200 OKbull Content-Type applicationjson
[
outgoing_relationships httplocalhost7474dbdatanode20relationshipsout
data
name Root
traverse httplocalhost7474dbdatanode20traversereturnType
all_typed_relationships httplocalhost7474dbdatanode20relationshipsall-list|amp|types
property httplocalhost7474dbdatanode20propertieskey
self httplocalhost7474dbdatanode20
outgoing_typed_relationships httplocalhost7474dbdatanode20relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode20properties
incoming_relationships httplocalhost7474dbdatanode20relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode20connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode20pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode20getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode20createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode20getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode20clonedSubgraph
REST API
81
create_relationship httplocalhost7474dbdatanode20relationships
paged_traverse httplocalhost7474dbdatanode20pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode20relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode20relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode21relationshipsout
data
name Mattias
traverse httplocalhost7474dbdatanode21traversereturnType
all_typed_relationships httplocalhost7474dbdatanode21relationshipsall-list|amp|types
property httplocalhost7474dbdatanode21propertieskey
self httplocalhost7474dbdatanode21
outgoing_typed_relationships httplocalhost7474dbdatanode21relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode21properties
incoming_relationships httplocalhost7474dbdatanode21relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode21connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode21pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode21getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode21createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode21getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode21clonedSubgraph
create_relationship httplocalhost7474dbdatanode21relationships
paged_traverse httplocalhost7474dbdatanode21pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode21relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode21relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode24relationshipsout
data
name Peter
traverse httplocalhost7474dbdatanode24traversereturnType
all_typed_relationships httplocalhost7474dbdatanode24relationshipsall-list|amp|types
property httplocalhost7474dbdatanode24propertieskey
self httplocalhost7474dbdatanode24
outgoing_typed_relationships httplocalhost7474dbdatanode24relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode24properties
incoming_relationships httplocalhost7474dbdatanode24relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode24connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode24pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode24getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode24createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode24getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode24clonedSubgraph
create_relationship httplocalhost7474dbdatanode24relationships
paged_traverse httplocalhost7474dbdatanode24pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode24relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode24relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode25relationshipsout
data
name Tobias
REST API
82
traverse httplocalhost7474dbdatanode25traversereturnType
all_typed_relationships httplocalhost7474dbdatanode25relationshipsall-list|amp|types
property httplocalhost7474dbdatanode25propertieskey
self httplocalhost7474dbdatanode25
outgoing_typed_relationships httplocalhost7474dbdatanode25relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode25properties
incoming_relationships httplocalhost7474dbdatanode25relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode25connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode25pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode25getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode25createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode25getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode25clonedSubgraph
create_relationship httplocalhost7474dbdatanode25relationships
paged_traverse httplocalhost7474dbdatanode25pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode25relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode25relationshipsin-list|amp|types
]
682 Creating a paged traverserPaged traversers are created by POST-ing a traversal description to the link identified by thepaged_traverser key in a node representation When creating a paged traverser the same optionsapply as for a regular traverser meaning that node path or fullpath can be targeted
Example request
bull POST httplocalhost7474dbdatanode34pagedtraversenodebull Accept applicationjsonbull Content-Type applicationjson
prune_evaluatorlanguagebuiltinnamenonereturn_filterlanguagejavascriptbodypositionendNode()getProperty(name)contains(1)orderdepth_firstrelationshipstypeNEXTdirectionout
Example response
bull 201 Createdbull Content-Type applicationjsonbull Location httplocalhost7474dbdatanode34pagedtraversenode2ee0eb9931bd40758c5254c6057ac119
[
outgoing_relationships httplocalhost7474dbdatanode35relationshipsout
data
name 1
traverse httplocalhost7474dbdatanode35traversereturnType
all_typed_relationships httplocalhost7474dbdatanode35relationshipsall-list|amp|types
property httplocalhost7474dbdatanode35propertieskey
self httplocalhost7474dbdatanode35
outgoing_typed_relationships httplocalhost7474dbdatanode35relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode35properties
incoming_relationships httplocalhost7474dbdatanode35relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode35connected_nodes
REST API
83
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode35pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode35getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode35createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode35getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode35clonedSubgraph
create_relationship httplocalhost7474dbdatanode35relationships
paged_traverse httplocalhost7474dbdatanode35pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode35relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode35relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode44relationshipsout
data
name 10
traverse httplocalhost7474dbdatanode44traversereturnType
all_typed_relationships httplocalhost7474dbdatanode44relationshipsall-list|amp|types
property httplocalhost7474dbdatanode44propertieskey
self httplocalhost7474dbdatanode44
outgoing_typed_relationships httplocalhost7474dbdatanode44relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode44properties
incoming_relationships httplocalhost7474dbdatanode44relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode44connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode44pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode44getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode44createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode44getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode44clonedSubgraph
create_relationship httplocalhost7474dbdatanode44relationships
paged_traverse httplocalhost7474dbdatanode44pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode44relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode44relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode45relationshipsout
data
name 11
traverse httplocalhost7474dbdatanode45traversereturnType
all_typed_relationships httplocalhost7474dbdatanode45relationshipsall-list|amp|types
property httplocalhost7474dbdatanode45propertieskey
self httplocalhost7474dbdatanode45
outgoing_typed_relationships httplocalhost7474dbdatanode45relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode45properties
incoming_relationships httplocalhost7474dbdatanode45relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode45connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode45pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode45getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode45createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode45getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode45clonedSubgraph
REST API
84
create_relationship httplocalhost7474dbdatanode45relationships
paged_traverse httplocalhost7474dbdatanode45pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode45relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode45relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode46relationshipsout
data
name 12
traverse httplocalhost7474dbdatanode46traversereturnType
all_typed_relationships httplocalhost7474dbdatanode46relationshipsall-list|amp|types
property httplocalhost7474dbdatanode46propertieskey
self httplocalhost7474dbdatanode46
outgoing_typed_relationships httplocalhost7474dbdatanode46relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode46properties
incoming_relationships httplocalhost7474dbdatanode46relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode46connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode46pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode46getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode46createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode46getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode46clonedSubgraph
create_relationship httplocalhost7474dbdatanode46relationships
paged_traverse httplocalhost7474dbdatanode46pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode46relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode46relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode47relationshipsout
data
name 13
traverse httplocalhost7474dbdatanode47traversereturnType
all_typed_relationships httplocalhost7474dbdatanode47relationshipsall-list|amp|types
property httplocalhost7474dbdatanode47propertieskey
self httplocalhost7474dbdatanode47
outgoing_typed_relationships httplocalhost7474dbdatanode47relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode47properties
incoming_relationships httplocalhost7474dbdatanode47relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode47connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode47pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode47getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode47createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode47getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode47clonedSubgraph
create_relationship httplocalhost7474dbdatanode47relationships
paged_traverse httplocalhost7474dbdatanode47pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode47relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode47relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode48relationshipsout
data
name 14
REST API
85
traverse httplocalhost7474dbdatanode48traversereturnType
all_typed_relationships httplocalhost7474dbdatanode48relationshipsall-list|amp|types
property httplocalhost7474dbdatanode48propertieskey
self httplocalhost7474dbdatanode48
outgoing_typed_relationships httplocalhost7474dbdatanode48relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode48properties
incoming_relationships httplocalhost7474dbdatanode48relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode48connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode48pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode48getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode48createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode48getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode48clonedSubgraph
create_relationship httplocalhost7474dbdatanode48relationships
paged_traverse httplocalhost7474dbdatanode48pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode48relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode48relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode49relationshipsout
data
name 15
traverse httplocalhost7474dbdatanode49traversereturnType
all_typed_relationships httplocalhost7474dbdatanode49relationshipsall-list|amp|types
property httplocalhost7474dbdatanode49propertieskey
self httplocalhost7474dbdatanode49
outgoing_typed_relationships httplocalhost7474dbdatanode49relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode49properties
incoming_relationships httplocalhost7474dbdatanode49relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode49connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode49pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode49getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode49createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode49getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode49clonedSubgraph
create_relationship httplocalhost7474dbdatanode49relationships
paged_traverse httplocalhost7474dbdatanode49pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode49relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode49relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode50relationshipsout
data
name 16
traverse httplocalhost7474dbdatanode50traversereturnType
all_typed_relationships httplocalhost7474dbdatanode50relationshipsall-list|amp|types
property httplocalhost7474dbdatanode50propertieskey
self httplocalhost7474dbdatanode50
outgoing_typed_relationships httplocalhost7474dbdatanode50relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode50properties
incoming_relationships httplocalhost7474dbdatanode50relationshipsin
extensions
FunctionalTestPlugin
REST API
86
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode50connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode50pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode50getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode50createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode50getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode50clonedSubgraph
create_relationship httplocalhost7474dbdatanode50relationships
paged_traverse httplocalhost7474dbdatanode50pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode50relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode50relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode51relationshipsout
data
name 17
traverse httplocalhost7474dbdatanode51traversereturnType
all_typed_relationships httplocalhost7474dbdatanode51relationshipsall-list|amp|types
property httplocalhost7474dbdatanode51propertieskey
self httplocalhost7474dbdatanode51
outgoing_typed_relationships httplocalhost7474dbdatanode51relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode51properties
incoming_relationships httplocalhost7474dbdatanode51relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode51connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode51pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode51getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode51createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode51getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode51clonedSubgraph
create_relationship httplocalhost7474dbdatanode51relationships
paged_traverse httplocalhost7474dbdatanode51pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode51relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode51relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode52relationshipsout
data
name 18
traverse httplocalhost7474dbdatanode52traversereturnType
all_typed_relationships httplocalhost7474dbdatanode52relationshipsall-list|amp|types
property httplocalhost7474dbdatanode52propertieskey
self httplocalhost7474dbdatanode52
outgoing_typed_relationships httplocalhost7474dbdatanode52relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode52properties
incoming_relationships httplocalhost7474dbdatanode52relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode52connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode52pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode52getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode52createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode52getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode52clonedSubgraph
REST API
87
create_relationship httplocalhost7474dbdatanode52relationships
paged_traverse httplocalhost7474dbdatanode52pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode52relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode52relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode53relationshipsout
data
name 19
traverse httplocalhost7474dbdatanode53traversereturnType
all_typed_relationships httplocalhost7474dbdatanode53relationshipsall-list|amp|types
property httplocalhost7474dbdatanode53propertieskey
self httplocalhost7474dbdatanode53
outgoing_typed_relationships httplocalhost7474dbdatanode53relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode53properties
incoming_relationships httplocalhost7474dbdatanode53relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode53connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode53pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode53getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode53createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode53getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode53clonedSubgraph
create_relationship httplocalhost7474dbdatanode53relationships
paged_traverse httplocalhost7474dbdatanode53pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode53relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode53relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode55relationshipsout
data
name 21
traverse httplocalhost7474dbdatanode55traversereturnType
all_typed_relationships httplocalhost7474dbdatanode55relationshipsall-list|amp|types
property httplocalhost7474dbdatanode55propertieskey
self httplocalhost7474dbdatanode55
outgoing_typed_relationships httplocalhost7474dbdatanode55relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode55properties
incoming_relationships httplocalhost7474dbdatanode55relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode55connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode55pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode55getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode55createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode55getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode55clonedSubgraph
create_relationship httplocalhost7474dbdatanode55relationships
paged_traverse httplocalhost7474dbdatanode55pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode55relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode55relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode65relationshipsout
data
name 31
REST API
88
traverse httplocalhost7474dbdatanode65traversereturnType
all_typed_relationships httplocalhost7474dbdatanode65relationshipsall-list|amp|types
property httplocalhost7474dbdatanode65propertieskey
self httplocalhost7474dbdatanode65
outgoing_typed_relationships httplocalhost7474dbdatanode65relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode65properties
incoming_relationships httplocalhost7474dbdatanode65relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode65connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode65pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode65getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode65createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode65getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode65clonedSubgraph
create_relationship httplocalhost7474dbdatanode65relationships
paged_traverse httplocalhost7474dbdatanode65pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode65relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode65relationshipsin-list|amp|types
]
683 Paging through the results of a paged traverserPaged traversers hold state on the server and allow clients to page through the results of a traversalTo progress to the next page of traversal results the client issues a HTTP GET request on the pagedtraversal URI which causes the traversal to fill the next page (or partially fill it if insufficient resultsare available)
Note that if a traverser expires through inactivity it will cause a 404 response on the next GET requestTraversers leases are renewed on every successful access for the same amount of time as originallyspecified
When the paged traverser reaches the end of its results the client can expect a 404 response as thetraverser is disposed by the server
Example request
bull GET httplocalhost7474dbdatanode67pagedtraversenodec61e65ec38764dfbb0117c1f6f894abf
bull Accept applicationjson
Example response
bull 200 OKbull Content-Type applicationjson
[
outgoing_relationships httplocalhost7474dbdatanode398relationshipsout
data
name 331
traverse httplocalhost7474dbdatanode398traversereturnType
all_typed_relationships httplocalhost7474dbdatanode398relationshipsall-list|amp|types
property httplocalhost7474dbdatanode398propertieskey
self httplocalhost7474dbdatanode398
outgoing_typed_relationships httplocalhost7474dbdatanode398relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode398properties
REST API
89
incoming_relationships httplocalhost7474dbdatanode398relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode398connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode398pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode398getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode398createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode398getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode398clonedSubgraph
create_relationship httplocalhost7474dbdatanode398relationships
paged_traverse httplocalhost7474dbdatanode398pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode398relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode398relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode408relationshipsout
data
name 341
traverse httplocalhost7474dbdatanode408traversereturnType
all_typed_relationships httplocalhost7474dbdatanode408relationshipsall-list|amp|types
property httplocalhost7474dbdatanode408propertieskey
self httplocalhost7474dbdatanode408
outgoing_typed_relationships httplocalhost7474dbdatanode408relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode408properties
incoming_relationships httplocalhost7474dbdatanode408relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode408connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode408pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode408getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode408createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode408getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode408clonedSubgraph
create_relationship httplocalhost7474dbdatanode408relationships
paged_traverse httplocalhost7474dbdatanode408pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode408relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode408relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode418relationshipsout
data
name 351
traverse httplocalhost7474dbdatanode418traversereturnType
all_typed_relationships httplocalhost7474dbdatanode418relationshipsall-list|amp|types
property httplocalhost7474dbdatanode418propertieskey
self httplocalhost7474dbdatanode418
outgoing_typed_relationships httplocalhost7474dbdatanode418relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode418properties
incoming_relationships httplocalhost7474dbdatanode418relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode418connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode418pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode418getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode418createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode418getRelationshipsBetween
REST API
90
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode418clonedSubgraph
create_relationship httplocalhost7474dbdatanode418relationships
paged_traverse httplocalhost7474dbdatanode418pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode418relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode418relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode428relationshipsout
data
name 361
traverse httplocalhost7474dbdatanode428traversereturnType
all_typed_relationships httplocalhost7474dbdatanode428relationshipsall-list|amp|types
property httplocalhost7474dbdatanode428propertieskey
self httplocalhost7474dbdatanode428
outgoing_typed_relationships httplocalhost7474dbdatanode428relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode428properties
incoming_relationships httplocalhost7474dbdatanode428relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode428connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode428pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode428getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode428createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode428getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode428clonedSubgraph
create_relationship httplocalhost7474dbdatanode428relationships
paged_traverse httplocalhost7474dbdatanode428pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode428relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode428relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode438relationshipsout
data
name 371
traverse httplocalhost7474dbdatanode438traversereturnType
all_typed_relationships httplocalhost7474dbdatanode438relationshipsall-list|amp|types
property httplocalhost7474dbdatanode438propertieskey
self httplocalhost7474dbdatanode438
outgoing_typed_relationships httplocalhost7474dbdatanode438relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode438properties
incoming_relationships httplocalhost7474dbdatanode438relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode438connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode438pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode438getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode438createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode438getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode438clonedSubgraph
create_relationship httplocalhost7474dbdatanode438relationships
paged_traverse httplocalhost7474dbdatanode438pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode438relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode438relationshipsin-list|amp|types
REST API
91
outgoing_relationships httplocalhost7474dbdatanode448relationshipsout
data
name 381
traverse httplocalhost7474dbdatanode448traversereturnType
all_typed_relationships httplocalhost7474dbdatanode448relationshipsall-list|amp|types
property httplocalhost7474dbdatanode448propertieskey
self httplocalhost7474dbdatanode448
outgoing_typed_relationships httplocalhost7474dbdatanode448relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode448properties
incoming_relationships httplocalhost7474dbdatanode448relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode448connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode448pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode448getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode448createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode448getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode448clonedSubgraph
create_relationship httplocalhost7474dbdatanode448relationships
paged_traverse httplocalhost7474dbdatanode448pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode448relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode448relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode458relationshipsout
data
name 391
traverse httplocalhost7474dbdatanode458traversereturnType
all_typed_relationships httplocalhost7474dbdatanode458relationshipsall-list|amp|types
property httplocalhost7474dbdatanode458propertieskey
self httplocalhost7474dbdatanode458
outgoing_typed_relationships httplocalhost7474dbdatanode458relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode458properties
incoming_relationships httplocalhost7474dbdatanode458relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode458connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode458pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode458getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode458createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode458getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode458clonedSubgraph
create_relationship httplocalhost7474dbdatanode458relationships
paged_traverse httplocalhost7474dbdatanode458pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode458relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode458relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode468relationshipsout
data
name 401
traverse httplocalhost7474dbdatanode468traversereturnType
all_typed_relationships httplocalhost7474dbdatanode468relationshipsall-list|amp|types
property httplocalhost7474dbdatanode468propertieskey
self httplocalhost7474dbdatanode468
outgoing_typed_relationships httplocalhost7474dbdatanode468relationshipsout-list|amp|types
REST API
92
properties httplocalhost7474dbdatanode468properties
incoming_relationships httplocalhost7474dbdatanode468relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode468connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode468pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode468getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode468createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode468getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode468clonedSubgraph
create_relationship httplocalhost7474dbdatanode468relationships
paged_traverse httplocalhost7474dbdatanode468pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode468relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode468relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode477relationshipsout
data
name 410
traverse httplocalhost7474dbdatanode477traversereturnType
all_typed_relationships httplocalhost7474dbdatanode477relationshipsall-list|amp|types
property httplocalhost7474dbdatanode477propertieskey
self httplocalhost7474dbdatanode477
outgoing_typed_relationships httplocalhost7474dbdatanode477relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode477properties
incoming_relationships httplocalhost7474dbdatanode477relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode477connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode477pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode477getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode477createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode477getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode477clonedSubgraph
create_relationship httplocalhost7474dbdatanode477relationships
paged_traverse httplocalhost7474dbdatanode477pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode477relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode477relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode478relationshipsout
data
name 411
traverse httplocalhost7474dbdatanode478traversereturnType
all_typed_relationships httplocalhost7474dbdatanode478relationshipsall-list|amp|types
property httplocalhost7474dbdatanode478propertieskey
self httplocalhost7474dbdatanode478
outgoing_typed_relationships httplocalhost7474dbdatanode478relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode478properties
incoming_relationships httplocalhost7474dbdatanode478relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode478connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode478pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode478getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode478createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode478getRelationshipsBetween
REST API
93
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode478clonedSubgraph
create_relationship httplocalhost7474dbdatanode478relationships
paged_traverse httplocalhost7474dbdatanode478pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode478relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode478relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode479relationshipsout
data
name 412
traverse httplocalhost7474dbdatanode479traversereturnType
all_typed_relationships httplocalhost7474dbdatanode479relationshipsall-list|amp|types
property httplocalhost7474dbdatanode479propertieskey
self httplocalhost7474dbdatanode479
outgoing_typed_relationships httplocalhost7474dbdatanode479relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode479properties
incoming_relationships httplocalhost7474dbdatanode479relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode479connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode479pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode479getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode479createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode479getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode479clonedSubgraph
create_relationship httplocalhost7474dbdatanode479relationships
paged_traverse httplocalhost7474dbdatanode479pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode479relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode479relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode480relationshipsout
data
name 413
traverse httplocalhost7474dbdatanode480traversereturnType
all_typed_relationships httplocalhost7474dbdatanode480relationshipsall-list|amp|types
property httplocalhost7474dbdatanode480propertieskey
self httplocalhost7474dbdatanode480
outgoing_typed_relationships httplocalhost7474dbdatanode480relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode480properties
incoming_relationships httplocalhost7474dbdatanode480relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode480connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode480pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode480getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode480createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode480getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode480clonedSubgraph
create_relationship httplocalhost7474dbdatanode480relationships
paged_traverse httplocalhost7474dbdatanode480pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode480relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode480relationshipsin-list|amp|types
REST API
94
outgoing_relationships httplocalhost7474dbdatanode481relationshipsout
data
name 414
traverse httplocalhost7474dbdatanode481traversereturnType
all_typed_relationships httplocalhost7474dbdatanode481relationshipsall-list|amp|types
property httplocalhost7474dbdatanode481propertieskey
self httplocalhost7474dbdatanode481
outgoing_typed_relationships httplocalhost7474dbdatanode481relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode481properties
incoming_relationships httplocalhost7474dbdatanode481relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode481connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode481pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode481getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode481createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode481getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode481clonedSubgraph
create_relationship httplocalhost7474dbdatanode481relationships
paged_traverse httplocalhost7474dbdatanode481pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode481relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode481relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode482relationshipsout
data
name 415
traverse httplocalhost7474dbdatanode482traversereturnType
all_typed_relationships httplocalhost7474dbdatanode482relationshipsall-list|amp|types
property httplocalhost7474dbdatanode482propertieskey
self httplocalhost7474dbdatanode482
outgoing_typed_relationships httplocalhost7474dbdatanode482relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode482properties
incoming_relationships httplocalhost7474dbdatanode482relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode482connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode482pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode482getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode482createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode482getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode482clonedSubgraph
create_relationship httplocalhost7474dbdatanode482relationships
paged_traverse httplocalhost7474dbdatanode482pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode482relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode482relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode483relationshipsout
data
name 416
traverse httplocalhost7474dbdatanode483traversereturnType
all_typed_relationships httplocalhost7474dbdatanode483relationshipsall-list|amp|types
property httplocalhost7474dbdatanode483propertieskey
self httplocalhost7474dbdatanode483
REST API
95
outgoing_typed_relationships httplocalhost7474dbdatanode483relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode483properties
incoming_relationships httplocalhost7474dbdatanode483relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode483connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode483pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode483getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode483createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode483getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode483clonedSubgraph
create_relationship httplocalhost7474dbdatanode483relationships
paged_traverse httplocalhost7474dbdatanode483pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode483relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode483relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode484relationshipsout
data
name 417
traverse httplocalhost7474dbdatanode484traversereturnType
all_typed_relationships httplocalhost7474dbdatanode484relationshipsall-list|amp|types
property httplocalhost7474dbdatanode484propertieskey
self httplocalhost7474dbdatanode484
outgoing_typed_relationships httplocalhost7474dbdatanode484relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode484properties
incoming_relationships httplocalhost7474dbdatanode484relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode484connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode484pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode484getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode484createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode484getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode484clonedSubgraph
create_relationship httplocalhost7474dbdatanode484relationships
paged_traverse httplocalhost7474dbdatanode484pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode484relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode484relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode485relationshipsout
data
name 418
traverse httplocalhost7474dbdatanode485traversereturnType
all_typed_relationships httplocalhost7474dbdatanode485relationshipsall-list|amp|types
property httplocalhost7474dbdatanode485propertieskey
self httplocalhost7474dbdatanode485
outgoing_typed_relationships httplocalhost7474dbdatanode485relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode485properties
incoming_relationships httplocalhost7474dbdatanode485relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode485connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode485pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode485getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode485createRelationships
REST API
96
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode485getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode485clonedSubgraph
create_relationship httplocalhost7474dbdatanode485relationships
paged_traverse httplocalhost7474dbdatanode485pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode485relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode485relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode486relationshipsout
data
name 419
traverse httplocalhost7474dbdatanode486traversereturnType
all_typed_relationships httplocalhost7474dbdatanode486relationshipsall-list|amp|types
property httplocalhost7474dbdatanode486propertieskey
self httplocalhost7474dbdatanode486
outgoing_typed_relationships httplocalhost7474dbdatanode486relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode486properties
incoming_relationships httplocalhost7474dbdatanode486relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode486connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode486pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode486getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode486createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode486getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode486clonedSubgraph
create_relationship httplocalhost7474dbdatanode486relationships
paged_traverse httplocalhost7474dbdatanode486pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode486relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode486relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode488relationshipsout
data
name 421
traverse httplocalhost7474dbdatanode488traversereturnType
all_typed_relationships httplocalhost7474dbdatanode488relationshipsall-list|amp|types
property httplocalhost7474dbdatanode488propertieskey
self httplocalhost7474dbdatanode488
outgoing_typed_relationships httplocalhost7474dbdatanode488relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode488properties
incoming_relationships httplocalhost7474dbdatanode488relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode488connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode488pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode488getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode488createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode488getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode488clonedSubgraph
create_relationship httplocalhost7474dbdatanode488relationships
paged_traverse httplocalhost7474dbdatanode488pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode488relationshipsall
REST API
97
incoming_typed_relationships httplocalhost7474dbdatanode488relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode498relationshipsout
data
name 431
traverse httplocalhost7474dbdatanode498traversereturnType
all_typed_relationships httplocalhost7474dbdatanode498relationshipsall-list|amp|types
property httplocalhost7474dbdatanode498propertieskey
self httplocalhost7474dbdatanode498
outgoing_typed_relationships httplocalhost7474dbdatanode498relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode498properties
incoming_relationships httplocalhost7474dbdatanode498relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode498connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode498pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode498getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode498createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode498getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode498clonedSubgraph
create_relationship httplocalhost7474dbdatanode498relationships
paged_traverse httplocalhost7474dbdatanode498pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode498relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode498relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode508relationshipsout
data
name 441
traverse httplocalhost7474dbdatanode508traversereturnType
all_typed_relationships httplocalhost7474dbdatanode508relationshipsall-list|amp|types
property httplocalhost7474dbdatanode508propertieskey
self httplocalhost7474dbdatanode508
outgoing_typed_relationships httplocalhost7474dbdatanode508relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode508properties
incoming_relationships httplocalhost7474dbdatanode508relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode508connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode508pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode508getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode508createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode508getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode508clonedSubgraph
create_relationship httplocalhost7474dbdatanode508relationships
paged_traverse httplocalhost7474dbdatanode508pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode508relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode508relationshipsin-list|amp|types
]
684 Paged traverser page sizeThe default page size is 50 items but depending on the application larger or smaller pages sizes mightbe appropriate This can be set by adding a pageSize query parameter
Example request
REST API
98
bull POST httplocalhost7474dbdatanode544pagedtraversenodepageSize=1bull Accept applicationjsonbull Content-Type applicationjson
prune_evaluatorlanguagebuiltinnamenonereturn_filterlanguagejavascriptbodypositionendNode()getProperty(name)contains(1)orderdepth_firstrelationshipstypeNEXTdirectionout
Example response
bull 201 Createdbull Content-Type applicationjsonbull Location httplocalhost7474dbdatanode544pagedtraversenode723906ad46b74865b71cba847e423a76
[
outgoing_relationships httplocalhost7474dbdatanode545relationshipsout
data
name 1
traverse httplocalhost7474dbdatanode545traversereturnType
all_typed_relationships httplocalhost7474dbdatanode545relationshipsall-list|amp|types
property httplocalhost7474dbdatanode545propertieskey
self httplocalhost7474dbdatanode545
outgoing_typed_relationships httplocalhost7474dbdatanode545relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode545properties
incoming_relationships httplocalhost7474dbdatanode545relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode545connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode545pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode545getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode545createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode545getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode545clonedSubgraph
create_relationship httplocalhost7474dbdatanode545relationships
paged_traverse httplocalhost7474dbdatanode545pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode545relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode545relationshipsin-list|amp|types
]
685 Paged traverser timeoutThe default timeout for a paged traverser is 60 seconds but depending on the application larger orsmaller timeouts might be appropriate This can be set by adding a leaseTime query parameter withthe number of seconds the paged traverser should last
Example request
bull POST httplocalhost7474dbdatanode577pagedtraversenodeleaseTime=10bull Accept applicationjsonbull Content-Type applicationjson
prune_evaluatorlanguagebuiltinnamenonereturn_filterlanguagejavascriptbodypositionendNode()getProperty(name)contains(1)orderdepth_firstrelationshipstypeNEXTdirectionout
Example response
bull 201 Created
REST API
99
bull Content-Type applicationjsonbull Location httplocalhost7474dbdatanode577pagedtraversenode6de04c6f439d403a8c7e10d8c738ab57
[
outgoing_relationships httplocalhost7474dbdatanode578relationshipsout
data
name 1
traverse httplocalhost7474dbdatanode578traversereturnType
all_typed_relationships httplocalhost7474dbdatanode578relationshipsall-list|amp|types
property httplocalhost7474dbdatanode578propertieskey
self httplocalhost7474dbdatanode578
outgoing_typed_relationships httplocalhost7474dbdatanode578relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode578properties
incoming_relationships httplocalhost7474dbdatanode578relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode578connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode578pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode578getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode578createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode578getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode578clonedSubgraph
create_relationship httplocalhost7474dbdatanode578relationships
paged_traverse httplocalhost7474dbdatanode578pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode578relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode578relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode587relationshipsout
data
name 10
traverse httplocalhost7474dbdatanode587traversereturnType
all_typed_relationships httplocalhost7474dbdatanode587relationshipsall-list|amp|types
property httplocalhost7474dbdatanode587propertieskey
self httplocalhost7474dbdatanode587
outgoing_typed_relationships httplocalhost7474dbdatanode587relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode587properties
incoming_relationships httplocalhost7474dbdatanode587relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode587connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode587pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode587getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode587createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode587getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode587clonedSubgraph
create_relationship httplocalhost7474dbdatanode587relationships
paged_traverse httplocalhost7474dbdatanode587pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode587relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode587relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode588relationshipsout
data
name 11
REST API
100
traverse httplocalhost7474dbdatanode588traversereturnType
all_typed_relationships httplocalhost7474dbdatanode588relationshipsall-list|amp|types
property httplocalhost7474dbdatanode588propertieskey
self httplocalhost7474dbdatanode588
outgoing_typed_relationships httplocalhost7474dbdatanode588relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode588properties
incoming_relationships httplocalhost7474dbdatanode588relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode588connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode588pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode588getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode588createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode588getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode588clonedSubgraph
create_relationship httplocalhost7474dbdatanode588relationships
paged_traverse httplocalhost7474dbdatanode588pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode588relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode588relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode589relationshipsout
data
name 12
traverse httplocalhost7474dbdatanode589traversereturnType
all_typed_relationships httplocalhost7474dbdatanode589relationshipsall-list|amp|types
property httplocalhost7474dbdatanode589propertieskey
self httplocalhost7474dbdatanode589
outgoing_typed_relationships httplocalhost7474dbdatanode589relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode589properties
incoming_relationships httplocalhost7474dbdatanode589relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode589connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode589pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode589getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode589createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode589getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode589clonedSubgraph
create_relationship httplocalhost7474dbdatanode589relationships
paged_traverse httplocalhost7474dbdatanode589pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode589relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode589relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode590relationshipsout
data
name 13
traverse httplocalhost7474dbdatanode590traversereturnType
all_typed_relationships httplocalhost7474dbdatanode590relationshipsall-list|amp|types
property httplocalhost7474dbdatanode590propertieskey
self httplocalhost7474dbdatanode590
outgoing_typed_relationships httplocalhost7474dbdatanode590relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode590properties
incoming_relationships httplocalhost7474dbdatanode590relationshipsin
extensions
REST API
101
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode590connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode590pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode590getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode590createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode590getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode590clonedSubgraph
create_relationship httplocalhost7474dbdatanode590relationships
paged_traverse httplocalhost7474dbdatanode590pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode590relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode590relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode591relationshipsout
data
name 14
traverse httplocalhost7474dbdatanode591traversereturnType
all_typed_relationships httplocalhost7474dbdatanode591relationshipsall-list|amp|types
property httplocalhost7474dbdatanode591propertieskey
self httplocalhost7474dbdatanode591
outgoing_typed_relationships httplocalhost7474dbdatanode591relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode591properties
incoming_relationships httplocalhost7474dbdatanode591relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode591connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode591pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode591getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode591createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode591getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode591clonedSubgraph
create_relationship httplocalhost7474dbdatanode591relationships
paged_traverse httplocalhost7474dbdatanode591pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode591relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode591relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode592relationshipsout
data
name 15
traverse httplocalhost7474dbdatanode592traversereturnType
all_typed_relationships httplocalhost7474dbdatanode592relationshipsall-list|amp|types
property httplocalhost7474dbdatanode592propertieskey
self httplocalhost7474dbdatanode592
outgoing_typed_relationships httplocalhost7474dbdatanode592relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode592properties
incoming_relationships httplocalhost7474dbdatanode592relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode592connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode592pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode592getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode592createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode592getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode592clonedSubgraph
REST API
102
create_relationship httplocalhost7474dbdatanode592relationships
paged_traverse httplocalhost7474dbdatanode592pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode592relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode592relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode593relationshipsout
data
name 16
traverse httplocalhost7474dbdatanode593traversereturnType
all_typed_relationships httplocalhost7474dbdatanode593relationshipsall-list|amp|types
property httplocalhost7474dbdatanode593propertieskey
self httplocalhost7474dbdatanode593
outgoing_typed_relationships httplocalhost7474dbdatanode593relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode593properties
incoming_relationships httplocalhost7474dbdatanode593relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode593connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode593pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode593getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode593createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode593getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode593clonedSubgraph
create_relationship httplocalhost7474dbdatanode593relationships
paged_traverse httplocalhost7474dbdatanode593pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode593relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode593relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode594relationshipsout
data
name 17
traverse httplocalhost7474dbdatanode594traversereturnType
all_typed_relationships httplocalhost7474dbdatanode594relationshipsall-list|amp|types
property httplocalhost7474dbdatanode594propertieskey
self httplocalhost7474dbdatanode594
outgoing_typed_relationships httplocalhost7474dbdatanode594relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode594properties
incoming_relationships httplocalhost7474dbdatanode594relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode594connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode594pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode594getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode594createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode594getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode594clonedSubgraph
create_relationship httplocalhost7474dbdatanode594relationships
paged_traverse httplocalhost7474dbdatanode594pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode594relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode594relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode595relationshipsout
data
REST API
103
name 18
traverse httplocalhost7474dbdatanode595traversereturnType
all_typed_relationships httplocalhost7474dbdatanode595relationshipsall-list|amp|types
property httplocalhost7474dbdatanode595propertieskey
self httplocalhost7474dbdatanode595
outgoing_typed_relationships httplocalhost7474dbdatanode595relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode595properties
incoming_relationships httplocalhost7474dbdatanode595relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode595connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode595pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode595getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode595createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode595getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode595clonedSubgraph
create_relationship httplocalhost7474dbdatanode595relationships
paged_traverse httplocalhost7474dbdatanode595pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode595relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode595relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode596relationshipsout
data
name 19
traverse httplocalhost7474dbdatanode596traversereturnType
all_typed_relationships httplocalhost7474dbdatanode596relationshipsall-list|amp|types
property httplocalhost7474dbdatanode596propertieskey
self httplocalhost7474dbdatanode596
outgoing_typed_relationships httplocalhost7474dbdatanode596relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode596properties
incoming_relationships httplocalhost7474dbdatanode596relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode596connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode596pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode596getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode596createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode596getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode596clonedSubgraph
create_relationship httplocalhost7474dbdatanode596relationships
paged_traverse httplocalhost7474dbdatanode596pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode596relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode596relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode598relationshipsout
data
name 21
traverse httplocalhost7474dbdatanode598traversereturnType
all_typed_relationships httplocalhost7474dbdatanode598relationshipsall-list|amp|types
property httplocalhost7474dbdatanode598propertieskey
self httplocalhost7474dbdatanode598
outgoing_typed_relationships httplocalhost7474dbdatanode598relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode598properties
incoming_relationships httplocalhost7474dbdatanode598relationshipsin
REST API
104
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode598connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode598pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode598getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode598createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode598getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode598clonedSubgraph
create_relationship httplocalhost7474dbdatanode598relationships
paged_traverse httplocalhost7474dbdatanode598pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode598relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode598relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode608relationshipsout
data
name 31
traverse httplocalhost7474dbdatanode608traversereturnType
all_typed_relationships httplocalhost7474dbdatanode608relationshipsall-list|amp|types
property httplocalhost7474dbdatanode608propertieskey
self httplocalhost7474dbdatanode608
outgoing_typed_relationships httplocalhost7474dbdatanode608relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode608properties
incoming_relationships httplocalhost7474dbdatanode608relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode608connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode608pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode608getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode608createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode608getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode608clonedSubgraph
create_relationship httplocalhost7474dbdatanode608relationships
paged_traverse httplocalhost7474dbdatanode608pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode608relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode608relationshipsin-list|amp|types
]
REST API
105
69 Built-in Graph AlgorithmsNeo4j comes with a number of built-in graph algorithms They are performed from a start node Thetraversal is controlled by the URI and the body sent with the request
algorithmThe algorithm to choose If not set default is shortestPath algorithm can have one of thesevalues
bull shortestPath
bull allSimplePaths
bull allPaths
bull dijkstra (optional with cost_property and default_cost parameters)
max_depthThe maximum depth as an integer for the algorithms like ShortestPath where applicable Defaultis 1
691 Find all shortest pathsThe shortestPath algorithm can find multiple paths between the same nodes like in this example
Example request
bull POST httplocalhost7474dbdatanode7paths
bull Accept applicationjson
bull Content-Type applicationjson
tohttplocalhost7474dbdatanode2 max_depth3 relationshipstypeto directionout algorithmshortestPath
Example response
bull 200 OK
bull Content-Type applicationjson
[
start httplocalhost7474dbdatanode7
nodes [ httplocalhost7474dbdatanode7 httplocalhost7474dbdatanode3 httplocalhost7474dbdatanode2 ]
length 2
relationships [ httplocalhost7474dbdatarelationship1 httplocalhost7474dbdatarelationship7 ]
end httplocalhost7474dbdatanode2
start httplocalhost7474dbdatanode7
nodes [ httplocalhost7474dbdatanode7 httplocalhost7474dbdatanode6 httplocalhost7474dbdatanode2 ]
length 2
relationships [ httplocalhost7474dbdatarelationship0 httplocalhost7474dbdatarelationship9 ]
end httplocalhost7474dbdatanode2
]
692 Find one of the shortest paths between nodesIf no path algorithm is specified a ShortestPath algorithm with a max depth of 1 will be chosen Inthis example the max_depth is set to 3 in order to find the shortest path between 3 linked nodes
Example request
bull POST httplocalhost7474dbdatanode14path
bull Accept applicationjson
REST API
106
bull Content-Type applicationjson
tohttplocalhost7474dbdatanode9 max_depth3 relationshipstypeto directionout algorithmshortestPath
Example response
bull 200 OK
bull Content-Type applicationjson
start httplocalhost7474dbdatanode14
nodes [ httplocalhost7474dbdatanode14 httplocalhost7474dbdatanode10 httplocalhost7474dbdatanode9 ]
length 2
relationships [ httplocalhost7474dbdatarelationship11 httplocalhost7474dbdatarelationship17 ]
end httplocalhost7474dbdatanode9
693 Execute a Dijkstra algorithm with similar weights on relationshipsExample request
bull POST httplocalhost7474dbdatanode29path
bull Accept applicationjson
bull Content-Type applicationjson
tohttplocalhost7474dbdatanode32 cost_propertycost relationshipstypeto directionout algorithmdijkstra
Example response
bull 200 OK
bull Content-Type applicationjson
weight 20
start httplocalhost7474dbdatanode29
nodes [ httplocalhost7474dbdatanode29 httplocalhost7474dbdatanode30 httplocalhost7474dbdatanode32 ]
length 2
relationships [ httplocalhost7474dbdatarelationship33 httplocalhost7474dbdatarelationship34 ]
end httplocalhost7474dbdatanode32
694 Execute a Dijkstra algorithm with weights on relationshipsExample request
bull POST httplocalhost7474dbdatanode20path
bull Accept applicationjson
bull Content-Type applicationjson
tohttplocalhost7474dbdatanode23 cost_propertycost relationshipstypeto directionout algorithmdijkstra
Example response
bull 200 OK
bull Content-Type applicationjson
weight 60
REST API
107
start httplocalhost7474dbdatanode20
nodes [ httplocalhost7474dbdatanode20 httplocalhost7474dbdatanode21 httplocalhost7474dbdatanode18 httplocalhost7474dbdatanode19 httplocalhost7474dbdatanode16 httplocalhost7474dbdatanode17 httplocalhost7474dbdatanode23 ]
length 6
relationships [ httplocalhost7474dbdatarelationship20 httplocalhost7474dbdatarelationship22 httplocalhost7474dbdatarelationship24 httplocalhost7474dbdatarelationship27 httplocalhost7474dbdatarelationship29 httplocalhost7474dbdatarelationship30 ]
end httplocalhost7474dbdatanode23
REST API
108
610 Batch operations
CautionBatch support is currently experimental Expect this part of the API to change
6101 Execute multiple operations in batchThis lets you execute multiple API calls through a single HTTP call significantly improvingperformance for large insert and update operations
The batch service expects an array of job descriptions as input each job description describing anaction to be performed via the normal server API
This service is transactional If any of the operations performed fails (returns a non-2xx HTTP statuscode) the transaction will be rolled back and all changes will be undone
Each job description should contain a path attribute with a value relative to the data API root (sohttplocalhostdbdatanode becomes just node) and a method attribute containing HTTP verb touse
Optionally you may provide a body attribute and an id attribute to help you keep track of responsesalthough responses are guaranteed to be returned in the same order the job descriptions are received
The following figure outlines the different parts of the job descriptions
Example request
bull POST httplocalhost7474dbdatabatch
bull Accept applicationjson
bull Content-Type applicationjson
[
methodPUT
tonode0properties
body
age1
id0
methodGET
tonode0
id1
REST API
109
methodPOST
tonode
body
age1
id2
methodPOST
tonode
body
age1
id3
]
Example response
bull 200 OK
bull Content-Type applicationjson
[id0fromnode0propertiesid1body
outgoing_relationships httplocalhost7474dbdatanode0relationshipsout
data
age 1
traverse httplocalhost7474dbdatanode0traversereturnType
all_typed_relationships httplocalhost7474dbdatanode0relationshipsall-list|amp|types
property httplocalhost7474dbdatanode0propertieskey
self httplocalhost7474dbdatanode0
outgoing_typed_relationships httplocalhost7474dbdatanode0relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode0properties
incoming_relationships httplocalhost7474dbdatanode0relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode0connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode0pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode0getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode0createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode0getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode0clonedSubgraph
create_relationship httplocalhost7474dbdatanode0relationships
paged_traverse httplocalhost7474dbdatanode0pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode0relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode0relationshipsin-list|amp|types
fromnode0id2locationhttplocalhost7474dbdatanode3body
outgoing_relationships httplocalhost7474dbdatanode3relationshipsout
data
age 1
traverse httplocalhost7474dbdatanode3traversereturnType
all_typed_relationships httplocalhost7474dbdatanode3relationshipsall-list|amp|types
property httplocalhost7474dbdatanode3propertieskey
self httplocalhost7474dbdatanode3
outgoing_typed_relationships httplocalhost7474dbdatanode3relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode3properties
incoming_relationships httplocalhost7474dbdatanode3relationshipsin
extensions
FunctionalTestPlugin
REST API
110
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode3connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode3pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode3getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode3createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode3getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode3clonedSubgraph
create_relationship httplocalhost7474dbdatanode3relationships
paged_traverse httplocalhost7474dbdatanode3pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode3relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode3relationshipsin-list|amp|types
fromnodeid3locationhttplocalhost7474dbdatanode4body
outgoing_relationships httplocalhost7474dbdatanode4relationshipsout
data
age 1
traverse httplocalhost7474dbdatanode4traversereturnType
all_typed_relationships httplocalhost7474dbdatanode4relationshipsall-list|amp|types
property httplocalhost7474dbdatanode4propertieskey
self httplocalhost7474dbdatanode4
outgoing_typed_relationships httplocalhost7474dbdatanode4relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode4properties
incoming_relationships httplocalhost7474dbdatanode4relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode4connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode4pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode4getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode4createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode4getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode4clonedSubgraph
create_relationship httplocalhost7474dbdatanode4relationships
paged_traverse httplocalhost7474dbdatanode4pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode4relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode4relationshipsin-list|amp|types
fromnode]
6102 Refer to items created earlier in the same batch jobThe batch operation API allows you to refer to the URI returned from a created resource in subsequentjob descriptions within the same batch call
Use the [JOB ID] special syntax to inject URIs from created resources into JSON strings insubsequent job descriptions
Example request
bull POST httplocalhost7474dbdatabatch
bull Accept applicationjson
bull Content-Type applicationjson
[
methodPOST
tonode
id0
REST API
111
body
age1
methodPOST
tonode
id1
body
age12
methodPOST
to0relationships
id3
body
to1
data
namebob
typeKNOWS
methodPOST
toindexrelationshipmy_relsnamebob
id4
body3
]
Example response
bull 200 OK
bull Content-Type applicationjson
[id0locationhttplocalhost7474dbdatanode7body
outgoing_relationships httplocalhost7474dbdatanode7relationshipsout
data
age 1
traverse httplocalhost7474dbdatanode7traversereturnType
all_typed_relationships httplocalhost7474dbdatanode7relationshipsall-list|amp|types
property httplocalhost7474dbdatanode7propertieskey
self httplocalhost7474dbdatanode7
outgoing_typed_relationships httplocalhost7474dbdatanode7relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode7properties
incoming_relationships httplocalhost7474dbdatanode7relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode7connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode7pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode7getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode7createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode7getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode7clonedSubgraph
create_relationship httplocalhost7474dbdatanode7relationships
paged_traverse httplocalhost7474dbdatanode7pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode7relationshipsall
REST API
112
incoming_typed_relationships httplocalhost7474dbdatanode7relationshipsin-list|amp|types
fromnodeid1locationhttplocalhost7474dbdatanode8body
outgoing_relationships httplocalhost7474dbdatanode8relationshipsout
data
age 12
traverse httplocalhost7474dbdatanode8traversereturnType
all_typed_relationships httplocalhost7474dbdatanode8relationshipsall-list|amp|types
property httplocalhost7474dbdatanode8propertieskey
self httplocalhost7474dbdatanode8
outgoing_typed_relationships httplocalhost7474dbdatanode8relationshipsout-list|amp|types
properties httplocalhost7474dbdatanode8properties
incoming_relationships httplocalhost7474dbdatanode8relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode8connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode8pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode8getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode8createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode8getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode8clonedSubgraph
create_relationship httplocalhost7474dbdatanode8relationships
paged_traverse httplocalhost7474dbdatanode8pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode8relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode8relationshipsin-list|amp|types
fromnodeid3locationhttplocalhost7474dbdatarelationship1body
start httplocalhost7474dbdatanode7
data
name bob
self httplocalhost7474dbdatarelationship1
property httplocalhost7474dbdatarelationship1propertieskey
properties httplocalhost7474dbdatarelationship1properties
type KNOWS
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship1methodOnRelationship
end httplocalhost7474dbdatanode8
fromhttplocalhost7474dbdatanode7relationshipsid4locationhttplocalhost7474dbdataindexrelationshipmy_relsnamebob1body
indexed httplocalhost7474dbdataindexrelationshipmy_relsnamebob1
start httplocalhost7474dbdatanode7
data
name bob
self httplocalhost7474dbdatarelationship1
property httplocalhost7474dbdatarelationship1propertieskey
properties httplocalhost7474dbdatarelationship1properties
type KNOWS
extensions
FunctionalTestPlugin
methodOnRelationship httplocalhost7474dbdataextFunctionalTestPluginrelationship1methodOnRelationship
end httplocalhost7474dbdatanode8
fromindexrelationshipmy_relsnamebob]
REST API
113
611 Gremlin PluginGremlin lthttpgremlintinkerpopcomgt is a Groovy based Graph Traversal Language and provides avery expressive way of explicitly scripting traversals through a Neo4j graph
The Neo4j Gremlin Plugin provides an endpoint to send Gremlin scripts to the Neo4j Serverhave them executed on the server database and return the results as Neo4j Node and Relationshiprepresentations thus keeping the types throughout the REST API consistent This results is quiteverbose listings when returning Neo4j Node Relationship or Graph representations On the otherhand just return properties like in the Section 6114 ldquoSend a Gremlin Script - JSON encoded withtable resultrdquo example for returns tailored to specific needs
6111 Send a Gremlin Script - URL encodedSend a Gremlin Script URL-encoded with UTF-8 encoding eg the equivalent of the Gremlin Scripti = gv(1)ioutEinV
Example request
bull POST httplocalhost7474dbdataextGremlinPlugingraphdbexecute_script
bull Accept applicationjson
bull Content-Type applicationx-www-form-urlencoded
script=i+3D+gv282293BioutEinV
Example response
bull 200 OK
bull Content-Type applicationjson
[
outgoing_relationships httplocalhost7474dbdatanode1relationshipsout
data
name you
traverse httplocalhost7474dbdatanode1traversereturnType
all_typed_relationships httplocalhost7474dbdatanode1relationshipsall-list|amp|types
property httplocalhost7474dbdatanode1propertieskey
self httplocalhost7474dbdatanode1
properties httplocalhost7474dbdatanode1properties
outgoing_typed_relationships httplocalhost7474dbdatanode1relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode1relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode1connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode1pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode1getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode1createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode1getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode1clonedSubgraph
create_relationship httplocalhost7474dbdatanode1relationships
paged_traverse httplocalhost7474dbdatanode1pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode1relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode1relationshipsin-list|amp|types
]
REST API
114
6112 Load a sample graph graphImport a graph form a GraphML lthttpgraphmlgraphdrawingorggt file can be achieved through theGremlin GraphMLReader The following script imports 3 nodes into Neo4j and then returns a list ofall nodes in the graph
Example request
bull POST httplocalhost7474dbdataextGremlinPlugingraphdbexecute_scriptbull Accept applicationjsonbull Content-Type applicationjson
scriptGraphMLReaderinputGraph(g new URL(httpsrawgithubcomneo4jgremlin-pluginmastersrcdatagraphml1xml)openStream())gV
Example response
bull 200 OKbull Content-Type applicationjson
[
outgoing_relationships httplocalhost7474dbdatanode0relationshipsout
data
traverse httplocalhost7474dbdatanode0traversereturnType
all_typed_relationships httplocalhost7474dbdatanode0relationshipsall-list|amp|types
property httplocalhost7474dbdatanode0propertieskey
self httplocalhost7474dbdatanode0
properties httplocalhost7474dbdatanode0properties
outgoing_typed_relationships httplocalhost7474dbdatanode0relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode0relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode0connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode0pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode0getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode0createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode0getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode0clonedSubgraph
create_relationship httplocalhost7474dbdatanode0relationships
paged_traverse httplocalhost7474dbdatanode0pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode0relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode0relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode3relationshipsout
data
name I
traverse httplocalhost7474dbdatanode3traversereturnType
all_typed_relationships httplocalhost7474dbdatanode3relationshipsall-list|amp|types
property httplocalhost7474dbdatanode3propertieskey
self httplocalhost7474dbdatanode3
properties httplocalhost7474dbdatanode3properties
outgoing_typed_relationships httplocalhost7474dbdatanode3relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode3relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode3connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode3pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode3getThisNodeOrById
REST API
115
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode3createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode3getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode3clonedSubgraph
create_relationship httplocalhost7474dbdatanode3relationships
paged_traverse httplocalhost7474dbdatanode3pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode3relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode3relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode4relationshipsout
data
name you
traverse httplocalhost7474dbdatanode4traversereturnType
all_typed_relationships httplocalhost7474dbdatanode4relationshipsall-list|amp|types
property httplocalhost7474dbdatanode4propertieskey
self httplocalhost7474dbdatanode4
properties httplocalhost7474dbdatanode4properties
outgoing_typed_relationships httplocalhost7474dbdatanode4relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode4relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode4connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode4pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode4getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode4createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode4getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode4clonedSubgraph
create_relationship httplocalhost7474dbdatanode4relationships
paged_traverse httplocalhost7474dbdatanode4pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode4relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode4relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode5relationshipsout
data
name him
traverse httplocalhost7474dbdatanode5traversereturnType
all_typed_relationships httplocalhost7474dbdatanode5relationshipsall-list|amp|types
property httplocalhost7474dbdatanode5propertieskey
self httplocalhost7474dbdatanode5
properties httplocalhost7474dbdatanode5properties
outgoing_typed_relationships httplocalhost7474dbdatanode5relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode5relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode5connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode5pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode5getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode5createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode5getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode5clonedSubgraph
create_relationship httplocalhost7474dbdatanode5relationships
paged_traverse httplocalhost7474dbdatanode5pagedtraversereturnTypepageSizeleaseTime
REST API
116
all_relationships httplocalhost7474dbdatanode5relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode5relationshipsin-list|amp|types
]
6113 Sort a result using raw Groovy operationsThe following script returns a sorted list of all nodes connected via outgoing relationships to node 1sorted by their name-property
Example request
bull POST httplocalhost7474dbdataextGremlinPlugingraphdbexecute_script
bull Accept applicationjson
bull Content-Type applicationjson
scriptgv(8)outEinVsortitnametoList()
Example response
bull 200 OK
bull Content-Type applicationjson
[
outgoing_relationships httplocalhost7474dbdatanode7relationshipsout
data
name him
traverse httplocalhost7474dbdatanode7traversereturnType
all_typed_relationships httplocalhost7474dbdatanode7relationshipsall-list|amp|types
property httplocalhost7474dbdatanode7propertieskey
self httplocalhost7474dbdatanode7
properties httplocalhost7474dbdatanode7properties
outgoing_typed_relationships httplocalhost7474dbdatanode7relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode7relationshipsin
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode7connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode7pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode7getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode7createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode7getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode7clonedSubgraph
create_relationship httplocalhost7474dbdatanode7relationships
paged_traverse httplocalhost7474dbdatanode7pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode7relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode7relationshipsin-list|amp|types
outgoing_relationships httplocalhost7474dbdatanode6relationshipsout
data
name you
traverse httplocalhost7474dbdatanode6traversereturnType
all_typed_relationships httplocalhost7474dbdatanode6relationshipsall-list|amp|types
property httplocalhost7474dbdatanode6propertieskey
self httplocalhost7474dbdatanode6
properties httplocalhost7474dbdatanode6properties
outgoing_typed_relationships httplocalhost7474dbdatanode6relationshipsout-list|amp|types
incoming_relationships httplocalhost7474dbdatanode6relationshipsin
REST API
117
extensions
FunctionalTestPlugin
connected_nodes httplocalhost7474dbdataextFunctionalTestPluginnode6connected_nodes
pathToReference httplocalhost7474dbdataextFunctionalTestPluginnode6pathToReference
getThisNodeOrById httplocalhost7474dbdataextFunctionalTestPluginnode6getThisNodeOrById
createRelationships httplocalhost7474dbdataextFunctionalTestPluginnode6createRelationships
getRelationshipsBetween httplocalhost7474dbdataextFunctionalTestPluginnode6getRelationshipsBetween
GraphCloner
clonedSubgraph httplocalhost7474dbdataextGraphClonernode6clonedSubgraph
create_relationship httplocalhost7474dbdatanode6relationships
paged_traverse httplocalhost7474dbdatanode6pagedtraversereturnTypepageSizeleaseTime
all_relationships httplocalhost7474dbdatanode6relationshipsall
incoming_typed_relationships httplocalhost7474dbdatanode6relationshipsin-list|amp|types
]
6114 Send a Gremlin Script - JSON encoded with table resultTo send a Script JSON encoded set the payload Content-Type Header In this example find all thethings that my friends like and return a table listing my friends by their name and the names of thethings they like in a table with two columns ignoring the third named step variable I Remember thateverything in Gremlin is an iterator - in order to populate the result table t iterate through the pipeswith gtgt -1
Example request
bull POST httplocalhost7474dbdataextGremlinPlugingraphdbexecute_script
bull Accept applicationjson
bull Content-Type applicationjson
scripti = gv(11)t= new Table()ias(I)out(know)as(friend)out(like)as(likes)table(t[friendlikes])itnameitname gtgt -1t
Example response
bull 200 OK
bull Content-Type applicationjson
[
data [ [ Joe cats ] [ Joe dogs ] ]
columns [ friend likes ]
]
REST API
118
612 Cypher PluginThe Neo4j Cypher Plugin enables querying with the Chapter 4 Cypher Query Language possibleThe results are returned as a list of string headers (columns) and a data part consisting of a list of allrows every row consisting of a list of REST representations of the field value - Node Relationshipor any simple value like String
6121 Send a QueryA simple query returning all nodes connected to node 1 returning the node and the name property ifit exists otherwise null
Example request
bull POST httplocalhost7474dbdataextCypherPlugingraphdbexecute_query
bull Accept applicationjson
bull Content-Type applicationjson
query start x = (3) match (x) --gt (n) return nname nage
Example response
bull 200 OK
bull Content-Type applicationjson
data [ [ you null ] [ him null ] ]
columns [ nname nage ]
119
Chapter 7 Indexing
Indexing in Neo4j can be done in two different ways
1 The database itself is a natural index consisting of its relationships of different types betweennodes For example a tree structure can be layered on top of the data and used for index lookupsperformed by a traverser
2 Separate index engines can be used with Apache Lucene lthttpluceneapacheorgjava3_1_0indexhtmlgt being the default backend included with Neo4j
This chapter demonstrate how to use the second type of indexing focusing on Lucene
Indexing
120
71 IntroductionIndexing operations are part of the Neo4j index API lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexpackage-summaryhtmlgt
Each index is tied to a unique user-specified name (for example first_name or books) andcan index either nodes lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbNodehtmlgt or relationships lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbRelationshiphtmlgt
The default index implementation is provided by the neo4j-lucene-index component whichis included in the standard Neo4j download It can also be downloaded separately from httprepo1mavenorgmaven2orgneo4jneo4j-lucene-index For Maven users the neo4j-lucene-index component has the coordinates orgneo4jneo4j-lucene-index and should be usedwith the same version of orgneo4jneo4j-kernel Different versions of the index and kernelcomponents are not compatible in the general case Both components are included transitively by theorgneo4jneo4jpom artifact which makes it simple to keep the versions in sync
NoteAll modifying index operations must be performed inside a transaction as with anymutating operation in Neo4j
Indexing
121
72 CreateAn index is created if it doesnrsquot exist when you ask for it Unless you give it a custom configuration itwill be created with default configuration and backend
To set the stage for our examples letrsquos create some indexes to begin with
IndexManager index = graphDbindex()
IndexltNodegt actors = indexforNodes( actors )
IndexltNodegt movies = indexforNodes( movies )
RelationshipIndex roles = indexforRelationships( roles )
This will create two node indexes and one relationship index with default configuration SeeSection 78 ldquoRelationship indexesrdquo for more information specific to relationship indexes
See Section 710 ldquoConfiguration and fulltext indexesrdquo for how to create fulltext indexes
You can also check if an index exists like this
IndexManager index = graphDbindex()
boolean indexExists = indexexistsForNodes( actors )
Indexing
122
73 DeleteIndexes can be deleted When deleting the entire contents of the index will be removed as well as itsassociated configuration A new index can be created with the same name at a later point in time
IndexManager index = graphDbindex()
IndexltNodegt actors = indexforNodes( actors )
actorsdelete()
Note that the actual deletion of the index is made during the commit of the surrounding transactionCalls made to such an index instance after delete() lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexhtmldelete2829gt has been called are invalid inside thattransaction as well as outside (if the transaction is successful) but will become valid again if thetransaction is rolled back
Indexing
123
74 AddEach index supports associating any number of key-value pairs with any number of entities (nodes orrelationships) where each association between entity and key-value pair is performed individually Tobegin with letrsquos add a few nodes to the indexes
Actors
Node reeves = graphDbcreateNode()
actorsadd( reeves name Keanu Reeves )
Node bellucci = graphDbcreateNode()
actorsadd( bellucci name Monica Bellucci )
multiple values for a field
actorsadd( bellucci name La Bellucci )
Movies
Node theMatrix = graphDbcreateNode()
moviesadd( theMatrix title The Matrix )
moviesadd( theMatrix year 1999 )
Node theMatrixReloaded = graphDbcreateNode()
moviesadd( theMatrixReloaded title The Matrix Reloaded )
moviesadd( theMatrixReloaded year 2003 )
Node malena = graphDbcreateNode()
moviesadd( malena title Malegravena )
moviesadd( malena year 2000 )
Note that there can be multiple values associated with the same entity and key
Next up wersquoll create relationships and index them as well
we need a relationship type
DynamicRelationshipType ACTS_IN = DynamicRelationshipTypewithName( ACTS_IN )
create relationships
Relationship role1 = reevescreateRelationshipTo( theMatrix ACTS_IN )
rolesadd( role1 name Neo )
Relationship role2 = reevescreateRelationshipTo( theMatrixReloaded ACTS_IN )
rolesadd( role2 name Neo )
Relationship role3 = belluccicreateRelationshipTo( theMatrixReloaded ACTS_IN )
rolesadd( role3 name Persephone )
Relationship role4 = belluccicreateRelationshipTo( malena ACTS_IN )
rolesadd( role4 name Malegravena Scordia )
Assuming we set the same key-value pairs as properties as well our example graph looks like this
Indexing
124
75 RemoveRemoving lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexhtmlremove28T20javalangString20javalangObject29gt from an index is similar toadding but can be done by supplying one of the following combinations of arguments
bull entity
bull entity key
bull entity key value
completely remove bellucci from the actors index
actorsremove( bellucci )
remove any name entry of bellucci from the actors index
actorsremove( bellucci name )
remove the name -gt La Bellucci entry of bellucci
actorsremove( bellucci name La Bellucci )
Indexing
125
76 Update
ImportantTo update an index entry old one must be removed and a new one added
Remember that a node or relationship can be associated with any number of key-value pairs in anindex which means that you can index a node or relationship with many key-value pairs that havethe same key In the case where a property value changes and yoursquod like to update the index itrsquos notenough to just index the new value - yoursquoll have to remove the old value as well
Herersquos a code example for that demonstrates how itrsquos done
create a node with a property
Node fishburn = graphDbcreateNode()
fishburnsetProperty( name Fishburn )
index it
actorsadd( fishburn name fishburngetProperty( name ) )
update the index entry
actorsremove( fishburn name fishburngetProperty( name ) )
fishburnsetProperty( name Laurence Fishburn )
actorsadd( fishburn name fishburngetProperty( name ) )
Indexing
126
77 SearchAn index can be searched in two ways get lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexhtmlget28javalangString20javalangObject29gt and querylthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexhtmlquery28javalangString20javalangObject29gt The get method will return exact matches tothe given key-value pair whereas query exposes querying capabilities directly from the backendused by the index For example the Lucene query syntax lthttpluceneapacheorgjava3_1_0queryparsersyntaxhtmlgt can be used directly with the default indexing backend
771 GetThis is how to search for a single exact match
IndexHitsltNodegt hits = actorsget( name Keanu Reeves )
Node reeves = hitsgetSingle()
IndexHits lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexHitshtmlgt is an Iterable with some additional useful methods For examplegetSingle() lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexHitshtmlgetSingle2829gt returns the first and only item from the result iterator or null ifthere isnrsquot any hit
Herersquos how to get a single relationship by exact matching and retrieve its start and end nodes
Relationship persephone = rolesget( name Persephone )getSingle()
Node actor = persephonegetStartNode()
Node movie = persephonegetEndNode()
Finally we can iterate over all exact matches from a relationship index
for ( Relationship role rolesget( name Neo ) )
this will give us Reeves twice
Node reeves = rolegetStartNode()
ImportantIn you donrsquot iterate through all the hits IndexHitsclose() lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexHitshtmlclose2829gt must becalled explicitly
772 QueryThere are two query methods one which uses a key-value signature where the value represents aquery for values with the given key only The other method is more generic and supports querying formore than one key-value pair in the same query
Herersquos an example using the key-query option
for ( Node actor actorsquery( name e ) )
This will return Reeves and Bellucci
In the following example the query uses multiple keys
for ( Node movie moviesquery( titleMatrix AND year1999 ) )
This will return The Matrix from 1999 only
Indexing
127
NoteBeginning a wildcard search with or is discouraged by Lucene but willnevertheless work
CautionYou canrsquot have any whitespace in the search term with this syntax See Section 7113ldquoQuerying with Lucene Query objectsrdquo for how to do that
Indexing
128
78 Relationship indexesAn index for relationships is just like an index for nodes extended by providing support to constraina search to relationships with a specific start andor end nodes These extra methods reside in theRelationshipIndex lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexRelationshipIndexhtmlgt interface which extends IndexltRelationshipgt lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexhtmlgt
Example of querying a relationship index
find relationships filtering on start node
using exact matches
IndexHitsltRelationshipgt reevesAsNeoHits
reevesAsNeoHits = rolesget( name Neo reeves null )
Relationship reevesAsNeo = reevesAsNeoHitsiterator()next()
reevesAsNeoHitsclose()
find relationships filtering on end node
using a query
IndexHitsltRelationshipgt matrixNeoHits
matrixNeoHits = rolesquery( name eo null theMatrix )
Relationship matrixNeo = matrixNeoHitsiterator()next()
matrixNeoHitsclose()
And herersquos an example for the special case of searching for a specific relationship type
find relationships filtering on end node
using a relationship type
this is how to add it to the index
rolesadd( reevesAsNeo type reevesAsNeogetType()name() )
Note that to use a compound query we cant combine committed
and uncommitted index entries so well commit before querying
txsuccess()
txfinish()
and now we can search for it
IndexHitsltRelationshipgt typeHits
typeHits = rolesquery( typeACTS_IN AND nameNeo null theMatrix )
Relationship typeNeo = typeHitsiterator()next()
typeHitsclose()
Such an index can be useful if your domain has nodes with a very large number of relationshipsbetween them since it reduces the search time for a relationship between two nodes A good examplewhere this approach pays dividends is in time series data where we have readings represented as arelationship per occurrence
Indexing
129
79 ScoresThe IndexHits interface exposes scoring lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexHitshtmlcurrentScore2829gt so that the index can communicatescores for the hits Note that the result is not sorted by the score unless you explicitly specify that SeeSection 7112 ldquoSortingrdquo for how to sort by score
IndexHitsltNodegt hits = moviesquery( title The )
for ( Node movie hits )
Systemoutprintln( moviegetProperty( title ) + + hitscurrentScore() )
Indexing
130
710 Configuration and fulltext indexesAt the time of creation extra configuration can be specified to control the behavior of the index andwhich backend to use For example to create a Lucene fulltext index
IndexManager index = graphDbindex()
IndexltNodegt fulltextMovies = indexforNodes( movies-fulltext
MapUtilstringMap( IndexManagerPROVIDER lucene type fulltext ) )
fulltextMoviesadd( theMatrix title The Matrix )
fulltextMoviesadd( theMatrixReloaded title The Matrix Reloaded )
search in the fulltext index
Node found = fulltextMoviesquery( title reloAdEd )getSingle()
TipIn order to search for tokenized words the query method has to be used The get methodwill only match the full string value not the tokens
The configuration of the index is persisted once the index has been created The providerconfiguration key is interpreted by Neo4j but any other configuration is passed onto the backendindex (eg Lucene) to interpret
Table 71 Lucene indexing configuration parameters
Parameter Possible values Effect
type exact fulltext exact is the default and uses a Lucenekeyword analyzer lthttpluceneapacheorgjava3_1_0apicoreorgapacheluceneanalysisKeywordAnalyzerhtmlgt fulltext uses a white-space tokenizer in its analyzer
to_lower_case true false This parameter goes together with typefulltext and converts values to lower caseduring both additions and querying making theindex case insensitive Defaults to true
analyzer the full class name ofan Analyzer lthttpluceneapacheorgjava3_1_0apicoreorgapacheluceneanalysisAnalyzerhtmlgt
Overrides the type so that a custom analyzercan be used Note to_lower_case still affectslowercasing of string queries If the customanalyzer uppercases the indexed tokens stringqueries will not match as expected
Indexing
131
711 Extra features for Lucene indexes
7111 Numeric rangesLucene supports smart indexing of numbers querying for ranges and sorting such results and so doesits backend for Neo4j To mark a value so that it is indexed as a numeric value we can make use ofthe ValueContext lthttpcomponentsneo4jorgneo4j-lucene-index14M06apidocsorgneo4jindexluceneValueContexthtmlgt class like this
moviesadd( theMatrix year-numeric new ValueContext( 1999 )indexNumeric() )
moviesadd( theMatrixReloaded year-numeric new ValueContext( 2003 )indexNumeric() )
moviesadd( malena year-numeric new ValueContext( 2000 )indexNumeric() )
int from = 1997
int to = 1999
hits = moviesquery( QueryContextnumericRange( year-numeric from to ) )
NoteThe same type must be used for indexing and querying That is you canrsquot index a value asa Long and then query the index using an Integer
By giving null as fromto argument an open ended query is created In the following example we aredoing that and have added sorting to the query as well
hits = moviesquery(
QueryContextnumericRange( year-numeric from null )
sortNumeric( year-numeric false ) )
Fromto in the ranges defaults to be inclusive but you can change this behavior by using two extraparameters
moviesadd( theMatrix score new ValueContext( 87 )indexNumeric() )
moviesadd( theMatrixReloaded score new ValueContext( 71 )indexNumeric() )
moviesadd( malena score new ValueContext( 74 )indexNumeric() )
include 80 exclude 90
hits = moviesquery( QueryContextnumericRange( score 80 90 true false ) )
7112 SortingLucene performs sorting very well and that is also exposed in the index backend through theQueryContext lthttpcomponentsneo4jorgneo4j-lucene-index14M06apidocsorgneo4jindexluceneQueryContexthtmlgt class
hits = moviesquery( title new QueryContext( )sort( title ) )
for ( Node hit hits )
all movies with a title in the index ordered by title
or
hits = moviesquery( new QueryContext( title )sort( year title ) )
for ( Node hit hits )
all movies with a title in the index ordered by year then title
We sort the results by relevance (score) like this
hits = moviesquery( title new QueryContext( The )sortByScore() )
for ( Node movie hits )
Indexing
132
hits sorted by relevance (score)
7113 Querying with Lucene Query objectsInstead of passing in Lucene query syntax queries you can instantiate such queries programmaticallyand pass in as argument for example
a TermQuery will give exact matches
Node actor = actorsquery( new TermQuery( new Term( name Keanu Reeves ) ) )getSingle()
Note that the TermQuery lthttpluceneapacheorgjava3_1_0apicoreorgapachelucenesearchTermQueryhtmlgt is basically the same thing as using the get method on the index
This is how to perform wildcard searches using Lucene Query Objects
hits = moviesquery( new WildcardQuery( new Term( title The Matrix ) ) )
for ( Node movie hits )
Systemoutprintln( moviegetProperty( title ) )
Note that this allows for whitespace in the search string
7114 Compound queriesLucene supports querying for multiple terms in the same query like so
hits = moviesquery( titleMatrix AND year1999 )
CautionCompound queries canrsquot search across committed index entries and those who havenrsquot gotcommitted yet at the same time
7115 Default operatorThe default operator (that is whether AND or OR is used in between different terms) in a query is ORChanging that behavior is also done via the QueryContext lthttpcomponentsneo4jorgneo4j-lucene-index14M06apidocsorgneo4jindexluceneQueryContexthtmlgt class
QueryContext query = new QueryContext( titleMatrix year1999 )defaultOperator( OperatorAND )
hits = moviesquery( query )
7116 CachingIf your index lookups becomes a performance bottle neck caching can be enabled for certain keys incertain indexes (key locations) to speed up get requests The caching is implemented with an LRUlthttpenwikipediaorgwikiCache_algorithmsLeast_Recently_Usedgt cache so that only the mostrecently accessed results are cached (with results meaning a query result of a get request not asingle entity) You can control the size of the cache (the maximum number of results) per index key
IndexltNodegt index = graphDbindex()forNodes( actors )
( (LuceneIndexltNodegt) index )setCacheCapacity( name 300000 )
CautionThis setting is not persisted after shutting down the database This means set this valueafter each startup of the database if you want to keep it
Indexing
133
712 Batch insertionNeo4j has a batch insertion mode intended for initial imports which must run in a singlethread and bypasses transactions and other checks in favor of performance Indexingduring batch insertion is done using BatchInserterIndex lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexBatchInserterIndexhtmlgt which are provided viaBatchInserterIndexProvider lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexBatchInserterIndexProviderhtmlgt An example
BatchInserter inserter = new BatchInserterImpl( targetneo4jdb-batchinsert )
BatchInserterIndexProvider indexProvider = new LuceneBatchInserterIndexProvider( inserter )
BatchInserterIndex actors = indexProvidernodeIndex( actors MapUtilstringMap( type exact ) )
actorssetCacheCapacity( name 100000 )
MapltString Objectgt properties = MapUtilmap( name Keanu Reeves )
long node = insertercreateNode( properties )
actorsadd( node properties )
Make sure to shut down the index provider
indexProvidershutdown()
insertershutdown()
The configuration parameters are the same as mentioned in Section 710 ldquoConfiguration and fulltextindexesrdquo
7121 Best practicesHere are some pointers to get the most performance out of BatchInserterIndex
bull Try to avoid flushing lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexBatchInserterIndexhtmlflush2829gt too often because each flush will result in alladditions (since last flush) to be visible to the querying methods and publishing those changes canbe a performance penalty
bull Have (as big as possible) phases where one phase is either only writes or only reads and donrsquotforget to flush after a write phase so that those changes becomes visible to the querying methods
bull Enable caching lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexBatchInserterIndexhtmlsetCacheCapacity28javalangString20int29gt for keys you knowyoursquore going to do lookups for later on to increase performance significantly (though insertionperformance may degrade slightly)
Indexing
134
713 Auto IndexingNeo4j provides the ability to have an index that automatically follows property values as they areadded deleted and changed on database primitives This functionality is called auto indexing and iscontrolled both from the database configuration Map and through its own API
CautionThis is an experimental feature Expect changes in the API and do not rely on it forproduction data handling
7131 ConfigurationBy default Auto Indexing is off for both Nodes and Relationships To enable it ondatabase startup set the configuration options ConfigNODE_AUTO_INDEXING andConfigRELATIONSHIP_AUTO_INDEXING to the string true
If you just enable auto indexing as above then still no property will be auto indexed To define whichproperty names you want the auto indexer to monitor as a configuration parameter set the ConfigNODERELATIONSHIP_KEYS_INDEXABLE option to a String that is a comma separated concatenationof the property names you want auto indexed
Creating the configuration adding nodeProp1 and nodeProp2 as
auto indexed properties for Nodes and relProp1 and relProp2 as
auto indexed properties for Relationships Only those will be
indexed We also have to enable auto indexing for both these
primitives explicitly
MapltString Stringgt config = new HashMapltString Stringgt()
configput( ConfigNODE_KEYS_INDEXABLE nodeProp1 nodeProp2 )
configput( ConfigRELATIONSHIP_KEYS_INDEXABLE relProp1 relProp2 )
configput( ConfigNODE_AUTO_INDEXING true )
configput( ConfigRELATIONSHIP_AUTO_INDEXING true )
EmbeddedGraphDatabase graphDb = new EmbeddedGraphDatabase(
getStoreDir( testConfig ) config )
Transaction tx = graphDbbeginTx()
Node node1 = null node2 = null
Relationship rel = null
try
Create the primitives
node1 = graphDbcreateNode()
node2 = graphDbcreateNode()
rel = node1createRelationshipTo( node2
DynamicRelationshipTypewithName( DYNAMIC ) )
Add indexable and non-indexable properties
node1setProperty( nodeProp1 nodeProp1Value )
node2setProperty( nodeProp2 nodeProp2Value )
node1setProperty( nonIndexed nodeProp2NonIndexedValue )
relsetProperty( relProp1 relProp1Value )
relsetProperty( relPropNonIndexed relPropValueNonIndexed )
Make things persistent
txsuccess()
catch ( Exception e )
txfailure()
Indexing
135
finally
txfinish()
7132 SearchThe usefulness of the auto indexing functionality comes of course from the ability to actuallyquery the index and retrieve results To that end you can acquire a ReadableIndex objectfrom the AutoIndexer that exposes all the query and get methods of a full Index lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbindexIndexhtmlgt with exactly thesame functionality Continuing from the previous example accessing the index is done like this
Get the Node auto index
ReadableIndexltNodegt autoNodeIndex = graphDbindex()getNodeAutoIndexer()getAutoIndex()
node1 and node2 both had auto indexed properties get them
assertEquals( node1
autoNodeIndexget( nodeProp1 nodeProp1Value )getSingle() )
assertEquals( node2
autoNodeIndexget( nodeProp2 nodeProp2Value )getSingle() )
node2 also had a property that should be ignored
assertFalse( autoNodeIndexget( nonIndexed
nodeProp2NonIndexedValue )hasNext() )
Get the relationship auto index
ReadableIndexltRelationshipgt autoRelIndex = graphDbindex()getRelationshipAutoIndexer()getAutoIndex()
One property was set for auto indexing
assertEquals( rel
autoRelIndexget( relProp1 relProp1Value )getSingle() )
The rest should be ignored
assertFalse( autoRelIndexget( relPropNonIndexed
relPropValueNonIndexed )hasNext() )
7133 Runtime ConfigurationThe same options that are available during database creation via the configuration can also be setduring runtime via the AutoIndexer API
Gaining access to the AutoIndexer API and adding two Node and one +Relationship properties toauto index is done like so
Start without any configuration
EmbeddedGraphDatabase graphDb = new EmbeddedGraphDatabase(
getStoreDir( testAPI ) )
Get the Node AutoIndexer set nodeProp1 and nodeProp2 as auto
indexed
AutoIndexerltNodegt nodeAutoIndexer = graphDbindex()getNodeAutoIndexer()
nodeAutoIndexerstartAutoIndexingProperty( nodeProp1 )
nodeAutoIndexerstartAutoIndexingProperty( nodeProp2 )
Get the Relationship AutoIndexer
AutoIndexerltRelationshipgt relAutoIndexer = graphDbindex()getRelationshipAutoIndexer()
relAutoIndexerstartAutoIndexingProperty( relProp1 )
None of the AutoIndexers are enabled so far Do that now
nodeAutoIndexersetEnabled( true )
relAutoIndexersetEnabled( true )
Parameters to the AutoIndexers passed through the Configuration and settings made through the APIare cumulative So you can set some beforehand known settings do runtime checks to augment the
Indexing
136
initial configuration and then enable the desired auto indexers - the final configuration is the sameregardless of the method used to reach it
7134 Updating the Auto IndexUpdates to the auto indexed properties happen of course automatically as you update them Removalof properties from the auto index happens for two reasons One is that you actually removed theproperty The other is that you stopped autoindexing on a property When the latter happens anyprimitive you touch and it has that property it is removed from the auto index regardless of anyoperations on the property When you start or stop auto indexing on a property no auto updateoperation happens currently If you need to change the set of auto indexed properties and have themre-indexed you currently have to do this by hand An example will illustrate the above better
Creating the configuration
MapltString Stringgt config = new HashMapltString Stringgt()
configput( ConfigNODE_KEYS_INDEXABLE nodeProp1 nodeProp2 )
configput( ConfigNODE_AUTO_INDEXING true )
EmbeddedGraphDatabase graphDb = new EmbeddedGraphDatabase(
getStoreDir( mutations ) config )
Transaction tx = graphDbbeginTx()
Node node1 = null node2 = null node3 = null node4 = null
try
Create the primitives
node1 = graphDbcreateNode()
node2 = graphDbcreateNode()
node3 = graphDbcreateNode()
node4 = graphDbcreateNode()
Add indexable and non-indexable properties
node1setProperty( nodeProp1 nodeProp1Value )
node2setProperty( nodeProp2 nodeProp2Value )
node3setProperty( nodeProp1 nodeProp3Value )
node4setProperty( nodeProp2 nodeProp4Value )
Make things persistent
txsuccess()
catch ( Exception e )
txfailure()
finally
txfinish()
Here both nodes are indexed To demonstrate removal we stop
autoindexing nodeProp1
AutoIndexerltNodegt nodeAutoIndexer = graphDbindex()getNodeAutoIndexer()
nodeAutoIndexerstopAutoIndexingProperty( nodeProp1 )
tx = graphDbbeginTx()
try
Indexing
137
nodeProp1 is no longer auto indexed It will be
removed regardless Note that node3 will remain
node1setProperty( nodeProp1 nodeProp1Value2 )
node2 will be auto updated
node2setProperty( nodeProp2 nodeProp2Value2 )
remove node4 property nodeProp2 from index
node4removeProperty( nodeProp2 )
Make things persistent
txsuccess()
catch ( Exception e )
txfailure()
finally
txfinish()
Verify
ReadableIndexltNodegt nodeAutoIndex = nodeAutoIndexergetAutoIndex()
node1 is completely gone
assertFalse( nodeAutoIndexget( nodeProp1 nodeProp1Value )hasNext() )
assertFalse( nodeAutoIndexget( nodeProp1 nodeProp1Value2 )hasNext() )
node2 is updated
assertFalse( nodeAutoIndexget( nodeProp2 nodeProp2Value )hasNext() )
assertEquals( node2
nodeAutoIndexget( nodeProp2 nodeProp2Value2 )getSingle() )
node3 is still there despite its nodeProp1 property not being monitored
any more because it was not touched in contrast with node1
assertEquals( node3
nodeAutoIndexget( nodeProp1 nodeProp3Value )getSingle() )
Finally node4 is removed because the property was removed
assertFalse( nodeAutoIndexget( nodeProp2 nodeProp4Value )hasNext() )
CautionIf you start the database with auto indexing enabled but different auto indexed propertiesthan the last run then already auto-indexed entities will be deleted as you work with themMake sure that the monitored set is what you want before enabling the functionality
7135 Low level detailsCurrently the AutoIndexer functionality is implemented as a TransactionEventHandlerlthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbeventTransactionEventHandlerhtmlgt that executes on beforeCommit() of every transaction TheTransactionData lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbeventTransactionDatahtmlgt object is queried for all modified (added deleted and changed)properties of the primitives supported by the AutoIndexer and adds and removes it based on thecurrent configuration This means that the auto indexing happens on successful finish() lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphdbTransactionhtmlfinish2829gtof the transaction and before that the changes are not visible
138
Chapter 8 Graph Algorithms
Neo4j graph algorithms is a component that contains Neo4j implementations of some commonalgorithms for graphs It includes algorithms like
bull Shortest paths
bull all paths
bull all simple paths
bull Dijkstra and
bull A
Graph Algorithms
139
81 IntroductionThe graph algorithms are found in the neo4j-graph-algo component which is included in thestandard Neo4j download
bull Javadocs lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphalgopackage-summaryhtmlgt
bull Download lthttpsearchmavenorgsearch7Cgav7C17Cg3A22orgneo4j2220AND20a3A22neo4j-graph-algo22gt
bull Source code lthttpsgithubcomneo4jcommunitytree14M06graph-algogt
For information on how to use neo4j-graph-algo as a dependency with Maven and other dependencymanagement tools see orgneo4jneo4j-graph-algo lthttpsearchmavenorgsearch7Cgav7C17Cg3A22orgneo4j2220AND20a3A22neo4j-graph-algo22gt Note that itshould be used with the same version of orgneo4jneo4j-kernel lthttpsearchmavenorgsearch7Cgav7C17Cg3A22orgneo4j2220AND20a3A22neo4j-kernel22gt Differentversions of the graph-algo and kernel components are not compatible in the general case Bothcomponents are included transitively by the orgneo4jneo4j lthttpsearchmavenorgsearch7Cgav7C17Cg3A22orgneo4j2220AND20a3A22neo4j22gt artifact which makesit simple to keep the versions in sync
The starting point to find and use graph algorithms is GraphAlgoFactory lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jgraphalgo
GraphAlgoFactoryhtmlgt
For examples see Section 126 ldquoGraph Algorithm examplesrdquo
140
Chapter 9 High Availability
NoteThe High Availability features are only available in the Neo4j Enterprise Edition
Neo4j High Availability or ldquoNeo4j HArdquo provides the following two main features
1 It enables a fault-tolerant database architecture where several Neo4j slave databases can beconfigured to be exact replicas of a single Neo4j master database This allows the end-user systemto be fully functional and both read and write to the database in the event of hardware failure
2 It enables a horizontally scaling read-mostly architecture that enables the system to handle moreread load than a single Neo4j database instance can handle
High Availability
141
91 ArchitectureNeo4j HA has been designed to make the transition from single machine to multi machine operationsimple by not having to change the already existing application
Consider an existing application with Neo4j embedded and running on a single machine To deploysuch an application in a multi machine setup the only required change is to switch the creation of theGraphDatabaseService from EmbeddedGraphDatabase to HighlyAvailableGraphDatabase Sinceboth implement the same interface no additional changes are required
Figure 91 Typical setup when running multiple Neo4j instances in HA mode
When running Neo4j in HA mode there is always a single master and zero or more slaves Comparedto other master-slave replication setups Neo4j HA can handle writes on a slave so there is no need toredirect writes to the master
A slave will handle writes by synchronizing with the master to preserve consistency Updates willhowever propagate from the master to other slaves eventually so a write from one slave is notimmediately visible on all other slaves This is the only difference between multiple machines runningin HA mode compared to single machine operation All other ACID characteristics are the same
High Availability
142
92 Setup and configurationNeo4j HA can be set up to accommodate differing requirements for load fault tolerance and availablehardware
Within a cluster Neo4j HA uses Apache ZooKeeper 1 for master election and propagation ofgeneral cluster and machine status information ZooKeeper can be seen as a distributed coordinationservice Neo4j HA requires a ZooKeeper service for initial master election new master election(current master failing) and to publish general status information about the current Neo4j HAcluster (for example when a machine joined or left the cluster) Read operations through theGraphDatabaseService API will always work and even writes can survive ZooKeeper failures if amaster is present
ZooKeeper requires a majority of the ZooKeeper instances to be available to operate properly Thismeans that the number of ZooKeeper instances should always be an odd number since that will makebest use of available hardware
To further clarify the fault tolerance characteristics of Neo4j HA here are a few example setups
921 Small
bull 3 physical (or virtual) machinesbull 1 ZooKeeper instance running on each machinebull 1 Neo4j HA instance running on each machine
This setup is conservative in the use of hardware while being able to handle moderate read load It canfully operate when at least 2 of the ZooKeeper instances are running Since the ZooKeeper service andNeo4j HA are running together on each machine this will in most scenarios mean that only one serveris allowed to go down
922 Medium
bull 5-7+ machinesbull ZooKeeper running on 3 5 or 7 machinesbull Neo4j HA can run on 5+ machines
This setup may mean that two different machine setups have to be managed (some machines run bothZooKeeper and Neo4j HA) The fault tolerance will depend on how many machines there are that arerunning ZooKeeper With 3 ZooKeeper instances the cluster can survive one ZooKeeper going downwith 5 it can survive 2 and with 7 it can handle 3 ZooKeeper instances failing The number of Neo4jHA instances that can fail for normal operations is theoretically all but 1 (but for each required masterelection the ZooKeeper service must be available)
923 Large
bull 8+ total machinesbull 3+ Neo4j HA machinesbull 5+ Zookeeper on separate dedicated machines
In this setup all ZooKeeper instances are running on separate machines as a dedicated ZooKeeperservice The dedicated ZooKeeper cluster can handle half of the instances minus 1 going down The
1httphadoopapacheorgzookeeper
High Availability
143
Neo4j HA cluster will be able to operate with at least a single live machine Adding more Neo4j HAinstances is very easy in this setup since Zookeeper is operating as a separate service
924 Installation NotesFor installation instructions of a High Availability cluster please visit the Neo4j Wiki 2
Note that while the HighlyAvailableGraphDatabase supports the same API as theEmbeddedGraphDatabase it does have additional configuration parameters
Table 91 HighlyAvailableGraphDatabase configuration parameters
Parameter Name Value Example value Required
ha machine_id integer gt= 0 1 yes
ha server (auto-discovered) hostamp port to bind whenacting as master
my-domain com6001 no
ha zoo_keeper_servers comma delimitedzookeeper connections
localhost2181
localhost2182
localhost2183
yes
ha pull_interval interval for pollingmaster from a slave inseconds
30 no
2httpwikineo4jorgcontentHigh_Availability_Cluster
High Availability
144
93 How Neo4j HA operatesA Neo4j HA cluster operates cooperatively coordinating activity through Zookeeper
On startup a Neo4j HA instance will connect to the ZooKeeper service to register itself and ask whois master If some other machine is master the new instance will start as slave and connect to thatmaster If the machine starting up was the first to register mdash or should become master according to themaster election algorithm mdash it will start as master
When performing a write transaction on a slave each write operation will be synchronized with themaster (locks will be acquired on both master and slave) When the transaction commits it will firstoccur on the master If the master commit is successful the transaction will be committed on the slaveas well To ensure consistency a slave has to be up to date with the master before performing a writeoperation This is built into the communication protocol between the slave and master so that updateswill happen automatically if needed
When performing a write on the master it will execute in the same way as running in normalembedded mode Currently the master will not push updates to the slave Instead slaves can beconfigured to have a pull interval Without polling updates will only happen on slaves whenever theysynchronize a write with the master
Having all writes go through slaves has the benefit that the data will be replicated on two machinesThis is recommended to avoid rollbacks in case of a master failure that could potentially happen whenthe new master is elected
Whenever a machine becomes unavailable the ZooKeeper service will detect that and remove itfrom the cluster If the master goes down a new master will automatically be elected Normally anew master is elected and started within just a few seconds and during this time no writes can takeplace (the write will throw an exception) A machine that becomes available after being unavailablewill automatically reconnect to the cluster The only time this is not true is when an old master hadchanges that did not get replicated to any other machine If the new master is elected and performschanges before the old master recovers there will two different versions of the data The old masterwill not be able to attach itself to the cluster and will require maintenance (replace the wrong versionof the data with the one running in the cluster)
All this can be summarized as
bull Slaves can handle write transactions
bull Updates to slaves are eventual consistent
bull Neo4j HA is fault tolerant and (depending on ZooKeeper setup) can continue to operate from Xmachines down to a single machine
bull Slaves will be automatically synchronized with the master on a write operation
bull If the master fails a new master will be elected automatically
bull Machines will be reconnected automatically to the cluster whenever the issue that caused the outage(network maintenance) is resolved
bull Transactions are atomic consistent and durable but eventually propagated out to other slaves
bull If the master goes down any running write transaction will be rolled back and during masterelection no write can take place
bull Reads are highly available
145
Chapter 10 Operations
This chapter describes how to maintain a Neo4j installation This includes topics such as backing upthe database and monitoring the health of the database as well as diagnosing issues
Operations
146
101 Backup
NoteThe Backup features are only available in the Neo4j Enterprise Edition
Backups are performed over the network live from a running graph database onto a local copy Thereare two types of backup full and incremental
A full backup copies the database files without acquiring any locks allowing for continued operationson the target instance This of course means that while copying transactions will continue and thestore will change For this reason the transaction that was running when the backup operation startedis noted and when the copy operation completes all transactions from the latter down to the onehappening at the end of the copy are replayed on the backup files This ensures that the backed up datarepresent a consistent and up-to-date snapshot of the database storage
In contrast incremental backup does not copy store files - instead it copies the logs of the transactionsthat have taken place since the last full or incremental backup which are then replayed over anexisting backup store This makes incremental backups far more efficient that doing full backupsevery time but they also require that a full backup has taken place before they are executed
Regardless of the mode a backup is created the resulting files represent a consistent database snapshotand they can be used to boot up a Neo4j instance
The database to be backed up is specified using a URI with syntax
ltrunning modegtlthostgt[port]lthostgt[port]
Running mode must be defined and is either single for non-HA or ha for HA clusters Thelthostgt[port] part points to a host running the database on port port if not the default The additionalhostport arguments are useful for passing multiple ZooKeeper instances
ImportantBackups can only be performed on databases which have the configuration parameterenable_online_backup=true set That will make the backup service available on thedefault port (6362) To enable the backup service on a different port use for exampleenable_online_backup=port=9999 instead
1011 Embedded and ServerTo perform a backup from a running embedded or server database run
Performing a full backup
neo4j-backup -full -from single192168134 -to mntbackupneo4j-backup
Performing an incremental backup
neo4j-backup -incremental -from single192168134 -to mntbackupneo4j-backup
Performing an incremental backup where the service is registered on a custom port
neo4j-backup -incremental -from single1921681349999 -to mntbackupneo4j-backup
1012 High AvailabilityTo perform a backup on an HA cluster you specify one or more ZooKeeper services managing thatcluster
Performing a full backup from HA cluster specifying two possible ZooKeeper services
neo4j-backup -full -from ha19216811521811921681162181 -to mntbackupneo4j-backup
Operations
147
Performing an incremental backup from HA cluster specifying only one ZooKeeper service
neo4j-backup -incremental -from ha1921681152181 -to mntbackupneo4j-backup
1013 Restoring Your DataThe Neo4j backups are fully functional databases To use a backup all you need to do replace yourdatabase folder with the backup
Operations
148
102 SecurityNeo4j in itself does not enforce security on the data level However there are different aspects thatshould be considered when using Neo4j in different scenarios
1021 Securing access to the Neo4j ServerThe Neo4j server currently does not enforce security on the REST access layer This should be takencare of by external means We strongly recommend to front a running Neo4j Server with a proxy likeApache mod_proxy 1 This provides a number of advantages
bull Control access to the Neo4j server to specific IP addresses URL patterns and IP ranges This can beused to make for instance only the dbdata namespace accessible to non-local clients while the dbadmin URLs only respond to a specific IP address
ltProxy gt
Order DenyAllow
Deny from all
Allow from 1921680
ltProxygt
bull Run Neo4j Server as a non-root user on a LinuxUnix system on a port lt 1000 (eg port 80) using
ProxyPass neo4jdbdata httplocalhost7474dbdata
ProxyPassReverse neo4jdbdata httplocalhost7474dbdata
bull Simple load balancing in a clustered environment to load-balance read load using the Apachemod_proxy_balancer 2 plugin
ltProxy balancermyclustergt
BalancerMember http19216815080
BalancerMember http19216815180
ltProxygt
ProxyPass test balancermycluster
1httphttpdapacheorgdocs22modmod_proxyhtml
Operations
149
103 Monitoring
NoteMost of the monitoring features are only available in the Advanced and Enterprise editionsof Neo4j
In order to be able to continuously get an overview of the health of a Neo4j database there aredifferent levels of monitoring facilities available
1031 JMX
How to connect to a Neo4j instance using JMX and JConsole
First start your embedded database or the Neo4j Server for instance using
$NEO4j_SERVER_HOMEbinneo4j start
Now start JConsole with
$JAVA_HOMEbinjconsole
Connect to the process running your Neo4j database instance
Figure 101 Connecting JConsole to the Neo4j Java process
Now beside the MBeans exposed by the JVM you will see an orgneo4j section in the MBeans tabUnder that you will have access to all the monitoring information exposed by Neo4j
Operations
150
Figure 102 Neo4j MBeans View
How to connect to the JMX monitoring programmatically
In order to programmatically connect to the Neo4j JMX server there are some convenience methodsin the Neo4j Management component to help you find out the most commonly used monitoringattributes of Neo4j For instance the number of node IDs in use can be obtained with code like
Neo4jManager manager = new Neo4jManager( graphDbgetManagementBean( Kernelclass ) )
long nodeIDsInUse = managergetPrimitivesBeangetNumberOfNodeIdsInUse()
Once you have access to this information you can use it to for instance expose the values to SNMPlthttpenwikipediaorgwikiSimple_Network_Management_Protocolgt or other monitoring systems
Reference of supported JMX MBeans
Table 101 MBeans exposed by the Neo4j Kernel
Name Description
orgneo4jinstance=kernel0name=MemoryMapping
The status of Neo4j memory mapping
orgneo4jinstance=kernel0name=Locking Information about the Neo4j lock status
orgneo4jinstance=kernel0name=Transactions Information about the Neo4j transaction manager
orgneo4jinstance=kernel0name=Cache Information about the caching in Neo4j
orgneo4jinstance=kernel0name=Configuration The configuration parameters used to configureNeo4j
orgneo4jinstance=kernel0name=Primitivecount
Estimates of the numbers of different kinds ofNeo4j primitives
orgneo4jinstance=kernel0name=XAResources
Information about the XA transaction manager
orgneo4jinstance=kernel0name=Store filesizes
Information about the sizes of the different partsof the Neo4j graph store
orgneo4jinstance=kernel0name=Kernel Information about the Neo4j kernel
orgneo4jinstance=kernel0name=HighAvailability
Information an High Availability cluster ifenabled
Operations
151
Table 102 MBean Memory Mapping
Attribute Description Type
MemoryPools Get information about each pool of memorymapped regions from store files withmemory mapping enabled
String
Table 103 MBean Locking
Attribute Description Type
NumberOfAdvertedDeadlocks The number of lock sequences that wouldhave lead to a deadlock situation that Neo4jhas detected and adverted (by throwingDeadlockDetectedException)
Integer
Table 104 MBean Transactions
Attribute Description Type
NumberOfOpenTransactions The number of currently open transactions Integer
PeakNumberOfConcurrentTransactions The highest number of transactions everopened concurrently
Integer
NumberOfOpenedTransactions The total number started transactions Integer
NumberOfCommittedTransactions The total number of committed transactionss Integer
Table 105 MBean Cache
Attribute Description Type
CacheType The type of cache used by Neo4j String
NodeCacheSize The number of Nodes currently in cache Integer
RelationshipCacheSize The number of Relationships currently incache
Integer
clear() clear all caches functionvoid
Table 106 MBean Configuration
Attribute Description Type
store_dir Relative path for where the Neo4j storagedirectory is located
String
rebuild_idgenerators_fast Use a quick approach for rebuilding the IDgenerators This give quicker recovery timebut will limit the ability to reuse the space ofdeleted entities
String
logical_log Relative path for where the Neo4j logicallog is located
String
neostore propertystore db index
keys mapped_memory
The size to allocate for memory mapping thestore for property key strings
String
Operations
152
Attribute Description Type
neostore propertystore db strings
mapped_memory
The size to allocate for memory mapping thestring property store
String
neostore propertystore db arrays
mapped_memory
The size to allocate for memory mapping thearray property store
String
neo_store Relative path for where the Neo4j storageinformation file is located
String
neostore relationshipstore db
mapped_memory
The size to allocate for memory mapping therelationship store
String
neostore propertystore db index
mapped_memory
The size to allocate for memory mapping thestore for property key indexes
String
create Configuration attribute String
enable_remote_shell Enable a remote shell server which shellclients can log in to
String
neostore propertystore db
mapped_memory
The size to allocate for memory mapping theproperty value store
Integer
neostore nodestore db mapped_memory The size to allocate for memory mapping thenode store
String
dir Configuration attribute String
Table 107 MBean Primitive count
Attribute Description Type
NumberOfNodeIdsInUse An estimation of the number of nodes usedin this Neo4j instance
Integer
NumberOfRelationshipIdsInUse An estimation of the number of relationshipsused in this Neo4j instance
Integer
NumberOfPropertyIdsInUse An estimation of the number of propertiesused in this Neo4j instance
Integer
NumberOfRelationshipTypeIdsInUse The number of relationship types used inthis Neo4j instance
Integer
Table 108 MBean XA Resources
Attribute Description Type
XaResources Information about all XA resourcesmanaged by the transaction manager
String
Table 109 MBean Store file sizes
Attribute Description Type
TotalStoreSize The total disk space used by this Neo4jinstance in bytes
Integer
LogicalLogSize The amount of disk space used by thecurrent Neo4j logical log in bytes
Integer
Operations
153
Attribute Description Type
ArrayStoreSize The amount of disk space used to store arrayproperties in bytes
Integer
NodeStoreSize The amount of disk space used to storenodes in bytes
Integer
PropertyStoreSize The amount of disk space used to storeproperties (excluding string values and arrayvalues) in bytes
Integer
RelationshipStoreSize The amount of disk space used to storerelationships in bytes
Integer
StringStoreSize The amount of disk space used to storestring properties in bytes
Integer
Table 1010 MBean Kernel
Attribute Description Type
ReadOnly Whether this is a read only instance boolean
MBeanQuery An ObjectName that can be used as a queryfor getting all management beans for thisNeo4j instance
String
KernelStartTime The time from which this Neo4j instancewas in operational mode
Date
StoreCreationDate The time when this Neo4j graph store wascreated
Date
StoreId An identifier that uniquely identifies thisNeo4j graph store
String
StoreLogVersion The current version of the Neo4j storelogical log
String
KernelVersion The version of Neo4j String
StoreDirectory The location where the Neo4j store islocated
String
Table 1011 MBean High Availability
Attribute Description Type
MachineId The cluster machine id of this instance String
Master True if this Neo4j instance is currentlyMaster in the cluster
boolean
ConnectedSlaves A list of conencted slaves in this cluster String
InstancesInCluster Information about the other Neo4j instancesin this HA cluster
String
Part II Tutorials
155
Chapter 11 Graph Database Concepts
Graph Database Concepts
156
111 What is a Graph DatabaseA graph database stores data in a graph the most generic of data structures capable of elegantlyrepresenting any kind of data in a highly accessible way Letrsquos follow along some graphs using themto express graph concepts Wersquoll ldquoreadrdquo a graph by following arrows around the diagram to formsentences
1111 A Graph contains Nodes and RelationshipsldquoA Graph mdashrecords data inndashgt Nodes mdashwhich havendashgt Propertiesrdquo
The simplest possible graph is a single Node a record that has named values referred to as PropertiesA Node could start with a single Property and grow to a few million though that can get a littleawkward At some point it makes sense to distribute the data into multiple nodes organized withexplicit Relationships
Graph
Nodes
records data in Relat ionships
records data in
Propert ies
have
organize
have
1112 Relationships organize the GraphldquoNodes mdashare organized byndashgt Relationships mdashwhich also havendashgt Propertiesrdquo
Relationships organize Nodes into arbitrary structures allowing a Graph to resemble a List a Treea Map or a compound Entity ndash any of which can be combined into yet more complex richly inter-connected structures
1113 Query a Graph with a TraversalldquoA Traversal mdashnavigatesndashgt a Graph it mdashidentifiesndashgt Paths mdashwhich orderndashgt Nodesrdquo
Graph Database Concepts
157
A Traversal is how you query a Graph navigating from starting Nodes to related Nodes according toan algorithm finding answers to questions like ldquowhat music do my friends like that I donrsquot yet ownrdquoor ldquoif this power supply goes down what web services are affectedrdquo
Traversal
Graph
navigates
Paths
ident ifies
Algorithm
expresses
Relat ionships
Nodes
organize
records data in
records data in order
1114 Indexes look-up Nodes or RelationshipsldquoAn Index mdashmaps fromndashgt Properties mdashto eitherndashgt Nodes or Relationshipsrdquo
Often you want to find a specific Node or Relationship according to a Property it has Rather thantraversing the entire graph use an Index to perform a look-up for questions like ldquofind the Account forusername master-of-graphsrdquo
Graph Database Concepts
158
Indexes
Relat ionships
m ap to
Nodes
m ap to
Propert ies
m ap fromorganize
have
have
1115 Neo4j is a Graph DatabaseldquoA Graph Database mdashmanages andashgt Graph and mdashalso manages relatedndashgt Indexesrdquo
Neo4j is a commercially supported open-source graph database It was designed and built from theground-up to be a reliable database optimized for graph structures instead of tables Working withNeo4j your application gets all the expressiveness of a graph with all the dependability you expectout of a database
Graph Database Concepts
159
Graph Database
Graph
m anages
Indexes
m anages
Relat ionships
records data in
Nodes
records data in
m ap to
m ap to
Propert ies
m ap from organize
have
have
Traversal
navigates
Paths
ident ifies
Algorithm
expresses
order
Graph Database Concepts
160
112 Comparing Database ModelsA Graph Database stores data structured in the Nodes and Relationships of a graph How does thiscompare to other persistence models Because a graph is a generic structure letrsquos compare how a fewmodels would look in a graph
1121 A Graph Database transforms a RDBMSTopple the stacks of records in a relational database while keeping all the relationships and yoursquoll seea graph Where an RDBMS is optimized for aggregated data Neo4j is optimized for highly connecteddata
Figure 111 RDBMS
A1
A2
A3
B1
B2
B3
B4
B5
B6
B7
C1
C2
C3
Figure 112 Graph Database as RDBMS
A1
B1B2
A2
B4B6
A3
B3B5 B7
C1 C2C3
1122 A Graph Database elaborates a Key-Value StoreA Key-Value model is great for lookups of simple values or lists When the values are themselvesinterconnected yoursquove got a graph Neo4j lets you elaborate the simple data structures into morecomplex interconnected data
Graph Database Concepts
161
Figure 113 Key-Value Store
K1
K2
K3
V1
K2
V2
K1
K3
V3
K1
Figure 114 Graph Database as Key-Value Store
V1
V2
V3K1
K2
K3
1123 A Graph Database relates Column-FamilyColumn Family (BigTable-style) databases are an evolution of key-value using families to allowgrouping of rows Stored in a graph the families could become hierarchical and the relationshipsamong data becomes explicit
1124 A Graph Database navigates a Document StoreThe container hierarchy of a document database accommodates nice schema-free data that can easilybe represented as a tree Which is of course a graph Refer to other documents (or document elements)within that tree and you have a more expressive representation of the same data When in Neo4j thoserelationships are easily navigable
Graph Database Concepts
162
Figure 115 Document Store
D1
S1
D2
S2S3
V1D2S2 V2V3V4D1S1
Figure 116 Graph Database as Document Store
D1
S1D2 S2S3
V1
V2
V3
V4
Graph Database Concepts
163
113 The Neo4j Graph DatabaseThis chapter will introduce more details on the data model and behavior of Neo4j
1131 RelationshipsRelationships between nodes are a key part of a graph database They allow for finding related data
A Relat ionship
Start node
has a
End node
has a
Relat ionship type
has a
Nam e
uniquely ident ified by
A relationship connects two nodes and is guaranteed to have valid start and end nodes
Start node End noderelat ionship
As relationships are always directed they can be viewed as outgoing or incoming relative to a nodewhich is useful when traversing the graph
Nodeincom ing relat ionship outgoing relat ionship
Relationships are equally well traversed in either direction This means that there is no need to addduplicate relationships in the opposite direction (with regard to traversal or performance)
While relationships always have a direction you can ignore the direction where it is not useful in yourapplication
Note that a node can have relationships to itself as well
Node loop
To further enhance graph traversal all relationships have a relationship type The following exampleshows a simple social network with two relationship types
Graph Database Concepts
164
Maja
Oscar
follows follows
William
blocks
Alice
follows
Table 111 Using relationship direction and type
What How
get who a person follows outgoing follows relationships depth one
get the followers of a person incoming follows relationships depth one
get who a person blocks outgoing blocks relationships depth one
get who a person is blocked by incoming blocks relationships depth one
This example is a simple model of a file system which includes symbolic links
A
B
file
C
file
D
sym bolic link nam e E
file
Depending on what you are looking for you will use the direction and type of relationships duringtraversal
Graph Database Concepts
165
What How
get the full path of a file incoming file relationships
get all paths for a file incoming file and symbolic link relationships
get all files in a directory outgoing file and symbolic link relationshipsstop at depth one
get all files in a directory excluding symboliclinks
outgoing file relationships stop at depth one
get all files in a directory recursively outgoing file and symbolic link relationships
1132 PropertiesProperties are key-value pairs where the key is a string Property values can be either a primitive or anarray of one primitive type For example String int and int[] values are valid for properties
Notenull is not a valid property value Nulls can instead be modeled by the absence of a key
A Property
Key
has a
Value
has a
Prim it ive
boolean
byte
short
int
long
float
double
char
St ring
is acan be acan be an array of
Table 112 Property value types
Type Description Value range
boolean truefalse
Graph Database Concepts
166
Type Description Value range
byte 8-bit integer -128 to 127 inclusive
short 16-bit integer -32768 to 32767 inclusive
int 32-bit integer -2147483648 to 2147483647 inclusive
long 64-bit integer -9223372036854775808 to9223372036854775807 inclusive
float 32-bit IEEE 754 floating-point number
double 64-bit IEEE 754 floating-point number
char 16-bit unsigned integers representingUnicode characters
u0000 to uffff (0 to 65535)
String sequence of Unicode characters
For further details on floatdouble values see Java Language Specification lthttpjavasuncomdocsbooksjlsthird_editionhtmltypesValueshtml423gt
167
Chapter 12 Using Neo4j embedded in Java applications
Using Neo4j embedded in Java applications
168
121 Include Neo4j in your projectAfter selecting the appropriate edition for your platform embed Neo4j in your Java application byincluding the Neo4j library jars in your build
1211 Add Neo4j to the build pathGet the Neo4j libraries from one of these sources
bull Extract a Neo4j download lthttpneo4jorgdownloadgt ziptarball and use the jar files found inthe lib directory
bull Use the jar files available from Maven Central Repository lthttpsearchmavenorgsearch|ga|1|g3A22orgneo4j22gt
Add the jar files to your project
JDK toolsAppend to -classpath
Eclipse
bull Right-click on the project and then go Build Path ndashgt Configure Build Path In the dialogchoose Add External JARs browse to the Neo4j lib directory and select all of the jar files
bull Another option is to use User Libraries lthttphelpeclipseorgheliosindexjsptopic=orgeclipsejdtdocuserreferencepreferencesjavabuildpathref-preferences-user-librarieshtmgt
IntelliJ IDEASee Libraries Global Libraries and the Configure Library dialog lthttpwwwjetbrainscomideawebhelplibraries-global-libraries-and-the-configure-library-dialoghtmlgt
NetBeans
bull Right-click on the Libraries node of the project choose Add JARFolder browse to the Neo4jlib directory and select all of the jar files
bull You can also handle libraries from the proejct node see Managing a Projectrsquos Classpath lthttpnetbeansorgkbdocsjavaproject-setuphtmlprojects-classpathgt
1212 Add Neo4j as a dependencyFor an overview of the main Neo4j artifacts see Table 12 ldquoNeo4j editionsrdquo The artifacts listed thereare top-level artifacts that will transitively include the actual Neo4j implementation You can either gowith the top-level artifact or include the individual components directly The examples included hereuse the top-level artifact approach
Maven
Maven dependency
ltprojectgt
ltdependenciesgt
ltdependencygt
ltgroupIdgtorgneo4jltgroupIdgt
ltartifactIdgtneo4jltartifactIdgt
ltversiongt$neo4j-versionltversiongt
ltdependencygt
ltdependenciesgt
Using Neo4j embedded in Java applications
169
ltprojectgt
Where $neo4j-version is the intended version and the artifactId is found in Table 12 ldquoNeo4jeditionsrdquo
IvyMake sure to resolve dependencies from Maven Central for example using this configuration in yourivysettingsxml file
ltivysettingsgt
ltsettings defaultResolver=maingt
ltresolversgt
ltchain name=maingt
ltfilesystem name=localgt
ltartifact pattern=$ivysettingsdirrepository[artifact]-[revision][ext] gt
ltfilesystemgt
ltibiblio name=maven_central root=httprepo1mavenorgmaven2 m2compatible=truegt
ltchaingt
ltresolversgt
ltivysettingsgt
With that in place you can add Neo4j to the mix by having something along these lines to your ivyxmlfile
ltdependenciesgt
ltdependency org=orgneo4j name=neo4j rev=$neo4j-versiongt
ltdependenciesgt
Where $neo4j-version is the intended version and the name is found in Table 12 ldquoNeo4jeditionsrdquo
Using Neo4j embedded in Java applications
170
122 Hello worldCreate and access nodes and relationships
To begin with we define the relationship types we want to use
private static enum ExampleRelationshipTypes implements RelationshipType
EXAMPLE
The next step is to start the database server
GraphDatabaseService graphDb = new EmbeddedGraphDatabase( DB_PATH )
registerShutdownHook( graphDb )
As seen we register a shutdown hook that will make sure the database shuts down when the JVMexits Now itrsquos time to interact with the database
Encapsulate operations in a transaction
Transaction tx = graphDbbeginTx()
try
Node firstNode = graphDbcreateNode()
firstNodesetProperty( NAME_KEY Hello )
Node secondNode = graphDbcreateNode()
secondNodesetProperty( NAME_KEY World )
firstNodecreateRelationshipTo( secondNode
ExampleRelationshipTypesEXAMPLE )
String greeting = firstNodegetProperty( NAME_KEY ) +
+ secondNodegetProperty( NAME_KEY )
Systemoutprintln( greeting )
At this point this is how the database looks
In this case wersquoll remove the data before committing
lets remove the data before committing
firstNodegetSingleRelationship( ExampleRelationshipTypesEXAMPLE
DirectionOUTGOING )delete()
firstNodedelete()
secondNodedelete()
txsuccess()
finally
txfinish()
Finally shut down the database server when the application finishes
Using Neo4j embedded in Java applications
171
graphDbshutdown()
Full source code EmbeddedNeo4jjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrcmainjavaorgneo4jexamplesEmbeddedNeo4jjavagt
Using Neo4j embedded in Java applications
172
123 User database with indexYou have a user database and want to retrieve users by name To begin with this is the structure ofthe database we want to create
Figure 121 Node space view of users
That is the reference node is connected to a users-reference node to which all users are connected
To begin with we define the relationship types we want to use
private static enum RelTypes implements RelationshipType
USERS_REFERENCE
USER
Then we have created two helper methods to handle user names and adding users to the database
private static String idToUserName( final int id )
return user + id + neo4jorg
private static Node createAndIndexUser( final String username )
Node node = graphDbcreateNode()
nodesetProperty( USERNAME_KEY username )
nodeIndexadd( node USERNAME_KEY username )
return node
The next step is to start the database server
graphDb = new EmbeddedGraphDatabase( DB_PATH )
nodeIndex = graphDbindex()forNodes( nodes )
registerShutdownHook()
Itrsquos time to add the users
Transaction tx = graphDbbeginTx()
try
Create users sub reference node (see design guidelines on
httpwikineo4jorg )
Using Neo4j embedded in Java applications
173
Node usersReferenceNode = graphDbcreateNode()
graphDbgetReferenceNode()createRelationshipTo(
usersReferenceNode RelTypesUSERS_REFERENCE )
Create some users and index their names with the IndexService
for ( int id = 0 id lt 100 id++ )
Node userNode = createAndIndexUser( idToUserName( id ) )
usersReferenceNodecreateRelationshipTo( userNode
RelTypesUSER )
And herersquos how to find a user by Id
int idToFind = 45
Node foundUser = nodeIndexget( USERNAME_KEY
idToUserName( idToFind ) )getSingle()
Systemoutprintln( The username of user + idToFind + is
+ foundUsergetProperty( USERNAME_KEY ) )
Full source code EmbeddedNeo4jWithIndexingjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrcmainjavaorgneo4jexamplesEmbeddedNeo4jWithIndexingjavagt
Using Neo4j embedded in Java applications
174
124 Traversal
1241 The MatrixThis is the first node space we want to traverse into
Figure 122 Matrix node space view
Friends and friends of friends
private static Traverser getFriends( final Node person )
return persontraverse( OrderBREADTH_FIRST
StopEvaluatorEND_OF_GRAPH
ReturnableEvaluatorALL_BUT_START_NODE RelTypesKNOWS
DirectionOUTGOING )
Letrsquos perform the actual traversal and print the results
Traverser friendsTraverser = getFriends( neoNode )
int numberOfFriends = 0
for ( Node friendNode friendsTraverser )
Systemoutprintln( At depth
+ friendsTraversercurrentPosition()
depth() + =gt
+ friendNodegetProperty( name ) )
Who coded the Matrix
private static Traverser findHackers( final Node startNode )
return startNodetraverse( OrderBREADTH_FIRST
StopEvaluatorEND_OF_GRAPH new ReturnableEvaluator()
Override
public boolean isReturnableNode(
final TraversalPosition currentPos )
return currentPosisStartNode()
ampamp currentPoslastRelationshipTraversed()
Using Neo4j embedded in Java applications
175
isType( RelTypesCODED_BY )
RelTypesCODED_BY DirectionOUTGOING RelTypesKNOWS
DirectionOUTGOING )
Print out the result
Traverser traverser = findHackers( getNeoNode() )
int numberOfHackers = 0
for ( Node hackerNode traverser )
Systemoutprintln( At depth + traversercurrentPosition()
depth() + =gt + hackerNodegetProperty( name ) )
Full source code MatrixTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesMatrixTestjavagt
1242 User rolesHere we have users assigned to groups and groups containing other groups This is the full nodespace of our example
Figure 123 User roles node space view
Get the admins
Node admins = getGroupByName( Admins )
Traverser traverser = adminstraverse(
TraverserOrderBREADTH_FIRST StopEvaluatorEND_OF_GRAPH
ReturnableEvaluatorALL_BUT_START_NODE RoleRelsPART_OF
DirectionINCOMING RoleRelsMEMBER_OF DirectionINCOMING )
for ( Node part traverser )
Systemoutprintln( partgetProperty( NAME )
+
+ ( traversercurrentPosition()depth() - 1 ) )
Get the group memberships of a user
Node jale = getUserByName( Jale )
Traverser traverser = jaletraverse( TraverserOrderDEPTH_FIRST
StopEvaluatorEND_OF_GRAPH
Using Neo4j embedded in Java applications
176
ReturnableEvaluatorALL_BUT_START_NODE RoleRelsMEMBER_OF
DirectionOUTGOING RoleRelsPART_OF DirectionOUTGOING )
for ( Node membership traverser )
Systemoutprintln( membershipgetProperty( NAME )
+
+ ( traversercurrentPosition()depth() - 1 ) )
Get all groups
Node referenceNode = graphDbgetReferenceNode()
Traverser traverser = referenceNodetraverse(
TraverserOrderBREADTH_FIRST StopEvaluatorEND_OF_GRAPH
ReturnableEvaluatorALL_BUT_START_NODE RoleRelsROOT
DirectionINCOMING RoleRelsPART_OF DirectionINCOMING )
for ( Node group traverser )
Systemoutprintln( groupgetProperty( NAME ) )
Get all members of all groups
Node referenceNode = graphDbgetReferenceNode()
Traverser traverser = referenceNodetraverse(
TraverserOrderBREADTH_FIRST StopEvaluatorEND_OF_GRAPH
new ReturnableEvaluator()
Override
public boolean isReturnableNode(
TraversalPosition currentPos )
if ( currentPosisStartNode() )
return false
Relationship rel = currentPoslastRelationshipTraversed()
return relisType( RoleRelsMEMBER_OF )
RoleRelsROOT
DirectionINCOMING RoleRelsPART_OF DirectionINCOMING
RoleRelsMEMBER_OF DirectionINCOMING )
for ( Node group traverser )
Systemoutprintln( groupgetProperty( NAME ) )
Full source code RolesTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesRolesTestjavagt
1243 New traversal framework
NoteThe following examples use a new experimental traversal API It shares the underlyingimplementation with the old traversal API so performance-wise they should be equalHowever expect the new API to evolve and thus undergo changes
The Matrix
The traversals from the Matrix example above this time using the new traversal API
Friends and friends of friends
Using Neo4j embedded in Java applications
177
private static Traverser getFriends( final Node person )
TraversalDescription td = Traversaldescription()
breadthFirst()
relationships( RelTypesKNOWS DirectionOUTGOING )
evaluator( EvaluatorsexcludeStartPosition() )
return tdtraverse( person )
Letrsquos perform the actual traversal and print the results
Traverser friendsTraverser = getFriends( neoNode )
int numberOfFriends = 0
for ( Path friendPath friendsTraverser )
Systemoutprintln( At depth + friendPathlength() + =gt
+ friendPathendNode()
getProperty( name ) )
Who coded the Matrix
private static Traverser findHackers( final Node startNode )
TraversalDescription td = Traversaldescription()
breadthFirst()
relationships( RelTypesCODED_BY DirectionOUTGOING )
relationships( RelTypesKNOWS DirectionOUTGOING )
evaluator(
EvaluatorsreturnWhereLastRelationshipTypeIs( RelTypesCODED_BY ) )
return tdtraverse( startNode )
Print out the result
Traverser traverser = findHackers( getNeoNode() )
int numberOfHackers = 0
for ( Path hackerPath traverser )
Systemoutprintln( At depth + hackerPathlength() + =gt
+ hackerPathendNode()
getProperty( name ) )
Full source code MatrixNewTravTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesMatrixNewTravTestjavagt
User roles
The traversals from the User roles example above this time using the new traversal API
Get the admins
Node admins = getGroupByName( Admins )
TraversalDescription td = Traversaldescription()
breadthFirst()
relationships( RoleRelsPART_OF DirectionINCOMING )
relationships( RoleRelsMEMBER_OF DirectionINCOMING )
evaluator( EvaluatorsexcludeStartPosition() )
for ( Path path tdtraverse( admins ) )
Node part = pathendNode()
Systemoutprintln( partgetProperty( NAME ) +
+ ( pathlength() - 1 ) )
Using Neo4j embedded in Java applications
178
Get the group memberships of a user
Node jale = getUserByName( Jale )
TraversalDescription td = Traversaldescription()
depthFirst()
relationships( RoleRelsMEMBER_OF DirectionOUTGOING )
relationships( RoleRelsPART_OF DirectionOUTGOING )
evaluator( EvaluatorsexcludeStartPosition() )
for ( Path path tdtraverse( jale ) )
Node membership = pathendNode()
Systemoutprintln( membershipgetProperty( NAME ) +
+ ( pathlength() - 1 ) )
Get all groups
Node referenceNode = graphDbgetReferenceNode()
TraversalDescription td = Traversaldescription()
breadthFirst()
relationships( RoleRelsROOT DirectionINCOMING )
relationships( RoleRelsPART_OF DirectionINCOMING )
evaluator( EvaluatorsexcludeStartPosition() )
for ( Node group tdtraverse( referenceNode )
nodes() )
Systemoutprintln( groupgetProperty( NAME ) )
Get all members of all groups
Node referenceNode = graphDbgetReferenceNode()
TraversalDescription td = Traversaldescription()
breadthFirst()
relationships( RoleRelsROOT DirectionINCOMING )
relationships( RoleRelsMEMBER_OF DirectionINCOMING )
relationships( RoleRelsPART_OF DirectionINCOMING )
evaluator(
EvaluatorspruneWhereLastRelationshipTypeIs( RoleRelsMEMBER_OF ) )
for ( Node group tdtraverse( referenceNode )nodes() )
Systemoutprintln( groupgetProperty( NAME ) )
Full source code RolesNewTravTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesRolesNewTravTestjavagt
Walking an ordered path
This example shows how to use a path context holding a representation of a path
Create a toy graph
Node A = dbcreateNode()
Node B = dbcreateNode()
Node C = dbcreateNode()
Node D = dbcreateNode()
AcreateRelationshipTo( B REL1 )
BcreateRelationshipTo( C REL2 )
CcreateRelationshipTo( D REL3 )
AcreateRelationshipTo( C REL2 )
Using Neo4j embedded in Java applications
179
Figure 124 The example graph
Now the order of relationships (REL1 ndashgt REL2 ndashgt REL3) is stored in an ArrayList Upon traversalthe Evaluator can check against it to ensure that only paths are included and returned that have thepredefined order of relationships
Walk the path
final ArrayListltRelationshipTypegt orderedPathContext = new ArrayListltRelationshipTypegt()
orderedPathContextadd( REL1 )
orderedPathContextadd( withName( REL2 ) )
orderedPathContextadd( withName( REL3 ) )
TraversalDescription td = Traversaldescription()evaluator(
new Evaluator()
Override
public Evaluation evaluate( final Path path )
if ( pathlength() == 0 )
return EvaluationEXCLUDE_AND_CONTINUE
String currentName = pathlastRelationship()getType()name()
String relationshipType = orderedPathContextget(
pathlength() - 1 )name()
if ( pathlength() == orderedPathContextsize() )
if ( currentNameequals( relationshipType ) )
return EvaluationINCLUDE_AND_PRUNE
else
return EvaluationEXCLUDE_AND_PRUNE
else
if ( currentNameequals( relationshipType ) )
return EvaluationEXCLUDE_AND_CONTINUE
else
return EvaluationEXCLUDE_AND_PRUNE
)
Traverser t = tdtraverse( dbgetNodeById( 1 ) )
for ( Path path t )
Using Neo4j embedded in Java applications
180
Systemoutprintln( path )
Full source code OrderedPathTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesorderedpathOrderedPathTestjavagt
1244 Social network
NoteThe following example uses the new experimental traversal API
Social networks (know as social graphs out on the web) are natural to model with a graph Thisexample shows a very simple social model that connects friends and keeps track of status updates
Simple social model
Figure 125 Social network data model
The data model for a social network is pretty simple Persons with names and StatusUpdates withtimestamped text These entities are then connected by specific relationships
bull Person
bull friend relates two distinct Person instances (no self-reference)
bull status connects to the most recent StatusUpdate
bull StatusUpdate
bull next points to the next StatusUpdate in the chain which was posted before the current one
Status graph instance
The StatusUpdate list for a Person is a linked list The head of the list (the most recent status) isfound by following status Each subsequent StatusUpdate is connected by next
Herersquos an example where Andreas Kollegger micro-blogged his way to work in the morning
Using Neo4j embedded in Java applications
181
Figure 126 Andreas Kolleggers status updates
To read the status updates we can create a traversal like so
TraversalDescription traversal = Traversaldescription()
depthFirst()
relationships( NEXT )
filter( TraversalreturnAll() )
This gives us a traverser that will start at one StatusUpdate and will follow the chain of updatesuntil they run out Traversers are lazy loading so itrsquos performant even when dealing with thousands ofstatuses - they are not loaded until we actually consume them
Activity streamOnce we have friends and they have status messages we might want to read our friends statusmessages in reverse time order - latest first To do this we go through these steps
1 Gather all friendrsquos status update iterators in a list - latest date first2 Sort the list3 Return the first item in the list4 If the first iterator is exhausted remove it from the list Otherwise get the next item in that iterator5 Go to step 2 until there are no iterators left in the list
Animated the sequence looks like this lthttpwwwslidesharenetsystaypattern-activity-streamgt
The code looks like
PositionedIteratorltStatusUpdategt first = statusesget(0)
StatusUpdate returnVal = firstcurrent()
if ( firsthasNext() )
statusesremove( 0 )
else
firstnext()
Using Neo4j embedded in Java applications
182
sort()
return returnVal
Full source code socnet lthttpsgithubcomneo4jcommunitytree14M06embedded-examplessrcmainjavaorgneo4jexamplessocnetgt
Using Neo4j embedded in Java applications
183
125 Domain entitiesThis page demonstrates one way to handle domain entities when using Neo4j The principle at use isto wrap the entities around a node (the same approach can be used with relationships as well)
First off store the node and make it accessible inside the package
private final Node underlyingNode
Person( Node personNode )
thisunderlyingNode = personNode
protected Node getUnderlyingNode()
return underlyingNode
Delegate attributes to the node
public String getName()
return (String)underlyingNodegetProperty( NAME )
Make sure to override these methods
Override
public int hashCode()
return underlyingNodehashCode()
Override
public boolean equals( Object o )
return o instanceof Person ampamp
underlyingNodeequals( ( (Person)o )getUnderlyingNode() )
Override
public String toString()
return Person[ + getName() + ]
Full source code Personjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrcmainjavaorgneo4jexamplessocnetPersonjavagt
Using Neo4j embedded in Java applications
184
126 Graph Algorithm examplesCalculating the shortest path (least number of relationships) between two nodes
Node startNode = graphDbcreateNode()
Node middleNode1 = graphDbcreateNode()
Node middleNode2 = graphDbcreateNode()
Node middleNode3 = graphDbcreateNode()
Node endNode = graphDbcreateNode()
createRelationshipsBetween( startNode middleNode1 endNode )
createRelationshipsBetween( startNode middleNode2 middleNode3 endNode )
Will find the shortest path between startNode and endNode via
MY_TYPE relationships (in OUTGOING direction) like fex
(startNode)--gt(middleNode1)--gt(endNode)
PathFinderltPathgt finder = GraphAlgoFactoryshortestPath(
TraversalexpanderForTypes( ExampleTypesMY_TYPE DirectionOUTGOING ) 15 )
IterableltPathgt paths = finderfindAllPaths( startNode endNode )
Using Dijkstrarsquos algorithm lthttpenwikipediaorgwikiDijkstra27s_algorithmgt to calculatecheapest path between node A and B where each relationship can have a weight (ie cost) and thepath(s) with least cost are found
PathFinderltWeightedPathgt finder = GraphAlgoFactorydijkstra(
TraversalexpanderForTypes( ExampleTypesMY_TYPE DirectionBOTH ) cost )
WeightedPath path = finderfindSinglePath( nodeA nodeB )
Get the weight for the found path
pathweight()
Using A lthttpenwikipediaorgwikiA_search_algorithmgt to calculate the cheapest path betweennode A and B where cheapest is for example the path in a network of roads which has the shortestlength between node A and B Herersquos our example graph
Node nodeA = createNode( name A x 0d y 0d )
Node nodeB = createNode( name B x 7d y 0d )
Node nodeC = createNode( name C x 2d y 1d )
Relationship relAB = createRelationship( nodeA nodeC length 2d )
Relationship relBC = createRelationship( nodeC nodeB length 3d )
Relationship relAC = createRelationship( nodeA nodeB length 10d )
EstimateEvaluatorltDoublegt estimateEvaluator = new EstimateEvaluatorltDoublegt()
public Double getCost( final Node node final Node goal )
double dx = (Double) nodegetProperty( x ) - (Double) goalgetProperty( x )
double dy = (Double) nodegetProperty( y ) - (Double) goalgetProperty( y )
double result = Mathsqrt( Mathpow( dx 2 ) + Mathpow( dy 2 ) )
return result
Using Neo4j embedded in Java applications
185
PathFinderltWeightedPathgt astar = GraphAlgoFactoryaStar(
TraversalexpanderForAllTypes()
CommonEvaluatorsdoubleCostEvaluator( length ) estimateEvaluator )
WeightedPath path = astarfindSinglePath( nodeA nodeB )
Full source code PathFindingExamplesTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesPathFindingExamplesTestjavagt
Using Neo4j embedded in Java applications
186
127 Reading a management attributeReading a management attribute
The EmbeddedGraphDatabase lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jkernelEmbeddedGraphDatabasehtmlgt class includes a convenience method lthttpcomponentsneo4jorgneo4j14M06apidocsorgneo4jkernelEmbeddedGraphDatabasehtmlgetManagementBean28javalangClass29gt to get instances of Neo4j management beans The common JMX servicecan be used as well but from your code you probably rather want to use the approach outlined here
This example shows how to get the start time of a database
private static Date getStartTimeFromManagementBean(
GraphDatabaseService graphDbService )
use EmbeddedGraphDatabase to access management beans
EmbeddedGraphDatabase graphDb = (EmbeddedGraphDatabase) graphDbService
Kernel kernel = graphDbgetManagementBean( Kernelclass )
Date startTime = kernelgetKernelStartTime()
return startTime
Depending on which Neo4j edition you are using different sets of management beans are available
bull For all editions see the orgneo4jjmx lthttpcomponentsneo4jorgneo4j-jmx14M06apidocsorgneo4jjmxpackage-summaryhtmlgt package
bull For the Advanced and Enterprise editions see the orgneo4jmanagement lthttpcomponentsneo4jorgneo4j-management14M06apidocsorgneo4jmanagementpackage-summaryhtmlgt package as well
Full source code JmxTestjava lthttpsgithubcomneo4jcommunityblob14M06embedded-examplessrctestjavaorgneo4jexamplesJmxTestjavagt
Part III Tools
188
Chapter 13 Web Administration
The Neo4j Web Administration is the primary user interface for Neo4j With it you can
bull monitor the Neo4j Server
bull manipulate and browse data
bull interact with the database via various consoles
bull view raw data management objects (JMX MBeans)
Web Administration
189
131 Dashboard tabThe Dashboard tab provides an overview of a running Neo4j instance
Figure 131 Web Administration Dashboard
1311 Entity chartThe charts show entity counts over time node relationship and properties
Figure 132 Entity charting
1312 Status monitoringBelow the entity chart is a collection of status panels displaying current resource usage
Figure 133 Status indicator panels
Web Administration
190
132 Data tabUse the Data tab to browse add or modify nodes relationships and their properties
Figure 134 Browsing and manipulating data
Figure 135 Editing properties
Web Administration
191
133 Console tabThe Console tab gives
bull scripting access to the database via the Gremlin lthttpgremlintinkerpopcomgt scripting engine
bull query access via Cypher
bull HTTP access via the HTTP console
Figure 136 Traverse data with Gremlin
Figure 137 Query data with Cypher
Web Administration
192
Figure 138 Interact over HTTP
Web Administration
193
134 The Server Info tabThe Server Info tab provides raw access to all available management objects (see Section 103ldquoMonitoringrdquo for details)
Figure 139 JMX Attributes
194
Chapter 14 Neo4j Shell
Neo4j shell is a command-line shell for browsing the graph much like how the Unix shell along withcommands like cd ls and pwd can be used to browse your local file system It consists of two parts
bull a lightweight client that sends commands via RMI and
bull a server that processes those commands and sends the result back to the client
Itrsquos a nice tool for development and debugging This guide will show you how to get it going
Neo4j Shell
195
141 Starting the shellWhen used together with Neo4j started as a server simply issue the following at the command line
binneo4j-shell
For the full list of options see the reference in the Shell manual page
To connect to a running Neo4j database use Section 1414 ldquoRead-only moderdquo for local databasesand see Section 1411 ldquoEnabling the shell serverrdquo for remote databases
You need to make sure that the shell jar file is on the classpath when you start up your Neo4j instance
1411 Enabling the shell serverShell is enabled from the configuration of the Neo4j kernel see Section 52 ldquoServer ConfigurationrdquoHerersquos some sample configurations
Using default values
enable_remote_shell = true
or specify custom port use default values for the others
enable_remote_shell = port=1234
When using the Neo4j server see Section 52 ldquoServer Configurationrdquo for how to add configurationsettings in that case
There are two ways to start the shell either by connecting to a remote shell server or by pointing it toa Neo4j store path
1412 Connecting to a shell serverTo start the shell and connect to a running server run
neo4j-shell
Alternatively supply -port and -name options depending on how the remote shell server was enabledThen yoursquoll get the shell prompt like this
neo4j-sh (0)$
1413 Pointing the shell to a pathTo start the shell by just pointing it to a Neo4j store path you run the shell jar file Given that the rightneo4j-kernel-ltversiongtjar and jta jar files are in the same path as your neo4j-shell-ltversiongtjar fileyou run it with
$ neo4j-shell -path pathtoneo4j-db
1414 Read-only modeBy issuing the -readonly switch when starting the shell with a store path changes cannot be made tothe database during the session
$ neo4j-shell -readonly -path pathtoneo4j-db
1415 Run a command and then exitIt is possible to tell the shell to just start execute a command and then exit This opens up for uses ofbackground jobs and also handling of huge output of fex an ls command where you then could pipethe output to less or another reader of your choice or even to a file So some examples of usage
$ neo4j-shell -c cd -a 24 ampamp set name Mattias
Neo4j Shell
196
$ neo4j-shell -c trav -r KNOWS | less
Neo4j Shell
197
142 Passing options and argumentsPassing options and arguments to your commands is very similar to many CLI commands in an nixenvironment Options are prefixed with a - and can contain one or more options Some options expecta value to be associated with it Arguments are string values which arenrsquot prefixed with - Letrsquos lookat ls as an example
ls -r -f KNOWSout -v 12345 will make a verbose listing of node 12345s outgoing relationshipsof type KNOWS The node id 12345 is an argument to ls which tells it to do the listing on that nodeinstead of the current node (see pwd command) However a shorter version of this can be written
ls -rfv KNOWSout 12345 Here all three options are written together after a single - prefix Eventhough f is in the middle it gets associated with the KNOWSout value The reason for this is that the lscommand doesnrsquot expect any values associated with the r or v options So it can infer the right valuesfor the rights options
Neo4j Shell
198
143 Enum optionsSome options expects a value which is one of the values in an enum fex direction part ofrelationship type filtering where therersquos INCOMING OUTGOING and BOTH All such values can besupplied in an easier way Itrsquos enough that you write the start of the value and the interpreter will findwhat you really meant Fex out in i or even INCOMING
Neo4j Shell
199
144 FiltersSome commands makes use of filters for varying purposes Fex -f in ls and in trav A filter issupplied as a json lthttpwwwjsonorggt object (w or wo the surrounding brackets Both keysand values can contain regular expressions for a more flexible matching An example of a filter couldbe urlhttpneo4jnameNeo4j The filter option is also accompanied by the options -i and -l which stands for ignore case (ignore casing of the characters) and loose matching (itrsquosconsidered a match even if the filter value just matches a part of the compared value not necessarilythe entire value) So for a case-insensitive loose filter you can supply a filter with -f -i -l or -filfor short
Neo4j Shell
200
145 Node titlesTo make it easier to navigate your graph the shell can display a title for each node fex in ls -r Itwill display the relationships as well as the nodes on the other side of the relationships The title isdisplayed together with each node and its best suited property value from a list of property keys
If yoursquore standing on a node which has two KNOWS relationships to other nodes itrsquod be difficult toknow which friend is which The title feature addresses this by reading a list of property keys andgrabbing the first existing property value of those keys and displays it as a title for the node So youmay specify a list (with or without regular expressions) fex nametitlecaption and the titlefor each node will be the property value of the first existing key in that list The list is defined by theclient (you) using the TITLE_KEYS environment variable and the default being nametitle
Neo4j Shell
201
146 How to use (individual commands)The shell is modeled after Unix shells like bash that you use to walk around your local file systemIt has some of the same commands like cd and ls When you first start the shell (see instructionsabove) you will get a list of all the available commands Use man ltcommandgt to get more info about aparticular command Some notes
1461 Current noderelationship and pathYou have a current noderelationship and a current path (like a current working directory in bash)that yoursquove traversed so far You start at the reference node lthttpapineo4jorgcurrentorgneo4jgraphdbGraphDatabaseServicehtmlgetReferenceNode()gt and can then cd your way through thegraph (check your current path at any time with the pwd command) cd can be used in different ways
bull cd ltnode-idgt will traverse one relationship to the supplied node id The node must have a directrelationship to the current node
bull cd -a ltnode-idgt will do an absolute path change which means the supplied node doesnrsquot have tohave a direct relationship to the current node
bull cd -r ltrelationship-idgt will traverse to a relationship instead of a node The relationshipmust have the current node as either start or end point To see the relationship ids use the ls -vrcommand on nodes
bull cd -ar ltrelationship-idgt will do an absolute path change which means the relationship can beany relationship in the graph
bull cd will take you back to the reference node where you started in the first placebull cd will traverse back one step to the previous location removing the last path item from your
current path (pwd)bull cd start (only if your current location is a relationship) Traverses to the start node of the
relationshipbull cd end (only if your current location is a relationship) Traverses to the end node of the
relationship
1462 Listing the contents of a noderelationshipList contents of the current noderelationship (or any other node) with the ls command Please notethat it will give an empty output if the current noderelationship has no properties or relationships (forexample in the case of a brand new graph) ls can take a node id as argument as well as filters seeSection 144 ldquoFiltersrdquo and for information about how to specify direction see Section 143 ldquoEnumoptionsrdquo Use man ls for more info
1463 Creating nodes and relationshipsYou create new nodes by connecting them with relationships to the current node For examplemkrel -t A_RELATIONSHIP_TYPE -d OUTGOING -c will create a new node (-c) and draw to it anOUTGOING relationship of type A_RELATIONSHIP_TYPE from the current node If you already have twonodes which yoursquod like to draw a relationship between (without creating a new node) you can do forexample mkrel -t A_RELATIONSHIP_TYPE -d OUTGOING -n ltother-node-idgt and it will justcreate a new relationship between the current node and that other node
1464 Setting renaming and removing propertiesProperty operations are done with the set mv and rm commands These commands operates on thecurrent noderelationship set ltkeygt ltvaluegt with optionally the -t option (for value type) sets aproperty Supports every type of value that Neo4j supports Examples of a property of type int
Neo4j Shell
202
$ set -t int age 29
And an example of setting a double[] property
$ set -t double[] my_values [1412213]
Example of setting a String property containing a JSON string
mkrel -c -d i -t DOMAIN_OF --np appfoobar
bull rm ltkeygt removes a property
bull mv ltkeygt ltnew-keygt renames a property from one key to another
1465 Deleting nodes and relationshipsDeleting nodes and relationships is done with the rmrel command It focuses on deletion ofrelationships but a node can also be deleted if the deleted relationship leaves the opposite nodestranded (ie it no longer has any relationships drawn to it) and the -d options is supplied See therelationship ids with the ls -rv command
1466 Environment variablesThe shell uses environment variables a-la bash to keep session information such as the current pathand more The commands for this mimics the bash commands export and env For example youcan at anytime issue a export STACKTRACES=true command to set the STACKTRACES environmentvariable to true This will then result in stacktraces being printed if an exception or error shouldoccur List environment variables using env
1467 Executing groovypython scriptsThe shell has support for executing scripts such as Groovy lthttpgroovycodehausorggt andPython lthttpwwwpythonorggt (via Jython lthttpwwwjythonorggt) As of now the scripts(groovy py) must exist on the server side and gets called from a client with for examplegsh --renamePerson 1234 Mathias Mattias --doSomethingElse where the scriptsrenamePersongroovy and doSomethingElsegroovy must exist on the server side in any of the pathsgiven by the GSH_PATH environment variable (defaults to srcsrcscript) This variable is like thejava classpath separated by a The pythonjython scripts can be executed with the jsh in a similarfashion however the scripts have the py extension and the environment variable for the paths isJSH_PATH
When writing the scripts assume that therersquos made available an args variable (a String[]) whichcontains the supplied arguments In the case of the renamePerson example above the array wouldcontain [1234 Mathias Mattias] Also please write your outputs to the out variable suchas outprintln( My tracing text ) so that it will be printed at the shell client instead of theserver
1468 TraverseYou can traverse the graph with the trav command which allows for simple traversing from thecurrent node You can supply which relationship types (w regex matching) and optionally directionas well as property filters for matching nodes In addition to that you can supply a command line toexecute for each match An example trav -o depth -r KNOWSbothHAS_incoming -c ls$n Which means traverse depth first for relationships with type KNOWS disregarding direction andincoming relationships with type matching HAS_ and do a ls ltmatching nodegt for each matchThe node filtering is supplied with the -f option see Section 144 ldquoFiltersrdquo See Section 143 ldquoEnum
Neo4j Shell
203
optionsrdquo for the traversal order option Even relationship typesdirections are supplied using the sameformat as filters
1469 Query with CypherYou can use Cypher to query the graph For that use the start command
bull start n = (0) return n will give you a listing of the node with ID 0
14610 IndexingItrsquos possible to query and manipulate indexes via the index command Example index -i personsname (will index the name for the current node or relationship in the persons index)
bull -g will do exact lookup in the index and display hits You can supply -c with a command to beexecuted for each hit
bull -q will ask the index a query and display hits You can supply -c with a command to be executedfor each hit
bull --cd will change current location to the hit from the query Itrsquos just a convenience for using the -coption
bull --ls will do a listing of the contents for each hit Itrsquos just a convenience for using the -c option
bull -i will index a key-value pair in an index for the current noderelationship If no value is given theproperty value for that key for the current node is used as value
bull -r will remove a key-value pair (if it exists) from an index for the current noderelationship If novalue is given the property value for that key for the current node is used as value
Neo4j Shell
204
147 Extending the shell Adding your own commandsOf course the shell is extendable and has a generic core which has nothing to do with Neo4jhellip onlysome of the commands lthttpcomponentsneo4jorgneo4j-shell14M06apidocsorgneo4jshellApphtmlgt do
So you say yoursquod like to start a Neo4j graph database lthttpapineo4jorgcurrentorgneo4jgraphdbGraphDatabaseServicehtmlgt enable the remote shell and add your own apps to it so that your appsand the standard Neo4j apps co-exist side by side Well herersquos an example of how an app could looklike
public class LsRelTypes extends GraphDatabaseApp
Override
protected String exec( AppCommandParser parser Session session Output out )
throws ShellException RemoteException
GraphDatabaseService graphDb = getServer()getDb()
outprintln( Types )
for ( RelationshipType type graphDbgetRelationshipTypes() )
outprintln( typename() )
return null
You make your app discoverable via the Java Service API so in a file eg srcmainresourcesMETA-INFservicesorgneo4jshellApp include orgmydomainMyShellApp
And you could now use it in the shell by typing lsreltypes (its name is based on the class name)
If yoursquod like it to display some nice help information when using the help (or man) app override thegetDescription method for a general description and use addValueType method to add descriptionsabout (and logic to) the options you can supply when using your app
Know that the apps reside server-side so if you have a running server and starts a remote client to itfrom another JVM you canrsquot add your apps on the client
Neo4j Shell
205
148 An example shell session where are we
pwd
Current is (0)
(0)
On the current node set the key name to value Jon
set name Jon
send a cypher query
start n=(0) return n
+----------------------+
| n |
+----------------------+
| Node[0]name-gtJon |
+----------------------+
1 rows 42 ms
make an incoming relationship of type LIKES create the end node with the node properties specified
mkrel -c -d i -t LIKES --np appfoobar
where are we
ls
name =[Jon]
(me) lt-[LIKES]-- (1)
change to the newly created node
cd 1
list relationships including relationshship id
ls -avr
(me) --[LIKES0]-gt (0)
create one more KNOWS relationship and the end node
mkrel -c -d i -t KNOWS --np nameBob
print current history stack
pwd
Current is (1)
(0)--gt(1)
verbose list relationships
ls -avr
(me) lt-[KNOWS1]-- (2)
(me) --[LIKES0]-gt (0)
Part IV Troubleshooting
207
Chapter 15 Troubleshooting guide
Problem Cause Resolution
OutOfMemoryError Too large top leveltransactions or leakingtransactions not finishedproperly
Split updates into smallertransactions Always makesure transactions are finishedproperly
ResourceAcquisitionFailedExceptionor an error message containing the textldquoThe transaction is marked for rollbackonlyrdquo
Leaked non finishedtransaction tied to the currentthread in state marked forrollback only
Finish transactions properly
DeadlockDetectedException Concurrent updates ofcontended resources ornot finishing transactionsproperly
See Section 34ldquoDeadlocksrdquo
208
Chapter 16 Community support
Get help from the Neo4j open source community here are some starting points
bull Searchable user mailing list archive lthttpwwwmail-archivecomuserlistsneo4jorginfohtmlgt
bull User mailing list lthttpslistsneo4jorgmailmanlistinfousergt
bull Neo4j wiki lthttpwikineo4jorggt
bull IRC channel ircircfreenodenetneo4j
209
Appendix A Manpages
The Neo4j Unix manual pages are included on the following pages
Manpages
210
Nameneo4j mdash Neo4j Server control and management
Synopsisneo4j ltcommandgt
DESCRIPTIONNeo4j is a graph database perfect for working with highly connected data
COMMANDS
consoleStart the server as an application running as a foreground proces Stop the server using CTRL-C
startStart server as daemon running as a background process
stopStops a running daemonized server
restartRestarts the server
statusCurrent running state of the server
installInstalls the server as a platform-appropriate system service
removeUninstalls the system service
infoDisplays configuration information such as the current NEO4J_HOME and CLASSPATH
Usage - WindowsNeo4jbat
Double-clicking on the Neo4jbat script will start the server in a console To quit just press control-C in the console window
Neo4jbat installremove
Neo4j can be installed and run as a Windows Service running without a console window Yoursquollneed to run the scripts with Administrator priveleges Just use the Neo4jbat script with the properargument
bull Neo4jbat install - install as a Windows service
bull will install the service
bull Neo4jbat remove - remove the Neo4j service
bull will stop and remove the Neo4j service
bull Neo4jbat start - will start the Neo4j service
bull will start the Neo4j service if installed or a console
bull session otherwise
bull Neo4jbat stop - stop the Neo4j service if running
Manpages
211
bull Neo4jbat restart - restart the Neo4j service if installed
bull Neo4jbat status - report on the status of the Neo4j service
bull returns RUNNING STOPPED or NOT INSTALLED
FILES
confneo4j-serverpropertiesServer configuration
confneo4j-wrapperconfConfiguration for service wrapper
confneo4jpropertiesTuning configuration for the database
Manpages
212
Nameneo4j-shell mdash a command-line tool for exploring and manipulating a graph database
Synopsisneo4j-shell [REMOTE OPTIONS]
neo4j-shell [LOCAL OPTIONS]
DESCRIPTIONNeo4j shell is a command-line shell for browsing the graph much like how the Unix shell alongwith commands like cd ls and pwd can be used to browse your local file system The shell canconnect directly to a graph database on the file system To access local a local database used by otherprocesses use the readonly mode
REMOTE OPTIONS
-port PORTPort of host to connect to (default 1337)
-host HOSTDomain name or IP of host to connect to (default localhost)
-name NAMERMI name ie rmilthostgtltportgtltnamegt (default shell)
-readonlyAccess the database in read-only mode The read-only mode enables browsing a database that isused by other processes
LOCAL OPTIONS
-path PATHThe path to the database directory If there is no database at the location a new one will e created
-pid PIDProcess ID to connect to
-readonlyAccess the database in read-only mode The read-only mode enables browsing a database that isused by other processes
-c COMMANDCommand line to execute After executing it the shell exits
-config CONFIGThe path to the Neo4j configuration file to be used
EXAMPLESExamples for remote
neo4j-shell
neo4j-shell -port 1337
neo4j-shell -host 1921681234 -port 1337 -name shell
neo4j-shell -host localhost -readonly
Examples for local
neo4j-shell -path pathtodb
Manpages
213
neo4j-shell -path pathtodb -config pathtoneo4jconfig
neo4j-shell -path pathtodb -readonly
Manpages
214
Nameneo4j-coordinator mdash Neo4j Coordinator for High-Availability clusters
Synopsisneo4j-coordinator ltcommandgt
DESCRIPTIONNeo4j Coordinator is a server which provides coordination for a Neo4j High Availability Data clusterA coordination cluster must be started and available before the data cluster can be started Thisserver is a member of the cluster
COMMANDS
consoleStart the server as an application running as a foreground proces Stop the server using CTRL-C
startStart server as daemon running as a background process
stopStops a running daemonized server
restartRestarts a running server
condrestartRestarts a server but only if it was already running
statusCurrent running state of the server
installInstalls the server as a platform-appropriate system service
removeUninstalls the system service
dumpDisplays thread dump also saved to the wrapperlog
FILES
confcoordcfgCoordination server configuration
confcoord-wrappercfgConfiguration for service wrapper
datacoordinatormyidUnique identifier for coordinator instance
Manpages
215
Nameneo4j-coordinator-shell mdash Neo4j Coordinator Shell interactive interface
Synopsisneo4j-coordinator-shell -server lthostportgt [ltcmdgt ltargsgt]
DESCRIPTIONNeo4j Coordinator Shell provides an interactive text-based interface to a running Neo4j Coordinatorserver
OPTIONS
-server HOSTPORTConnects to a Neo4j Coordinator at the specified host and port