Monday, 25 July 2011

Neo4j: Super-Nodes and Indexed Relationships, Part I

As part of my recent work for Open Credo, I have been involved in the project that was using Neo4J Graph database for application storage.
Neo4J is one of the first graph databases to appear on the global market. Being open source, in addition to its power and simplicity in supporting graph data model it represents good choice for production-ready graph database.
However, there has been one area I have struggled to get good-enough performance from Neo4j recently – super nodes.
Super nodes represent nodes with dense relationships (100K or more), which are quickly becoming bottlenecks in graph traversal algorithms when using Neo4J. I have tried many different approaches to get around this problem, but introduction of auto indexing in Neo4j 1.4 gave me an idea that I had success with. The approach I took is to try to fetch relationships of the super nodes using Lucene indexes, instead of using standard Neo APIs. In this entry I’ll share what I managed to achieve and how.
To start, let’s generate a sample graph with super-nodes. Here is the amount of generated data:
  • 5 nodes representing cities/towns (for example “London”,  “Manchester”, “Edinburgh”, “Cambridge” and “Oxford”)
  • Each city node has “IS_IN” relationship to a country node UK, (every city is related to a country node with IS_IN relationship, and we have only one country node - UK)
  • We have 100K users, and each of the users have a “HAS_VISITED” relationship to each of the five cities. I know this is not a likely scenario, but in a large data set (say among all Facebook users) you will find more then 5 cities that more then 100K users have visited
  • That’s in total 100,006 nodes (100K users+5 cities + 1 UK country node) and 500,005 relationships (100K users-HAS)_VISITED-5 cities + 5 cities IS_IN UK)
That’s not a huge amount of data, but it’s large enough to start with.
Let’s say that we want to load “IS_IN” relationships for a given city node. It’s quite simple thing to do using Neo API:

Listing 1: Iterating through node relationships using standard Neo4j API

