Skip to content

5-minute introduction to Cypher query language

The aim of this article is to get you up to speed with the basics of Cypher(the query language used for the Neo4j graph database) in just 5 minutes! So, without further ado, let's get started!

What is a graph data structure? How is it applied in database systems?

Since we are going to show the capabilities of a graph query language, we should get familiar with what a graph is first. If you already know what it is, you can simply move to the next section.

We will skip the formal mathematical definition of a graph intentionally, and just proceed with the graphic below.

City Graph

As you can see, we have a very simple map of some imaginary cities. They are marked with points or circles, and the distances between are represented by lines. This is actually a graph -- the cities are the nodes, the distances -- edges. Another way to think about it: if you know what a tree is, you can imagine the graph as a tree with loops where there is the possibility for its leafs to be connected.

Graph databases are just harnessing this data structure. Instead of tables, they make use of nodes and edges for modelling the relationship among the available data. Respectively, using a conventional query language won't be sufficient or relevant for such a database. That's where Cypher comes into play.

Our data

Since we need something to work on first, we will introduce the following graph database:

Star Wars Database

We'll use the relationship between a few of the main characters of Star Wars as an example. The blue circles represent the jedi, whereas green are non-jedi characters. Yellow, on the other hand, are the robots. All of the edges describe the relationship between these characters. As you can see, they can be both uni- and bidirectional.

Writing queries in Cypher

After having a basic understanding of what a graph is, and how the data is composed in the database, you'll find the syntax of Cypher very simple and intuitive to read and write. It is inspired by ASCII art, so you actually model your queries in a some graphical manner. Let's get started.

Nodes and relationships

Let’s start with the core structures of the graph -- nodes and relationships -- they are represented by () and [] plus < or >. For example, let's take a look at the relationship between Anakin and Padme, and how it can be represented with Cypher:

(:Jedi)-[:LOVES]->(:NonJedi)

Simple, isn't it? The arrows show how the nodes relate based on the relationship type that we have. Also, we have labels (or tags), which indicate the type of the nodes and the relationship.

Getting data with MATCH

We'll start with some basic examples of fetching data. I'll re-use the query from the previous section. Along with the MATCH keyword, we will be able to ask the database whether there are nodes that match our provided pattern, or subgraph.

The following query will return all jedi that are in love with non-jedi characters.

MATCH (j:Jedi)-[:LOVES]->(:NonJedi)
RETURN j

You probably noticed that we introduced a j in the query. This is simply a variable used for referring to the jedi node. Note that we can use these for relationships as well.

Going back to the query, you might have guessed that, in the case of our current database, we'll end up with Anakin's node being returned. That being said, we can be a bit more specific when creating the pattern:

MATCH (j:Jedi)-[:LOVES]->(:NonJedi)-[:LOVES]->(j)
RETURN j

With it, we can get not only the jedi that are in love with a non-jedi, but all jedi who are in a romantic relationship with a non-jedi (i.e. both sides love each other).

Moving forward, let's try a different query:

MATCH (Jedi)--(Jedi)

You may ask whether it's a valid one, but it completely is. We don't have to necessarily specify the relationship, nor the direction (unless we want to). That being said, this will return every pair of jedis who have a relationship between them like Yoda and Obi-Wan, Obi-Wan and Anakin, and Yoda and Anakin.

Same applies to relationship types. We can specify the type of a relationship while abstracting from node type, like:

()-[:MENTORING]->()

Conditional fetching

Just like in a conventional relational database, we can specify some criteria when fetching data. With Cypher, we have two ways to do that:

1. Inlined JSON-like object

Let's take a look at the following query:

MATCH
  (j1:Jedi { rank: 'master' })-[:MENTORING]->(j2:Jedi)
RETURN
  j2.name

Note: Both single and double quotes are valid.

We can describe it as: "Return the names of all jedis who are mentored by a jedi master. Again, this results in getting Anakin's name, but not Ahsoka. Now, we'll write the same query but a bit differently:

2. Using WHERE

MATCH
  (j1:Jedi)-[:MENTORING]->(j2:Jedi)
WHERE
  j1.rank = 'master'
RETURN
  j2.name

Using the WHERE clause is equivalent to inlining the JSON-like object in a node. However, it is a fuller and more powerful way of specifying our desired criteria compared to the latter. For example, we can perform a boundary check of a numerical data, whereas that would be impossible with the first approach:

