Expand my Community achievements bar.

SOLVED

How to get relevance score from QueryBuilder?

Avatar

Level 5

I am running a variety of queries and I am trying to sort them by @jcr:score descending.  I am noticing that the queryBuilder is returning a value of 0.01 for all results.  This is true for me using fulltext search, tag based search, very simple searches with filters, and very complex searches.

 

How are you supposed to sort by relevance using the jcr:score property?

 

For reference, I can literally run any query on this sheet and everything comes back with 0.01 for the score: aem-links/querybuilder_cheatsheet.md at master · paulrohrbeck/aem-links (github.com)

1 Accepted Solution

Avatar

Correct answer by
Community Advisor
3 Replies

Avatar

Correct answer by
Community Advisor

Hi @dylanmccurry 

 

With AEM 6.1 - Indexing plays a role that was not in 5.6.

 

Please check the relevant discussions here:

  1. https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/aem-fulltext-search-result...
  2. https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/xpath-query-ignoring-the-s...

Hope it helps!

Thanks,
Kiran Vedantam.

Avatar

Level 5

So this is AEM 6.5.

 

I am also using QueryBuilder ... does this work with query builder?

 

jcr:contains(., 'jelly sandwich^4')

Avatar

Community Advisor

@dylanmccurry 

To get the relevance score of a document to a particular query in AEM's QueryBuilder, you can use the setExplain(true) method to include the explanation of the score in the search results.

import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import com.day.cq.search.QueryBuilder;

// Get the QueryBuilder instance from the SlingHttpServletRequest object
QueryBuilder queryBuilder = slingRequest.adaptTo(QueryBuilder.class);

// Create a Map object for the query parameters
Map<String, String> queryParams = new HashMap<String, String>();

// Set the search term
queryParams.put("fulltext", "some query");

// Set the path to search
queryParams.put("path", "/content/my-site");

// Set the search type to "fulltext"
queryParams.put("type", "fulltext");

// Include the score explanation in the search results
queryParams.put("explain", "true");

// Execute the search
QueryResult queryResult = queryBuilder.createQuery(session, Query.XPATH, queryParams).getResult();

// Iterate through the hits to get the relevance score for each document
for (Hit hit : queryResult.getHits()) {
System.out.println(hit.getScore());
System.out.println(hit.getExcerpt());
System.out.println(hit.getPath());
}

 

In this example, queryParams.put("explain", "true") is used to include the explanation of the score in the search results. Then, hit.getScore() is used to retrieve the relevance score of each hit. Note that the Hit object is from the com.day.cq.search.result.Hit package.