Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

Getting Page path from SearchResult of QueryBuilder

Avatar

Level 8

Hello Team,

 

import com.day.cq.search.result.SearchResult;
 
List<MyPOJO> pojoObj = new ArrayList<>();
 
SearchResult results = query.getResult();
Iterator<Resource> resources = results.getResources();
            pojoObj = StreamSupport.stream(((Iterable<Resource>) () -> resources).spliterator(), false)
                    .map(resource -> resource.adaptTo(MyPOJO.class)).filter(Objects::nonNull)
                    .collect(Collectors.toList());
 
MyPOJO is a sling Model class which is having necessary fields
@ValueMapValue(name = "jcr:title")
private String title;
 
@ValueMapValue(name="jcr:description")
private String description;
   
@ValueMapValue(name = "property1")
private String prop;
 
Now, here how can I get the page path? 
  
1 Accepted Solution

Avatar

Correct answer by
Level 4

In that case you can try using

 

@Self

private Resource resource;

 

 

resource.getPath();

View solution in original post

4 Replies

Avatar

Level 4

Hi Mahesh,

 

Is there a particular reason why you would adapt it to a POJO class?

Instead you can adapt it to Page  class and get all the fields required.

 

Page page = resource.adaptTo(Page.class);

            if (page != null) {

                String title = page.getTitle();

                String path = page.getPath();

            }

 

Avatar

Level 8

I have 15 to 20 custom properties under each page. So, if I adapt to Page.class, then I need to write several lines of code to get each properties.

 

String title = page.getTitle();

String path = page.getPath();

 

ValueMap values = page.getProperties();

then, get each property values from ValueMap object.  

Also, Need to iterate through SearchResult object using while or for loop.

 

 

Avatar

Correct answer by
Level 4

In that case you can try using

 

@Self

private Resource resource;

 

 

resource.getPath();

Avatar

Level 8

Thanks a lot @SwetaB 

Your solution works like a charm.  Here is my code snippet.

 

@Model(adaptables = Resource.class,adapters = {MyPOJO.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MyPOJO {
 
@ValueMapValue(name = "jcr:title")
private String title;
 
@ValueMapValue(name="prop1")
private String property1;
 
@Self
private Resource resource;
   
other fields, setters, getters
 
... init method {
String path = resource.getPath();
}
 
}