How to Read Queries with WeaveDB

How to Read Queries with WeaveDB

Introduction

WeaveDB is a powerful database management system built on Arweave Blockchain that allows you to interact with your data using the WeaveDB SDK. It offers powerful querying options for retrieving data from your collections.

In the previous documentation article guide, we learned how to write queries.

In this guide, we'll learn how to use the WeaveDB SDK to perform read queries. These queries allow you to fetch documents, collections, and sub-collections, apply limits, sorting, and filtering, as well as access metadata.

Prerequisites:

Before proceeding, ensure that you have the WeaveDB SDK object stored in a variable named db. If you haven't initialized it, refer to the "Initialize WeaveDB" documentation. You should also have the collection_name variable, representing the name of your collection, and the doc_id variable, containing the unique identifier of a document within the collection.

Query Types

1. Get and Cget

The get query returns only the data, while the cget query returns both data and metadata. Metadata provided by cget can be useful for pagination.

const data = await db.get(collection_name, doc_id); // Get a document
const collectionData = await db.get(collection_name); // Get a collection

To retrieve sub-collections, you can use a sequence of collection and document IDs:

await db.get(collection_name, doc_id, "sub_collection_name_1", "sub_doc_id_1", "sub_collection_name_2");

2. Limit

You can limit the number of documents returned in a query by specifying a numeric value.

await db.get(collection_name, 5); // Limit to 5 documents

3. Sort

Sorting allows you to order the results. You can sort in ascending order by default or specify "desc" for descending.

await db.get(collection_name, ["age", "desc"]); // Sort by age in descending order
await db.get(collection_name, ["age"]); // Sort by age in ascending order (default)
await db.get(collection_name, ["age", "desc"], ["name", "asc"]); // Sort by age in descending order, then by name in ascending order

4. Where

The where clause helps filter documents based on specific conditions. Supported comparison operators include >, >=, <, <=, ==, !=, in, not-in, array-contains, and array-contains-any.

await db.get(collection_name, ["age"], ["age", ">", 20]); // Get docs where age is greater than 20

You can use dot notation to specify nested object fields for filtering.

await db.get(collection_name, ["favorites.food", "==", "apple"]); // Filter by nested field

Note: The = operator has been deprecated and replaced by == starting from v0.23.0. You can still use it for backward compatibility.

5. Skip

You can skip results using the startAfter, startAt, endAt, and endAfter options.

await db.get(collection_name, ["age"], ["startAfter", 20], ["endAt", 60]); // Skip documents within a range
await db.get(collection_name, ["age"], ["name", "desc"], ["startAfter", 20, "Bob"]); // Skip and sort

6. Pagination

To implement pagination, you can use the metadata returned by the cget query. Fetch a page of data and use the last item's metadata to retrieve the next page.

const docs_page1 = await db.cget(collection_name, ["age"]); // First page
const lastMetadata = docs_page1[docs_page1.length - 1];
const docs_page2 = await db.cget(collection_name, ["age"], ["startAfter", lastMetadata]);

7. Get Nonce

To obtain the next nonce for an address, which is used for signature verification during write operations:

await db.getNonce("address");

8. Get Ids

To retrieve the last added document's ID, you can use the getIds query.

const tx = await db.add({ age: 20, name: "Bob" }, collection_name);
const doc_id = (await db.getIds(tx))[0];

9. On and Con (Subscription)

You can subscribe to state changes with on and con, which are the counterparts of get and cget. Subscriptions allow you to receive real-time updates when the state changes. Note that these functions are available with weavedb-sdk-node.

const unsubscribe = await on(collection_name, doc_id, (data) => {
  console.log(data);
  unsubscribe();
});

10. GetCache and CgetCache

getCache and cgetCache functions are similar to get and cget but retrieve values from the cached state. This can be faster but may not provide the most up-to-date values. These functions are available with weavedb-sdk-node.

await db.getCache(collection_name, doc_id);
await db.cgetCache(collection_name, doc_id);

11. List Collections

You can list collection names using the listCollections query.

await db.listCollections(); // List root collections
await db.listCollections(collection_name, doc_id); // List sub-collections

WeaveDB's read queries offer a wide range of options for retrieving and filtering data, making it a versatile tool for managing your data effectively. Be sure to consult the official documentation for further details and more detailed query options.

Did you find this article valuable?

Support Gordian Etim by becoming a sponsor. Any amount is appreciated!