MATCH
  (j1:Jedi)-[:MENTORING]->(j2:Jedi)
WHERE
  j1.age < 100
RETURN
  j2.name

This will return all mentees' names whose mentors are less than 100 years old (i.e. Ahsoka and Anakin).

Keep in mind that we can apply all of these for the relationships as well!

Updating the existing data

After we have a good perception of how data is fetched from the database, we can spend a minute on how it can be updated. This happens with the help of the SET keyword:

MATCH
  (j:Jedi { name: 'Anakin' })
SET
  j.placeOfBirth = 'Tatooine'
  j.dateOfBirth = '41 BBY'
RETURN
  j

The explanation is obvious -- based on the provided search criteria, we perform an update via SET on the returned results. That's it!

Creating new data

In this sub-section, we will introduce two more keywords needed for adding new data to our database. These are CREATE and MERGE. Let's start with a simple example of "create":

CREATE (:Jedi { name: 'Qui-Gon' })

As you might have guessed, it simply adds a new node to our database. But what if we want to create a relation with this node? Well, here, MERGE comes in handy. It is intended for ensuring that the provided pattern exists in the database, which means that if it doesn't, it will be created.

Using the example we have, we can extend it so that Obi-Wan is an apprentice of Qui-Gon:

CREATE
  (qg:Jedi { name: 'Qui-Gon Jinn' })
MERGE
  (qg)-[:MENTORING]->(:Jedi { name: 'Obi-Wan' })

That'll ensure that the non-existent Qui-Gon node will be created, whereas the existing Obi-Wan node will be reused in the specified relation, or created if unavailable.

There are a lot more other use cases. For example, you can perform different updates on creation or on match when using MERGE:

MERGE
  (j:Jedi { name: 'Qui-Gon' })
ON CREATE SET
  j.created = timestamp()
ON MATCH SET
  j.updated = timestamp()
RETURN
  j

Removing data

Finally, we'll briefly go through removing of data from our database. There isn't a lot that needs to be explained, so let's move directly to the examples that we have:

Properties and labels

This is possible using REMOVE. We first search for a pattern, then we provide a property via a variable that has to be removed:

MATCH (r:Robot { name: 'C-3PO' })
REMOVE r.age

We can do the same for labels:

MATCH (r:Robot { name: 'C-3PO' })
REMOVE r:Robot

Deleting nodes and relationships

Let’s introduce yet another keyword called DELETE. With it, we can remove single nodes, like:

MATCH (j:Jedi { name: 'Anakin' })
DELETE j

or relationships:

MATCH (:Jedi { name: 'Anakin' })-[l:LOVES]->()
DELETE l

or a node with all of its relationships altogether, using the additional DETACH keyword:

MATCH (r:Robot { name: 'C-3PO' })
DETACH DELETE r

Further information

This is a simplified article, meant as an introduction. You can always get a deeper understanding of the query language from its official docs. Anyway, hopefully you were able to get an insight of how basic CRUD queries are being created, and how intuitive Cypher is!

This Dot Labs is a development consultancy that is trusted by top industry companies, including Stripe, Xero, Wikimedia, Docusign, and Twilio. This Dot takes a hands-on approach by providing tailored development strategies to help you approach your most pressing challenges with clarity and confidence. Whether it's bridging the gap between business and technology or modernizing legacy systems, you’ll find a breadth of experience and knowledge you need. Check out how This Dot Labs can empower your tech journey.

You might also like

Common Interview Questions & What They Mean cover image

Common Interview Questions & What They Mean

