ChaincodeStub Functions for Rich Queries
ouchDB enables you to perform rich queries from the chaincode. It can be done using two functions provided by ChaincodeStub Interface:
getQueryResult(query: string): Promise<StateQueryIterator>
getQueryResultWithPagination(query: string, pageSize: number, bookmark?: string): Promise<StateQueryResponse<StateQueryIterator>>
The second function is a version of the first one that implements pagination. We have discussed pagination in the Ledger Data Range Queries chapter, so we will not focus on this topic now. Let’s dive into the getQueryResult function and logic.
getQueryResult performs a rich query against a state database. The function returns an iterator of the StateQueryIterator type, same as the query functions covered before. This iterator can be used to iterate over all the keys in the query result set.
The main point that differentiates getQueryResult from other query functions is that it is not re-executed during the validation phase. It means that the other committed transactions may have added, updated, or removed keys that impact the result set, and this would not be detected during the validation/commit time. Applications susceptible to this should not use getQueryResult as part of transactions that update the ledger and should limit use to read-only chaincode operations.
getQueryResult has a single input parameter only — a query string in the native syntax of the underlying state database. CouchDB uses an internal JSON query language called Mango. This way, the query string is a JSON object, and it has a single required field — a selector.
The selector itself is also a JSON object that specifies the criteria for selecting documents. Let’s assume that the ledger consists of simple assets with the following structure:
// Asset
{
id: string;
owner: string;
year: int;
}
If we want to query all the objects owned by Alice, the selector should look as shown below:
{
"selector": {
"owner": "Alice"
}
}
Selectors support different logical and conditional operators, so we can construct a complex selector to get all the objects owned by Alice since 2010:
{
"selector": {
"owner": "Alice",
"year": {
"$gte": 2010
}
}
}
Last updated
Was this helpful?