NEO4J's Query grammar note (ii)

Source: Internet
Author: User
Tags neo4j

Tag: Ring operation Boolean SQL and set skip less return

Cypher is the NEO4J official website to provide the declarative query language, very powerful, with it can complete any of the map of the query filtering, our knowledge map of the first phase of the project is completed, the following will be summed up to learn about neo4j related knowledge. Today, the previous article looks at some basic concepts and syntax of NEO4J's cpyher query.

One, node syntax

In cypher, a node is represented by a pair of parentheses (), which is queried in the Cypher form as follows:

1, () means match any one of the nodes

2, (Node1) represents the match of any node and gives it an alias

3, (: lable) represents querying a type of data

4, (person:lable) represents querying a type of data, and gives it an alias

5, (person:lable {name: "Xiao Wang"}) query data under a type where the node property satisfies a value

6, (person:lable {name: "Xiao Wang", age:23}) the attributes of a node can exist in more than one, and is a relationship of an and

Two, relational grammar

Relationship with a pair-composition, the relationship between the direction of the in and out, if there is no direction is to enter and out both query

1,--> point to a Node

2,-[role]-> the relationship with an individual name

3,-[:acted_in]-> access to a class of relationships

4,-[role:acted_in]-> accesses a class of relationships and adds aliases

5,-[role:acted_in {roles:["Neo", "Hadoop"]}]->

Data that accesses a relationship of a property under a class of relationship

Three, pattern syntax

Schema syntax is a combination of node and relational query syntax, and we can do whatever complex query we want with the schema syntax.

(p1: Person:Actor {name:"tom"})-[role:acted_in {roles:["neo","actor"]}]-(m1:Movie {title:"water"})
Four, pattern variables

To increase modularity and reduce duplication, Cypher allows the result of a pattern to be specified in a variable or alias for subsequent use or operation

Path = (: Person)-[:acted_in]-> (: Movie)

Path is the abstract encapsulation of the result set, and there are several functions that can extract data directly from path, such as:

Nodes (PATH): Extract all Nodes

Rels (PATH): Extract all relationships and relationships (path) equal

Length (path): Gets the path length

Five, conditions

Cypher statements are also made up of multiple keywords, like SQL's

select name, count(*) from talbe where age=24 group by name having count(*) >2 order by count(*) desc

The syntax of multiple keywords, cypher is very similar, each keyword executes a specific task to process the data

Match: Key keywords for queries

Create: Insert similar to SQL

Filter,project,sort,page and so on have the corresponding function statement

By combining some of the above statements, we can write very powerful and complex syntax to query what we want to retrieve, and Cypher automatically parses the syntax and optimizes execution.

Some practical examples of usage:

1, create
create (:Movie {title:"驴得水",released:2016}) return p;

Execute successfully, in NEO4J's web page we can see the following information

+-------------------+| No data returned. |+-------------------+Nodes created: 1Properties set: 2Labels added: 1

Of course cypher can also create multiple data at once and add relationships at the same time

2, query

Match (P:person) return p; Querying all data for the person type

Match (P:person {name: "Sun"}) return p; Search for people whose names are equal to sun

Match (P1:person {name: "Sun"})-[rel:friend]-> (p2) return p2.name, p2.age Query Sun's friend's name and age

Match (old) ... create (new)-[rel:dr]-> (new) return new creates a relationship to a node that already exists and a new node

3, query or update

The merge syntax can make no changes to the existing nodes, merging the changed parts

MERGE (m:Movie { title:"Cloud Atlas" })ON CREATE SET m.released = 2012RETURN m

Merge .... On create set ... return syntax supports merge updates

4, Filter filter

Cypher filtering is also used with the same keywords as SQL where

Match (P1:person) where p1.name= "Sun" return p1;

Equivalent to the following

Match (P1:person {name: "Sun"}) return P1

Note that in the Where condition the Boolean operators such as and, or, xor,not are supported, and inside the JSON string are

In addition, the Where query also supports regular queries

match (p1: Person)-[r:friend]->(p2: Person) where p1.name=~"K.+" or p2.age=24 or "neo" in r.rels return p1,r,p2

Relationship filtering matching using not

MATCH (p:Person)-[:ACTED_IN]->(m)WHERE NOT (p)-[:DIRECTED]->()RETURN p,m
5, the result set returns
MATCH (p:Person)RETURN p, p.name AS name, upper(p.name), coalesce(p.nickname,"n/a") AS nickname, { name: p.name, label:head(labels(p))} AS person

The result set returns to do the redo

match (n) return distinct n.name;
6, aggregate function

Cypher Support Count,sum,avg,min,max

Match (: Person) return count (*)

When aggregating, NULL is skipped count syntax support count (distinct role)

MATCH (actor:Person)-[:ACTED_IN]->(movie:Movie)<-[:DIRECTED]-(director:Person)RETURN actor,director,count(*) AS collaborations
7, Sorting and paging
MATCH (a:Person)-[:ACTED_IN]->(m:Movie)RETURN a,count(*) AS appearancesORDER BY appearances DESC SKIP 3 LIMIT 10;
8, collect aggregated results
MATCH (m:Movie)<-[:ACTED_IN]-(a:Person)RETURN m.title AS movie, collect(a.name) AS cast, count(*) AS actors
9, Union Union

Supports two query structure set-like results merging

MATCH (actor:Person)-[r:ACTED_IN]->(movie:Movie)RETURN actor.name AS name, type(r) AS acted_in, movie.title AS titleUNION (ALL)MATCH (director:Person)-[r:DIRECTED]->(movie:Movie)RETURN director.name AS name, type(r) AS acted_in, movie.title AS title
Ten, with

The WITH statement provides Cypher with a powerful pipeline capability that can be one or query output, or the input of the next query is very similar to the return statement, except that with each result, the alias identifier must be used.

Through this function, we can easily do in the query results in the continuation of nested queries.

count(*) AS appearances, collect(m.title) AS moviesWHERE appearances > 1RETURN person.name, appearances, movies

Note that in SQL, we want to filter the aggregation results, we need to use the having statement but in Cypher we can use the WHERE keyword to complete the filter with the WITH statement

11, adding a constraint or index

Unique constraint (implemented using merge) CREATE CONSTRAINT on (movie:movie) ASSERT Movie.title is unique

Add indexes (quickly find the start node when the graph is traversed), greatly improving query traversal performance CREATE INDEX On:actor (name)

To add test data:

CREATE (actor:Actor { name:"Tom Hanks" }),(movie:Movie { title:‘Sleepless IN Seattle‘ }), (actor)-[:ACTED_IN]->(movie);

Using index Queries:

MATCH (actor:Actor { name: "Tom Hanks" })RETURN actor;

NEO4J's Query grammar note (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.