CouchDB queries (Rich Queries) in HLF
Hyperledger Fabric (HLF) allows us to use CouchDB as the state database instead of default golevel database. There are many advantages of using couchdb as the state database. One of them is rich queries. In this article, we will focus on various queries and options available while writing rich queries.
In order to query data via rich queries, chaincode struct definition should have json information.
struct Address {
DoorNo string `json:"doorNo"`
City string `json:"city"`
}struct Employee {
DocumentType string `json:"documentType"`
EmployeeID string `json:"employeeId"`
Name string `json:"name"`
Salary int64 `json:"salary"`
Unit string `json:"unit"`
Addresses Address[] `json:"addresses"`
}
Here we have specified json field names for each of the struct field. For each of the Employee record, we will keep documentType as “Employee” so that we can query all employees with that criteria.
Now let us go through various rich queries to query couchdb data.
- Get all employees
{"selector": {"documentType": "Employee"}}
2. Get every employee’s employeeId and salary
{"selector": {"documentType": "Employee"}, "fields": ["employeeId", "salary"]}
3. Get all employees belonging to unit named “RnD”
{"selector": {"documentType": "Employee", "unit": "RnD"}}
4. Get all employees belonging to units “RnD”, “BLK”
{"selector": {"documentType": "Employee", "unit": {"$in": ["RnD", "BLK"]}}}
5. Get all employees with 10,00,000 ≤ salary ≤ 15,00,000
{"selector": {"documentType": "Employee", "salary": {"$gte": 1000000, "$lte": 1500000}}}
6. Get all employees with salary greated than 10,00,000 sorted by salary in descending order
To run the queries with sort, it is necessary to define design document and add it to META-INF/statedb/couchdb/indexes. Refer this link for more detail.
{"selector": {"documentType": "Employee", "salary": {"$gt": 1000000}}, "sort":[{"salary":"desc"}], "use_index":"_design/indexSalaryDoc"}
indexSalary.json
{"index":{"fields":["documentType","salary"]}, "ddoc":"indexSalaryDoc", "name":"indexSalary","type":"json"}
7. Get all employees with addresses containing city as Bengaluru
{"selector": {"documentType": "Employee",
"addresses": {
"$elemMatch": {
"city": "Bengaluru"
}
}
}
8. Get all employees with unit as BLK or salary >10,00,000
{"selector": {"documentType": "Employee",
"$or":[
{"unit": "BLK"},
{"salary": {"$gt": 1000000}}
]
}}
9. Get all employees whose name starts with “John”
{"selector": {"documentType": "Employee",
"name": {
"$regex": "John.*"
}
}
For more details on the couchdb queries, refer couchdb official documentation.
Thank you…