Iterable relationships =
for (Relationship r : relationships) {

How long does this take for a single city node? I have run this code snipped repeatedly 10 times (to account for the cache hits in subsequent runs), and here are the results:

Table 1: Performance of fetching relationships from super-node with 100K relationships, using standard Neo4J API

Time elapsed (ms)

The first time the relationship is fetched, it takes 1.6 seconds. Each subsequent request remarkably takes less then 1 ms! We can thank Neo4j’s caching and mapped memory mechanism for this increase in speed (or the developers who implemented it to be more precise).
But I was still worried about the performance of the  first run. For a single relationship fetched (there is only one “IS_IN” relationship for each city node), 1.6 seconds seems a lot. The reason for the poor performance is that a city node has 100,001 relationships in total, and only one of those is of type IS_IN. In order to fetch the right one, Neo4j engine will have to look at all the relationships, then compare their types, and return only those that match the requested type.
While the system would perform well when the cache warms up, this can still cause a problem if you often access “cold” parts of the graph. While Neo4j tries to keep most of the data in caches or mapped-memory, this cannot always be achieved. When the graph is to large to fit in entirely If the super-nodes cannot be kept in memory all the time (either because there is too many of them, or the data more frequently accessed takes all cache/mapped memory available), then the performance will be adversely affected.
In terms of large data systems 100K relationships per node is not an awful lot. What would happen if you have super nodes with 1M relationships? Let’s see for ourselves!
I’m going to keep 5 city nodes in the graph, with each one having one IS_IN relationship with the UK country node. But I’ll increase number of users to 1,000,000. And assume that each user visitied each of 5 cities. So we’ll have 1,000,001 relationships per city node. I repeated the code from listing 1 to fetch the relationships of type IS_IN (there will be only one), and repeat it 10 times to see the results when cache kicks in. Table 2 shows the results.

Table 2: Performance of fetching relationships from super-node with 1M relationships, using standard Neo4J API

Time elapsed (millis):

The first time run is now close to 5 seconds, with subsequent calls which hit the cache still taking less then 1ms!
The performance degradation is not linear (with input increased 10 times, the time was only 3 times longer) – and that’s good. When its warm, the system works well with sub-ms responses.
But sometimes our requirements do not allow for the warming-up time. If you have a traversal that needs to pass through 10 super nodes, you may be getting close to 1 min a traversal. If you have a batch job that has to process 100K such traversals, and the data set is such that it cannot be stored in memory all the time, it may take 100K minutes, or more then a month to complete! What can we do to improve this?
One option can be to deploy HA Neo4j cluster, and partition calculation across the cluster. I haven’t tried this, and depending on your data set size and requirements it may be a viable solution.
But we’re going to concentrate on the simpler solution here: how can we fetch only relationships of the required type, ignoring the huge number of relationship of other types that we’re not interested in. We’re going to use Neo4j’s built-in Lucene indexing support to fetch the required relationships from the index directly. In order to do that, we’ll need to add the relationship type to the index whenever new relationship is created.
Firstly, we are going to configure Neo4J ‘s relationship auto-indexing capability by adding following properties to the file, as listing 2 illustrates.

Listing 2: Configuring relationship auto indexing in file


We are enabling the relationship auto-indexing using relationship_auto_indexing, property, and we are going to tell Neo to track and index property name type of every relationship created.
We have to make a slight change to our data generator and set the type property for every relationship we create:

Listing 3: Creating relationship with the type name as property, to enable relationship auto-indexing

DynamicRelationshipType relType = DynamicRelationshipType.withName("IS_IN");
Relationship isA = city.createRelationshipTo(ukCountry, relType);
DynamicRelationshipType hasVisited = DynamicRelationshipType.withName("HAS_VISITED");
Relationship rel = user.createRelationshipTo(city, hasVisited);

Having inserted the data for all 1M users, we are going to fetch IS_IN relationships for a single city node using auto index:

Listing 4: Creating relationship with the type name as property, to enable relationship auto-indexing

Iterable relationships = autoIndex.query("type", "IS_IN", city, null);

for (Relationship r : relationships) {

Now let’s measure how long loading the relationships from the index takes – as in the previous runs, we will fetch the relationships 10 times to allow the cache to wam up. Table 3 shows the results:

Table 3: Performance of fetching relationships from super-node with 1M relationships, using relationship auto-indexing 

Execution: 1 2 34 5 6 7 8 9 10
Time elapsed (millis):12 <1 <1 1 <1 <1 <1 1 <1 <1

Thanks to the Lucene index, the “cold” fetch has taken only 12ms on this run. The subsequent calls are still very quick, although slightly slower than before, as now we see a few 1ms times among majority of sub ms calls.
In the previous example we saw how we can ensure a more efficient lookup of relationships of particular type.  Where we are interested in traversal operations ensuring we retrieve only the relationships we are interested in traversing requires the use of a custom RelationshipExpander . The code in listing listing 5 shows an implementation of the relationship expander which ensures we use the Lucene index to retrieve relationships of a specified type.

Listing 5: Implementation of the IndexedRelationshipExpander that uses Lucene index to fetch relationships for node

public class IndexedRelationshipExpander implements RelationshipExpander{
private final GraphDatabaseService graphDatabaseService;
private final RelationshipType relationshipType;
private final Direction direction;

private IndexedRelationshipExpander(GraphDatabaseService graphDatabaseService, RelationshipType relationshipType, Direction direction) {
this.relationshipType = relationshipType;
this.graphDatabaseService = graphDatabaseService;
this.direction = direction;

public static IndexedRelationshipExpander create(GraphDatabaseService graphDatabaseService, RelationshipType relationshipType, Direction direction){
return new IndexedRelationshipExpander(graphDatabaseService, relationshipType, direction); #1

public Iterable expand(Node node) {
Iterable hits = null;

ReadableRelationshipIndex autoIndex = this.graphDatabaseService.index().getRelationshipAutoIndexer().getAutoIndex();
switch (this.direction){
hits = autoIndex.query("type",, node, null); #2
hits = autoIndex.query("type",, null, node); #3
case BOTH:
IndexHits out = autoIndex.query("type",, node, null);
IndexHits in = autoIndex.query("type",, null, node);
hits = Iterables.concat(out, in); #4
return hits;

public RelationshipExpander reversed() {
return new IndexedRelationshipExpander(graphDatabaseService, relationshipType, direction.reverse());

In order to access the index, the IndexedRelationshipExpander requires a reference to the GraphDatabaseService. In addition, we need to provide the relationship type and direction we are interested in to the IndexedRelationshipExpander (#1). The implementation of the  expand() method simply checks the direction of the relationship, and queries the relationship auto-index (#2, #3 – the difference is only in the startNode/endNode arguments). Where we need relationships in both directions, we have to perform two separate searches one for incoming and one for outgoing relationships. Then we need to concatenate the two results,  in the example this is done using the Google Guava library (#4)
And that’s all. We can now traverse the relationships of the specified type  using the new relationship expander:

Listing 6: Using custom IndexedRelationshipExpander in Neo4J Traversal API

RelationshipType relationshiptype = DynamicRelationshipType.withName("IS_IN");
Direction direction = Direction.OUTGOING;
TraversalDescription traversal = Traversal.description().
evaluator(Evaluators.atDepth(1)).expand(IndexedRelationhipExpande.create(this.embeddedGraphDatabase, relationshipType, direction));

NOTE that you have to have indexed type property on every relationship, which contain the name of the relationship type so the IndexedRelationshipExpander works correctlyGiven this basic implementation of a RelationshipExpander, it’s easy to adapt it for you specific requirements. For example, you can index the creation_date property for every relationship and then traverse only relationships created after a given date. You can include any indexed relationship property when creating a Lucene query, and implement it in the RelationshipExpander.expand() method.
We have now seen how we can use Lucene indexing to quickly fetch and traverse  a small subset of the relationships on the super node.  The effectiveness of this approach is however dependent on you being interested in only a small proportion of the relationships.  In the next blog entry we will explore how we can efficiently load a larger number of relationships from a supernode.
n.b. I used Neo4j 1.4 release to run samples described in this blog. The indexed relationship expander described wont work with earlier version of Neo4J as it depends on auto indexing capabilities on Neo4j.All tests are performed on 2.66GHz i7 MacBook Pro with 8GB RAM memory. Java heap size was set to 2GB and default Neo4J mapped memory settings were used. 
n.b.b.  There has been some development around super-node traversal improvements from the Neo4J guys, it can be found here Once I try the new features, I'll let you know here in one of the next blog entries.
NOTE: The second part of this blog entry, which covers fetching large number of relationships from a super node, is now available here


  1. Hi,
    First of all thanks for the good post ;)
    I came across the same problem in Bio4j project ( and was thinking of indexing relationships by hand.
    I guess with this new auto-indexing feature will be easier; still I don't like much the thing with indexing relationships... I'd rather have a more powerful mechanism implemented at core level that allowed distinguishing between different relationship types at a decent speed.


  2. Hi,

    nice post.
    I adapted this post and realized it using the sones GraphDB. This has the advantage that the edges will not be indexed. So you can address the edges of the cities directly. That is why it doesn't matter if there are 100k or 500M edges on those supernodes. Here are my results:

    If you have any questions contact me via or via twitter -> cosh23

    Greetings, Henning.

  3. @Henning: Your results bury that you are comparing a persistent graph database with an in-memory solution. You did not say anything about the deserialization of the edges or hyperedges and as far as I know your database has to deserialze the entire vertex to access any data stored within.


  4. @AchimFriedland: well, that's not the point. My post was about architecture and not the speed of InMemory graphs. I wanted to make clear that there is a significant speedup when using PropertyIDs for certain edges. So that you are able to request the "IS_IN" edge in exactly ONE step and not to search all edges for it.
    Yes, you are right... an InMemory-solution is faster than a persistent one. But even a InMemory-version of the scenario described above would have to search that 100001 edges for the desired one. So it would also be slower than the version I brought forward.

    If you have any questions concerning the architecture:

    Greetings, Henning.

  5. Because the admin of this web page is working, no question
    very rapidly it will be well-known, due to its feature contents.

    my homepage ... book of ra online spielen

  6. Hi! Someone in my Myspace group shared this site
    with us so I came to give it a look. I'm definitely enjoying the information. I'm book-marking and
    will be tweeting this to my followers! Superb blog and great style and design.

    My homepage; book of ra kostenlos f�roid

  7. I every time spent my half an hour to read this webpage's articles or reviews all the time along with a cup of coffee.

    my web site :: book of ra download chip online

  8. Tebrikler siteniz çok güzel olmuş

  9. I take pleasure in, result in I discovered exactly what
    I used to be having a look for. You've ended my 4 day long
    hunt! God Bless you man. Have a great day. Bye

    my weblog Nike Free 5.0 V4

  10. Wonderful article! That is the type of information that
    should be shared around the net. Shame on Google for no longer positioning this submit higher!
    Come on over and visit my website . Thank you =)

    Have a look at my page liftderma (

  11. Hi there to all, how is the whole thing, I think every
    one is getting more from this site, and your views are nice designed for new users.

    My blog post ... buy a house in the uk

  12. Hey! This post could not be writteen any better! Reading this post reminds me of my good old room mate!
    He always kept chatging about this. I will forward
    this page tto him. Fairly certain he willl have a good
    read. Thank you for sharing!

    Look into my website :: throne rush hack ios (

  13. Link exchange is nothing else but it is just placing the other person's
    webpage link on your page at suitable place and other person will
    also do same in support of you.

    Feel free to surf to my web site ... best only

  14. Therefore, taking too many times in the bloodstream.
    Too much protein to turn to be willing to release amino acids are the side-effects which result
    from many strength training as a one pound of the title.

    And no, you can save money and shed regulate of the adult exercises are working out.

    Look into my webpage ... best protein powder

  15. Hi! Do you know if they make any plugins to help with SEO?
    I'm trying to get my blog to rank for some targeted
    keywords but I'm not seeing very good gains. If you know of any please share.

    Here is my web-site; protein shakes for weight loss

  16. Artificial baits include spoons, jigs, ribbon baits, rattler baits & streamer baits.
    For instance at a time when anglers where sticking rigidly to the mantra of 3 to 5 milliliters of flavour, plus 1 to 2 milliliters
    of intense sweetener to a pound of base mix or more, as measured
    by 4 large eggs or 6 medium eggs as a basis of
    measurement, I tried other approaches and reaped big rewards against much more
    experienced anglers. If you are getting ready to go deep-sea fishing,
    there are a few things you might want to know about sea fishing bait.

    Feel free to visit my web site dunnage how to do box braids

  17. What's up colleagues, nice article and fastidious urging commented at this place, Iamm actuhally ennjoying by these.

    my web blog :: lokaal autorijschool

  18. The Fragment x Air Jordan 1 is already a rare sneaker, but there's a version out there white nike huarache that's even tougher to track down than the retail one.
    He's made use of the Nike Air Force 1 roshe runs High silhouette, which wasn't previously available. Clark's design manages to show off a pretty wide range of what's available nike huarache women on a roshe run all black pair of Bespokes by virtue of its "WTF" approach that doesn't appear to have any two pieces on the sneakers using the same material �C save for the soles, which are both white/gum.
    That the winners are selected nike free run 5.0 randomly seems to suggest that timing won't be an issue. If that's the case, people trying to game the nike air huarache system with bots, which complete the checkout process faster than a human possibly can, wouldn't necessarily have an advantage. black huarache Of course, Nike still needs a way to limit how many times people can enter the drawings �C each nike roshe run men user has to have a Nike+ account and a verified phone number, so that should help.

  19. moncler jackets,
    ugg uk,
    ralph lauren,
    black friday deals,
    canada goose jackets,
    michael kors outlet,
    nike air max shoes,
    ralph lauren shirts,
    michael kors outlet,
    tiffany outlet,
    swarovski jewelry,
    montblanc pens,
    louis vuitton handbags,
    abercrombie and fitch,
    louis vuitton handbags,
    dansko outlet,
    michael kors handbags,
    adidas outlet store,
    oakley sunglasses,
    ray ban sunglasses,
    north face outlet,
    longchamp handbags,

  20. Our football agent is one of the leading and reliable companies betting in Indonesia that provides assurance services to our customers for decades.bola tangkas

  21. articles that add insight, thanks

  22. This is a great article. It gave me a lot of useful information. thank you very much.
    happy wheels demo , happy wheels , zombie tsunami apk , retrica download , retrica apk

  23. I like the post format as you create user engagement in the complete article. It seems round up of all published posts. Thanks for gauging the informative posts.

  24. Marion Cotillard Is Everything You Dreamed She’d Be
    Preparing for a phone call with Marion Cotillard is a multimedia experience. Hours not spent indulging La Vie en Michael Kors Jewelry Rose daydreams and compulsively rewatching the Macbeth trailer in which Cotillard plays the Lady (to Michael Fassbender’s Macbeth) will Michael Kors Handbags On Sale be devoted to sifting through Google image search results for the inelegant but apt prompt “Marion Cotillard Style.” From 2015 Michael Kors the infinite issuing scroll comes back-baring red carpet gowns, gingham promo-party frocks, the occasional cocktail-hour Bermuda short, and every michael kors outlet online sale so often a candid snippet of wrapped-up airport-wear (usually set off by a cherubic toddler in tow)—a wardrobe suggesting Michael Kors Drawstring Bags a rare combination of ladylike daring. By which I mean to imply that one does not just prepare, one michael kors uk

  25. Hi there! This short article couldn’t become created any benefit! Experiencing this information reminds me associated with my personal past flatmate! He / she regularly retained talking concerning this. Let me forward this kind of publish to help him. Rather a number of he will use a excellent read. I get pleasure from you with regard to revealing!

  26. Company detecting leaks in Riyadh
    A famous company n Riyadh
    we have all kind of things you need
    (Detect water leaks_Isolating surfaces_The elimination of insects_Spraying pesticides_Aqueous thermal insulation)
    Our company El-harmeen is a Limited company It was Founded in Riyadh in 2011
    since we were working in Riyadh people loved our Services
    with you will find what ever you want
    our number is 0530464144
    our website
    [url=] شركة كشف تسربات المياه بالاحساء [/url]

    شركة كشف تسربات المياه بالاحساء
    كشف تسربات المياه بالاحساء
    شركة عزل اسطح بالاحساء
    شركة عزل خزانات المياه بالاحساء
    شركه عزل مائى بالاحساء
    شركة عزل حرارى بالاحساء
    شركة ترميم منازل بالاحساء
    شركة مكافحة حشرات بالاحساء
    شركة رش مبيدات بالاحساء
    شركة تسليك مجارى بالاحساء
    شركة ترميم منازل بالاحساء