20.4. Cypher Queries

20.4.1. Querying and reading the result
20.4.2. Parameterized and prepared queries

You can use the Cypher query language from neo4j-embedded. Read more about cypher syntax and cool stuff you can with it here: Chapter 16, Cypher Query Language.

20.4.1. Querying and reading the result

Basic query

To execute a plain text cypher query, do this:

result = db.query("START n=node(0) RETURN n")

Retrieve query result

Cypher returns a tabular result. You can either loop through the table row-by-row, or you can loop through the values in a given column. Here is how to loop row-by-row:

result = db.query("START n=node(0) RETURN n")

# Iterate through all result rows
for row in result:
    node = row['n']

# Or, we can use single here as well
node = result.single['n']

Here is how to loop through the values of a given column:

result = db.query("START n=node(0) RETURN n")

# Fetch an iterator for the "n" column
col = result['n']

for value in col:
    node = value

# We know it's a single result,
# so we could have done this as well
node = result['n'].single

List the result columns

You can get a list of the column names in the result like this:

result = db.query("START n=node(0) RETURN n,count(n)")

# Get a list of the column names
columns = result.keys()

20.4.2. Parameterized and prepared queries

Parameterized queries

Cypher supports parameterized queries, see Section 16.1, “Parameters”. This is how you use them in neo4j-embedded.

result = db.query("START n=node({id}) RETURN n",id=0)

node = result.single['n']

Prepared queries

If you are executing similar queries over and over, you can pre-parse a parameterized version of the query. Then you can just execute that pre-parsed query with appropriate parameters.

get_node_by_id = db.prepare_query("START n=node({id}) RETURN n")

result = db.query(get_node_by_id, id=0)

node = result.single['n']