Skip to content

Basic usage

Emmanuel Allison edited this page Dec 4, 2023 · 3 revisions

Basic Usage

AgeClient

The AgeClient is the actor which provides an interface for executing Cypher commands and queries against a PostgreSQL server with the Apache AGE extension installed. It opens and maintains the connection to the PostgreSQL server. Commands and queries tailored for Apache AGE can be executed against the PostgreSQL server using it.

To create an AgeClient, use the AgeClientBuilder:

var builder = new AgeClientBuilder("Host=server;Port=5432;Username=user;Password=pass;Database=sample1");
using var client = builder.Build();

Before executing Cypher commands, you must open a connection to the database using OpenConnectionAsync(), and the connection can be closed using CloseConnectionAsync(). A single AgeClient instance can be used for the lifetime of your application; only make sure you close the connection when not in use to avoid leaks.

Cypher Queries and Commands

AgeClient offers two methods for executing queries against the database: ExecuteCypherAsync and ExecuteQueryAsync.

ExecuteCypherAsync

This method executes cypher commands for which no result is needed. This is suitable for terminal cypher clauses.

await client.ExecuteCypherAsync("graph_name", "CREATE (:Person {name: 'Alex'})");

To return data from a command or query, use ExecuteQueryAsync.

ExecuteQueryAsync

This method executes cypher commands and returns the result set. Each field value is returned as an AgType.

await using var reader = await client.ExecuteQueryAsync(
$@"SELECT * FROM cypher('graph_name', $$
    MATCH (n)-[]-(m)
    RETURN n, m
$$) AS (n agtype, m agtype);");

// While there is another row, move to it and consume its values.
while(await reader.ReadAsync())
{
    AgType n = reader.GetValue(0);  // First column.
    AgType m = reader.GetValue(1);  // Second column.

    // Use results...
}

Clone this wiki locally