New ACM paper, free-tier cloud, and open-source license

Fetch query

In this guide, you’ll see how to retrieve data from a database and project it as a JSON using Studio, Console, or one of the drivers.

Understanding Fetch queries

A Fetch query is used to retrieve values and types from a TypeDB database. For a detailed explanation of the query see the Fetch query page.

Sending Fetch queries

Before getting start, ensure you followed instructions from the Writing data section. The easiest way to send a Fetch query is to use Studio or Console:

  • Studio

  • Console

Follow the Studio manual to connect to TypeDB and select a project folder. Then use the steps below:

  1. Use a drop-down list in the top toolbar to select a database.

  2. Switch to data session and read transaction types.

  3. Open a new tab and insert or type in an Insert query, for example:

    TypeQL Fetch query
    match
    $u isa user;
    fetch
    $u: name, email;
  4. Run the query by clicking the studio run Run Query button.

  1. Open a data session and read transaction to the selected database (e.g., sample_db):

    transaction sample_db data read
  2. Send the Fetch query:

    match
    $u isa user;
    fetch
    $u: name, email;

    Push Enter twice to send the query.

  3. Close the transaction:

    close

The resulted JSONs should look like this:

{
    "u": {
        "email": [ { "value": "alice@typedb.com", "type": { "label": "email", "root": "attribute", "value_type": "string" } } ],
        "name": [ { "value": "Alice", "type": { "label": "name", "root": "attribute", "value_type": "string" } } ],
        "type": { "label": "user", "root": "entity" }
    }
}
{
    "u": {
        "email": [ { "value": "the-bob@typedb.com", "type": { "label": "email", "root": "attribute", "value_type": "string" } } ],
        "name": [ { "value": "Bob", "type": { "label": "name", "root": "attribute", "value_type": "string" } } ],
        "type": { "label": "user", "root": "entity" }
    }
}
{
    "u": {
        "email": [ { "value": "charlie@typedb.com", "type": { "label": "email", "root": "attribute", "value_type": "string" } } ],
        "name": [ { "value": "Charlie", "type": { "label": "name", "root": "attribute", "value_type": "string" } } ],
        "type": { "label": "user", "root": "entity" }
    }
}

To send a Fetch query programmatically, use drivers:

  • Rust

  • Python

  • Node.js

  • Java

  • C#

  • C++

  • C

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the transaction.query.fetch() method:
let databases = DatabaseManager::new(driver);
let db = databases.get(DB_NAME)?;
{
    let session = Session::new(db, SessionType::Data)?;
    {
        let tx = session.transaction(TransactionType::Read)?;
        let fetch_query = "
                            match
                            $u isa user;
                            fetch
                            $u: name, email;
                            ";
        let response = tx.query().fetch(fetch_query)?;
        for (i, json) in response.enumerate() {
            println!("User #{}: {}", (i + 1).to_string(), json.unwrap().to_string())
        }
    }
}

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the transaction.query.fetch() method:
with driver.session(DB_NAME, SessionType.DATA) as session:
    with session.transaction(TransactionType.READ) as tx:
        fetch_query = """
                        match
                        $u isa user;
                        fetch
                        $u: name, email;
                        """
        response = tx.query.fetch(fetch_query)
        for i, JSON in enumerate(response, start=1):
            print(f"User #{i}: {JSON}")

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the transaction.query.fetch() method:
try {
    session = await driver.session(DB_NAME, SessionType.DATA);
    try {
        tx = await session.transaction(TransactionType.READ);
        const fetch_query = `
                            match
                            $u isa user;
                            fetch
                            $u: name, email;
                            `;
        let response = await tx.query.fetch(fetch_query).collect();
        for (let i = 0; i < response.length; i++) {
            console.log("User #" + (i + 1) + ": " + JSON.stringify(response[i], null, 4));
        }
    }
    finally {if (tx.isOpen()) {await tx.close()};}
}
finally {await session?.close();}

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the transaction.query.fetch() method:
try (TypeDBSession session = driver.session(DB_NAME, TypeDBSession.Type.DATA)) {
    try (TypeDBTransaction tx = session.transaction(TypeDBTransaction.Type.READ)) {
        String fetchQuery = """
                            match
                            $u isa user;
                            fetch
                            $u: name, email;
                            """;
        int[] ctr = new int[1];
        tx.query().fetch(fetchQuery).forEach(result -> System.out.println("Email #" + (++ctr[0]) + ": " + result.toString()));
    }
}

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the transaction.Query.Fetch() method:
using (ITypeDBSession session = driver.Session(DB_NAME, SessionType.Data)) {
    using (ITypeDBTransaction tx = session.Transaction(TransactionType.Read)) {
        string fetch_query = @"
                        match
                        $u isa user;
                        fetch
                        $u: name, email;";
        List<JObject> response = tx.Query.Fetch(fetch_query).ToList();
        foreach (JObject answer in response) {
            Console.WriteLine("User: " + answer.ToString());
        }
    }
}

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the transaction.query.fetch() method:
        TypeDB::Options options;
TypeDB::Session session = driver.session(DB_NAME, TypeDB::SessionType::DATA, options);
{
    TypeDB::Transaction tx = session.transaction(TypeDB::TransactionType::READ, options);
    std::string fetchQuery = R"(
                                match
                                $u isa user;
                                fetch
                                $u: name, email;
                                )";
    TypeDB::JSONIterable results = tx.query.fetch(fetchQuery);
    std::vector<TypeDB::JSON> fetchResult;
    for (TypeDB::JSON& result : results) {
        fetchResult.push_back(result);
    }
}

Follow the connection guide to connect the driver to TypeDB Cloud or TypeDB Core.

Open a data session to the selected database, open a read transaction, and use the query_fetch() function:
Options* opts = options_new();
session = session_new(databaseManager, DB_NAME, Data, opts);
tx = transaction_new(session, Read, opts);
if ((tx == NULL) || FAILED()) {
    handle_error("Transaction failed to start.");
    goto cleanup;
}
char query[512];
snprintf(query, sizeof(query), "match $u isa user; fetch $u: name, email;");
StringIterator* users = query_fetch(tx, query, opts);
if (FAILED()) {
    handle_error("Query execution failed.");
    goto cleanup;
}
char *userJSON;
while ((userJSON = string_iterator_next(users)) != NULL) {
    printf("%s %s\n", "User:", userJSON);
}
transaction_close(tx);
session_close(session);

Response interpretation

A Fetch query returns all fetched values projected in JSON objects.

The response is a Stream/Iterator with a JSON object for every solution of a match clause pattern. A concept can’t be returned directly, but a value or a type can be projected into the resulting JSON. To return full concepts, see the Get query page.

Learn more

Learn more about Fetch queries in TypeQL: syntax, behavior, and query examples.

Learn how to write some new data to a database to read.

Check out the Reading data section of our TypeDB Learning course.

Provide Feedback