Introduction Who hasn't been asked some weird and interesting questions in previous interviews? Interviewers are known for asking a variety of weird, interesting, and confusing questions to possible employees for a variety of reasons. And this makes sense because they want to know as much as possible about you in the limited interview duration. Here are some interview questions you might be asked and what the interviewer is trying to find out about you from your answers: Introduce yourself Here, the interviewer is not really interested in your answer. What they are looking at your confidence and your passion, so this is the best time to show them your communication skills! So, you should tell them about your education, where you grew up, your past work experience, your hobbies, and your personal interests! Be calm, relaxed, and confident! What are your strengths? Here, the interviewers want to know how positivly you think about yourself! It’s a quite general question, so there is no right or wrong answer for it! So it’s a good opportunity for you to share what makes you so unique, and what are you good at! But you should tie your strengths to what they’re looking for! That’s why you should read the job description very carefully, and get a good understanding of what they are looking for, and then try to fit yourself in there! What are your weaknesses? In this question, the interviewers are looking at is whether you can identify your weaknesses, and how you can cover them up! You need not be really negative about yourself! For example, don't say “I am a very impatient person”, or “I am getting angry easily”. The best way to answer this question is to talk about a weakness that you had that isn’t related to the job, and what you did to overcome it. That way, they can see a progression, and that is what they really want to hear in the answer! What is your expected salary? Here, the interviewers, of course, have knowledge about the typical salaries offered by the company. By asking this question, they're often trying to see whether the applicant did research about the company. So learn about the company before the interview! You can use websites like Payscale or Glassdoor and read the reviews from other people who worked at this company! Can you work under pressure? This is a behavioral question, and the reason behind this question is the interviewers want to know if you get really stressed out. So the best way to answer this question is by talking about a situation where you experienced pressure, and the action that you took to diffuse that pressure. Then, talk about the result and what happened. How do you make your decisions? You might be asked this question if you are applying for management or lead position. They're interested in knowing your process when making decisions, because it's very likely that at some point, you will have to make a critical decision in the workplace. So, the best way to answer is to be confident and walk them through some of your management exercises, or some of your work situations that you handled successfully. What attracted you to this job? Here, the interviewers are typically trying to know if you understand the position you’re applying for, and that your goals and experience align with the role. Always remember that employers value candidates who aim to meaningfully contribute to company goals while also advancing their own careers. Where do you see yourself in five years? This is a growth-oriented question. So, if you just simply say: “I see myself sitting around here for the next five years until I figure out what I want to do”, that’s not what they want to hear. You should align this question to where the company is going and then you talk about how you see yourself fitting in their future. Why are you applying for this job? Here the interviewers want to know if you know their core values. A lot of people make mistakes answering this question and say that they are applying for the job because of the compensation package. Of course, salarie and benefits are an important thing, but you should have a long-term goal you want to achieve from the job! So it’s better to make sure this goal alligns with the company’s goals. That is what they want to hear from you. Why do you want to work here? The key to answering this question is to align yourself with where this company is going, so that’s why you must do some research on the company, like what are their values? What is their mission? Where are they going? What do they want to do? And by doing that, that will make you appear to be someone who can contribute to their overall mission, their projects, or whatever it is they’re trying to do. What makes you a good fit for this job? Here, they want you to talk about your past experiences, your past education, the kinds of things that you have done that are related to the kinds of things that they're looking for. So, you have to get a lot of information about the position, the job description, what they're looking for, and what the goals are for this position. Why should we hire you? I guarantee you are probably going to get asked this question, but it will most likely come near the end of the interview, after they’ve had a chance to build up some rapport and they’re actually thinking that you might be a good fit. Now, this is the chance to sell yourself, but you have to understand what they are looking for and the pains and problems that they have. Do you have any questions? This is usually the last question, and I made it the last one for a reason because this is most likely the last question they're going to ask you. Now that's your opportunity to find out more about what the next steps are, where they're going, or whatever is important for you. Don't just ask them questions to ask questions. Ask them questions that will help you determine whether this is a place that you want to be. Don't just ask questions about their organization chart or their finances or things that just don't really pertain to you. Ask them questions that are going to help you make a decision about whether you want to work there....

3 Web Performance Concepts that Will Help Start a Conversation Around Performance cover image

3 Web Performance Concepts that Will Help Start a Conversation Around Performance

