1

I am looking for examples on usage for neo4j_client in C++. In the test suite I see the neo4j_result_t, but no example of iterating or calling fields by name. Is that possible?

Brian Dolan
  • 3,086
  • 2
  • 24
  • 35

1 Answers1

1

Results are returned as a neo4j_result_stream_t, which represents a stream of result rows. The number of the columns in the result is available via neo4j_nfields, and their names via neo4j_fieldname, both of which take the neo4j_result_stream_t pointer as a parameter.

To iterate over the result rows, use neo4j_fetch_next which returns a neo4j_result_t. And to extract values for each column from the row (the fields), pass the pointer to neo4j_result_field (along with the index of the column).

An example would be something like this:

neo4j_result_stream_t *results =
        neo4j_run(session, "MATCH (n) RETURN n.name, n.age", neo4j_null);
if (results == NULL)
{
    neo4j_perror(stderr, errno, "Failed to run statement");
    return EXIT_FAILURE;
}

int ncolumns = neo4j_nfields(results);
if (ncolumns < 0)
{
    neo4j_perror(stderr, errno, "Failed to retrieve results");
    return EXIT_FAILURE;
}
neo4j_result_t *result;
while ((result = neo4j_fetch_next(results)) != NULL)
{
    unsigned int i;
    for (i = 0; i < ncolumns; ++i)
    {
        if (i > 0)
        {
            printf(", ");
        }
        neo4j_value_t value = neo4j_result_field(result, i);
        neo4j_fprint(value, stdout);
    }
    printf("\n");
}
Chris Leishman
  • 1,777
  • 13
  • 19
  • Many thanks, and a follow up: can you call a field by name? like `neo4j_result_field(result, "age")`? Less intelligently: how do I get the age to come back as an `int`? I saw your `string` example. – Brian Dolan Oct 23 '16 at 23:11
  • 1
    Unfortunately not. The [Bolt Protocol](http://boltprotocol.org) offers no guarantee that a each column in the result has a unique name, so such a call could return an ambiguous result. – Chris Leishman Oct 23 '16 at 23:14
  • 1
    That said, I checked and Neo4j will refuse to run a Cypher command that would return duplicated column names. So you're unlikely to encounter this in practice and you could probably create a wrapper function fairly safely. – Chris Leishman Oct 23 '16 at 23:27