Queries Based on Composite Keys
In the previous section, we mentioned that getStateByRange does not work with composite keys. How can we then implement a function that will return all objects of the same type?
getStateByPartialCompositeKey from ChaincodeStub perfectly fits the purpose.
getStateByPartialCompositeKey(objectType: string, attributes: string[]): Promise<StateQueryIterator>
This function returns an iterator, which can be used to iterate over all composite keys, whose prefix matches the given partial composite key.
Let getByType(objType) be a new operation, which returns all states of a specified type. Then, an implementation of this operation in SimpleContract will look the following way:
async getByType(ctx, objType) {
const iteratorPromise = ctx.stub.getStateByPartialCompositeKey(objType, []);
let results = [];
for await (const res of iteratorPromise) {
const splitKey = ctx.stub.splitCompositeKey(res.key);
results.push({
objType: splitKey.objectType,
key: splitKey.attributes[0],
value: res.value.toString()
});
}
return JSON.stringify(results);
}
As you can see, the above method looks similar to getByRange. It also uses the same type of iterator object, though this iterator object is obtained from a different method, getStateByPartialCompositeKey. Furthermore, since getByType works with composite keys, we should parse the response accordingly.
Last updated
Was this helpful?