“show the latest ….” is a common prefix to user stories these days. Others have noted the same and given this symptom a moniker; ”The real time web“. Typically we just throw things into a table with an indexed timestamp column and query accordingly.
In jo4neo, finding the most recent additions requires two simple steps:
- annotation your type with @neo(recency=true)
- use the ObjectGraph.getMostRecent() method to retrieve the latest inserts.
In this small example, we’re indicating to jo4neo that we’d like it to remember our “Post” inserts in most recent order.
@neo(recency=true)
public class Post extends NeoBean
{
...
Let’s step back and pretend we’ve been given a quick assignment in our C programming class. We’ve been asked to allow the user to enter strings, and at any given point, allow the user to ask for the latest “n” inputs given. Basically we want the last thing in to be the first thing out…LIFO. That reminds us of the stack we just learned about, and after an hour of happy coding, we have a solution.
neo4j is a natural at storing stacks, queues, or any structure that can be composed from simple linked lists. One simple technique for remembering new nodes in LIFO ordering is to build a linked list, inserting from the head. Here’s the jo4neo that performs this head insertion:
private void recencyStack(Node newNode, Node metanode) {
Node latest=null;
for(Relationship r : metanode.getRelationships(
JO4NEO_NEXT_MOST_RECENT, Direction.OUTGOING)) {
latest = r.getEndNode();
r.delete();
}
if (latest!=null)
newNode.createRelationshipTo(latest,
JO4NEO_NEXT_MOST_RECENT);
metanode.createRelationshipTo(newNode,
JO4NEO_NEXT_MOST_RECENT);
}
The HubAction.java class demonstrates how easy it becomes to query for the most recent additions of a particular class. In this case we’re getting 5 blog posts to show on the “hub” or front page.