Order by Score

Order by Score

Select all nodes with the mixin type 'mix:title' containing any word from the set {'brown','fox','jumps'}. Then sort result by the score in ascending node. This way nodes that matches better the query statement are ordered at the last positions in the result list.

Info
SQL and XPath queries support both score constructions jcr:score and jcr:score()

SELECT * FROM nt:base ORDER BY jcr:score [ASC|DESC]
SELECT * FROM nt:base ORDER BY jcr:score()[ASC|DESC]

//element(*,nt:base) order by jcr:score() [descending]
//element(*,nt:base) order by @jcr:score [descending]

Do not use "ascending" combined with jcr:score in XPath. The following XPath statement may throw an exception:

... order by jcr:score() ascending

Do not set any ordering specifier - ascending is default:

... order by jcr:score()

Repository Structure

The repository contains mix:title nodes, where the jcr:description has different values.

  • root
    • document1 (mix:title) jcr:description="The quick brown fox jumps over the lazy dog."
    • document2 (mix:title) jcr:description="The brown fox lives in the forest."
    • document3 (mix:title) jcr:description="The fox is a nice animal."

Query Execution

SQL

// make SQL query
QueryManager queryManager = workspace.getQueryManager();
// create query
String sqlStatement = "SELECT * FROM mix:title WHERE CONTAINS(*, 'brown OR fox OR jumps') ORDER BY jcr:score() 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)[jcr:contains(., 'brown OR fox OR jumps')] order by jcr:score()";
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();
}

NodeIterator will return nodes in the following order: "document3", "document2", "document1".

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:description...jcr:pathjcr:score
The fox is a nice animal..../document32512
The brown fox lives in the forest..../document23595
The quick brown fox jumps over the lazy dog..../document15017

Tags:
Created by Sergey Karpenko on 10/20/2009
Last modified by Dénarié Romain on 05/06/2010

Products

generated on Fri Jul 30 18:53:30 UTC 2010

eXo Optional Modules

eXo Core Foundations


Copyright (c) 2000-2010. All Rights Reserved - eXo platform SAS
2.4.30451