Prev |  | Next

## 19.4. Cypher 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 15, Cypher Query Language.

### 19.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:

    root_node = "START n=node(0) RETURN n"

    # Iterate through all result rows
    for row in db.query(root_node):
        node = row['n']

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

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

    root_node = "START n=node(0) RETURN n"

    # Fetch an iterator for the "n" column
    column = db.query(root_node)['n']

    for cell in column:
        node = cell

    # Coumns support "single":
    column = db.query(root_node)['n']
    node = column.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()

### 19.4.2. Parameterized and prepared queries

#### Parameterized queries

Cypher supports parameterized queries, see Section 15.3, “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

Prepared queries, where you could retrieve a pre-parsed version of a cypher query to be used later, is deprecated. Cypher will recognize if it has previously parsed a given query, and won’t parse the same string twice.

So, in effect, all cypher queries are prepared queries, if you use them more than once. Use parameterized queries to gain the full power of this - then a generic query can be pre-parsed, and modified with parameters each time it is executed.

Copyright © 2013 Neo Technology

Prev | Up | Next
| Home |