In 2021, This Dot Labs released PerfBuddy, the free online platform for testing web and mobile based sites. With the release of this tool, it was our sincere hope to simplify the conversation around web performance, helping team leaders develop easy to understand metrics that they can use to advocate for further investment into their various web technologies. But we also realize that many new to web development, or who work in software but not as developers, might need more clarification on some of the basic key terms to help them engage more actively in conversations surrounding web development. Below, I’ve defined three of the top terms in web performance to help readers better ascertain your site’s performance, and play an active role in refining their technologies to provide the best experience for their customers. First Contentful Paint Time (FCP) FCP__, or __First Contentful Paint Time__, is a critical metric that measures the time that users must wait in order for a page to load its first visible element. For some sites, this could be the entire page. However, for others, the FCP time might measure the seconds between a user navigating to a site, and any responsive element, such as a loading bar, appearing in front of them. This is not a measurement of backend nor even frontend script loading speed, but a metric that affords development teams the ability to infer the quality of their site’s initial UX. According to metrics published by Akamai in 2018, sites are liable to lose nearly half of their visitors if their page takes more than three seconds to load. In fact, just a single second of load time delay can result in a 7% decrease in sales conversions for eCommerce platforms. This is especially true when considering mobile users, whose likelihood of leaving a page increases 90% when made to wait 5 seconds for a page to load And as more eCommerce shoppers turn to using their mobile devices- with 53% of users accessing shopping sites via mobile platforms on 2019’s Cyber Monday, representing a 40% YOY increase- teams need to be acutely aware of their cross platform performance with respect to FCP. Time to First Byte (TTFB) Not to be confused with FCP, TTFB, or Time to First Byte, refers to the amount of time that the browser waits in order to receive initial data from its server. In order for a site to display any information, a browser must make dozens, if not more, data requests. Issues related either to the quality of the host, site functionality, or complexity can all contribute to a site’s latency, or the amount of time it takes for data to be passed between the server and the browser. Of course, reducing site latency will improve user experience by decreasing FCP, and generally increasing browsing speed. However, ensuring low TTFB will also boost your SEO by making your site more quickly crawlable by leading search engines. Page Weight As developers add features and functionality to support more advanced user experience, web pages get heavier. As of 2020, the average desktop webpage weighs 2080 KB, up from an average of 1532 KB in 2017, with the weight of mobile web pages slightly lower, but still seeing a near 40% increase in size when compared to stats from just four years ago. eCommerce websites need to maintain acute awareness of their page weight, and ensure that their latency is not overly impacted by it, due to the tendency for shopping sites to be especially complex, supporting large catalogs of products along with other features to promote customer engagement. And as this era of advanced digital transformation continues to expand, eCommerce sites must develop strategies to meet market expectations for performance without over burdening their sites with heavy plugins and functionalities. Finding Your Path to Performance It starts with equipping yourself with the right tools to test your site’s speed and weight. There are countless platforms used for testing sites, however, there are only a handful that are capable of unlocking the insight that you need to support your most critical websites. Though PerfBuddy is a great place to start in order to identify potential roadblocks, it cannot do the work of actually improving site performance. By leveraging testing platforms such as Lighthouse, and continuously improving your performance metrics with assets such as DevTools, and strategies like Google’s PRPL, eCommerce retailers can ensure that their sites meet user expectations and promote their most critical business objectives. Need help? Contact This Dot Labs to learn more about how developing the tools and strategies to ensure optimal site performance can support scalable growth as you continue refining user experience!...

Nuxt DevTools v1.0: Redefining the Developer Experience Beyond Conventional Tools cover image

Nuxt DevTools v1.0: Redefining the Developer Experience Beyond Conventional Tools

