Sort Nodes by Property
Select all nodes with the mixin type ''mix:title' and order them by the 'prop_pagecount' property.
Repository Structure
The repository contains several mix:title nodes, where prop_pagecount has different values.
- root
- document1 (mix:title) jcr:title="War and peace" jcr:description="roman" prop_pagecount=4
- document2 (mix:title) jcr:title="Cinderella" jcr:description="fairytale" prop_pagecount=7
- document3 (mix:title) jcr:title="Puss in Boots" jcr:description="fairytale" prop_pagecount=1
Query Execution
SQL
// make SQL query
QueryManager queryManager = workspace.getQueryManager();
// create query
String sqlStatement = "SELECT * FROM mix:title ORDER BY prop_pagecount ASC";
Query query = queryManager.createQuery(sqlStatement, Query.SQL);
// execute query and fetch result
QueryResult result = query.execute();
XPath
// make XPath query
QueryManager queryManager = workspace.getQueryManager();
// create query
String xpathStatement = "//element(*,mix:title) order by prop_pagecount ascending";
Query query = queryManager.createQuery(xpathStatement, Query.XPATH);
// execute query and fetch result
QueryResult result = query.execute();
Fetching the Result
Let's get nodes:
NodeIterator it = result.getNodes();
if(it.hasNext())
{
Node findedNode = it.nextNode();
}
The NodeIterator will return nodes in the following order "document3", "document1", "document2".
We can also get a table:
String[] columnNames = result.getColumnNames();
RowIterator rit = result.getRows();
while (rit.hasNext())
{
Row row = rit.nextRow();
// get values of the row
Value[] values = row.getValues();
}
Table content is:
| jcr:title | jcr:description | prop_pagecount | jcr:path | jcr:score |
|---|
| Puss in Boots | fairytale | 1 | /document3 | 1405 |
| War and peace | roman | 4 | /document1 | 1405 |
| Cinderella | fairytale | 7 | /document2 | 1405 |