AnormCypher is a really cool library I came across as I was exploring how to easily interact with my Neo4j node graph from my Scala application…
The library was actually built by a local engineer, Wes Freeman , and he’s been extremely helpful since I started using the code…he actually helped me with this exact feature and I thought I’d share.
Scala has a nice way of easily creating immutable objects in Scala called case classes. If you are unsure of why immutability is important, check out this blog post that does an excellent job of explaining. One of the best things about using case classes is that you can use pattern matching in a very powerful way. I won’t spend a ton of time explaining pattern matching, but for non-Scala users, pattern matching is an easy way to match a value or type against cases (much like switch in Java), and subsequently provide an expression that in our case will affect the creation of an object.
In my project, I used anormcypher to easily execute cypher queries against neo4j, and handle the resulting data within my Scala application. Here is an example of how you might go about executing a query via anormcypher that returns a collection of CypherRow objects:
In this particular example, you can see a query executed to retrieve scores from a node graph. The collect() method from the anormcypher api is called, which returns a collection of anormcypher CypherRow objects. Through pattern matching we are able to create a list of Score objects that are stored in the value scoresList. This is a fairly straightforward example, but what about those cases when you need to specify parameters for your cypher query? How is this case handled with anormcypher?
This example works :)…which is what we care about right? To start, let’s look at this example independent of the previous example. Here you see a cypher query execution that does not retrieve a collection via anormcypher’s collect() functionality, it retrieves a single property using apply() from anormcypher’s Stream API, that is later used to create a TestScoreListing. What’s of interest here is that we are now providing query parameters to find the listing. This approach works, however it certainly isn’t as clean as when we were using pattern matching. Here’s a better approach using anormcypher’s “as” method which is part of its Parser API.
You can see that we are now still able to provide our parameters to the query, and in turn we use the Parser API to eventually transform our result into the TestScoreListing. Tho technically I don’t believe this qualifies exactly as pattern matching, the same principle applies.
If you actually finished this post, I encourage you to take a look at the documentation for Anormcypher and try it out for yourself!