In the ever-evolving world of web development, Nuxt.js has taken a monumental leap with the launch of Nuxt DevTools v1.0. More than just a set of tools, it's a game-changer—a faithful companion for developers. This groundbreaking release, available for all Nuxt projects and being defaulted from Nuxt v3.8 onwards, marks the beginning of a new era in developer tools. It's designed to simplify our development journey, offering unparalleled transparency, performance, and ease of use. Join me as we explore how Nuxt DevTools v1.0 is set to revolutionize our workflow, making development faster and more efficient than ever. What makes Nuxt DevTools so unique? Alright, let's start delving into the features that make this tool so amazing and unique. There are a lot, so buckle up! In-App DevTools The first thing that caught my attention is that breaking away from traditional browser extensions, Nuxt DevTools v1.0 is seamlessly integrated within your Nuxt app. This ensures universal compatibility across browsers and devices, offering a more stable and consistent development experience. This setup also means the tools are readily available in the app, making your work more efficient. It's a smart move from the usual browser extensions, making it a notable highlight. To use it you just need to press Shift + Option + D` (macOS) or `Shift + Alt + D` (Windows): With simple keystrokes, the Nuxt DevTools v1.0 springs to life directly within your app, ready for action. This integration eliminates the need to toggle between windows or panels, keeping your workflow streamlined and focused. The tools are not only easily accessible but also intelligently designed to enhance your productivity. Pages, Components, and Componsables View The Pages, Components, and Composables View in Nuxt DevTools v1.0 are a clear roadmap for your app. They help you understand how your app is built by simply showing its structure. It's like having a map that makes sense of your app's layout, making the complex parts of your code easier to understand. This is really helpful for new developers learning about the app and experienced developers working on big projects. Pages View lists all your app's pages, making it easier to move around and see how your site is structured. What's impressive is the live update capability. As you explore the DevTools, you can see the changes happening in real-time, giving you instant feedback on your app's behavior. Components View is like a detailed map of all the parts (components) your app uses, showing you how they connect and depend on each other. This helps you keep everything organized, especially in big projects. You can inspect components, change layouts, see their references, and filter them. By showcasing all the auto-imported composables, Nuxt DevTools provides a clear overview of the composables in use, including their source files. This feature brings much-needed clarity to managing composables within large projects. You can also see short descriptions and documentation links in some of them. Together, these features give you a clear picture of your app's layout and workings, simplifying navigation and management. Modules and Static Assets Management This aspect of the DevTools revolutionizes module management. It displays all registered modules, documentation, and repository links, making it easy to discover and install new modules from the community! This makes managing and expanding your app's capabilities more straightforward than ever. On the other hand, handling static assets like images and videos becomes a breeze. The tool allows you to preview and integrate these assets effortlessly within the DevTools environment. These features significantly enhance the ease and efficiency of managing your app's dynamic and static elements. The Runtime Config and Payload Editor The Runtime Config and Payload Editor in Nuxt DevTools make working with your app's settings and data straightforward. The Runtime Config lets you play with different configuration settings in real time, like adjusting settings on the fly and seeing the effects immediately. This is great for fine-tuning your app without guesswork. The Payload Editor is all about managing the data your app handles, especially data passed from server to client. It's like having a direct view and control over the data your app uses and displays. This tool is handy for seeing how changes in data impact your app, making it easier to understand and debug data-related issues. Open Graph Preview The Open Graph Preview in Nuxt DevTools is a feature I find incredibly handy and a real time-saver. It lets you see how your app will appear when shared on social media platforms. This tool is crucial for SEO and social media presence, as it previews the Open Graph tags (like images and descriptions) used when your app is shared. No more deploying first to check if everything looks right – you can now tweak and get instant feedback within the DevTools. This feature not only streamlines the process of optimizing for social media but also ensures your app makes the best possible first impression online. Timeline The Timeline feature in Nuxt DevTools is another standout tool. It lets you track when and how each part of your app (like composables) is called. This is different from typical performance tools because it focuses on the high-level aspects of your app, like navigation events and composable calls, giving you a more practical view of your app's operation. It's particularly useful for understanding the sequence and impact of events and actions in your app, making it easier to spot issues and optimize performance. This timeline view brings a new level of clarity to monitoring your app's behavior in real-time. Production Build Analyzer The Production Build Analyzer feature in Nuxt DevTools v1.0 is like a health check for your app. It looks at your app's final build and shows you how to make it better and faster. Think of it as a doctor for your app, pointing out areas that need improvement and helping you optimize performance. API Playground The API Playground in Nuxt DevTools v1.0 is like a sandbox where you can play and experiment with your app's APIs. It's a space where you can easily test and try out different things without affecting your main app. This makes it a great tool for trying out new ideas or checking how changes might work. Some other cool features Another amazing aspect of Nuxt DevTools is the embedded full-featured VS Code. It's like having your favorite code editor inside the DevTools, with all its powerful features and extensions. It's incredibly convenient for making quick edits or tweaks to your code. Then there's the Component Inspector. Think of it as your code's detective tool. It lets you easily pinpoint and understand which parts of your code are behind specific elements on your page. This makes identifying and editing components a breeze. And remember customization! Nuxt DevTools lets you tweak its UI to suit your style. This means you can set up the tools just how you like them, making your development environment more comfortable and tailored to your preferences. Conclusion In summary, Nuxt DevTools v1.0 marks a revolutionary step in web development, offering a comprehensive suite of features that elevate the entire development process. Features like live updates, easy navigation, and a user-friendly interface enrich the development experience. Each tool within Nuxt DevTools v1.0 is thoughtfully designed to simplify and enhance how developers build and manage their applications. In essence, Nuxt DevTools v1.0 is more than just a toolkit; it's a transformative companion for developers seeking to build high-quality web applications more efficiently and effectively. It represents the future of web development tools, setting new standards in developer experience and productivity....