首页 > 解决方案 > 如何使用 QueryBuilder Api 检索资产的所有属性

问题描述

当我在AEM QueryDebug上使用以下查询时

path=/content/dam/we-retail  
type=dam:Asset  
p.limit=-1  
p.nodedepth=2  
p.hits=full  
p.guesstotal=true 

以及形成的URL/JSON QueryBuilder链接。

我可以看到每个资产的所有属性,包括 jcr:content、元数据,如下所示:

在此处输入图像描述

我需要将相同的结果返回到我在 AEM 上为客户构建的服务/端点。当我将上述相同的查询转换为查询生成器 API 时

queryParamsMap.put("type", "dam:Asset");  
queryParamsMap.put("p.limit", "-1");  
queryParamsMap.put("p.nodedepth", "2");  
queryParamsMap.put("p.hits", "full");  
queryParamsMap.put("p.guessTotal", "true");  

我怎样才能检索所有的值?

SearchResult result = query.getResult();  
for (final Hit hit : result.getHits()) {  
  Resource resource = hit.getResource();  
  Asset asset = resource.adaptTo(Asset.class);  

如果我使用asset.getMetadata(),我们只能看到下面的属性,jcr:content\metadata而看不到其他属性。

如果我使用ValueMap properties = resource.getValueMap();我们可以检索所有资产属性(如 jcr:path、jcr:primaryType 等),但不能检索“元数据”。

有没有办法获取资产节点的所有值?

标签: aemquery-builder

解决方案


将 AEM 资产的所有属性从 dam:Asset 节点本身获取到元数据节点 (jcr:content/metadata) 的另一种方法是使用Apache Sling 模型并将查询返回的每个资源调整为该模型。

例如:

@Model(adaptables=Resource.class)
public class MyAsset{

    @Inject
    @Named("jcr:created")
    private String createdDate;

    @Inject
    @Named("jcr:createdBy")
    private String createdBy;

    @Inject
    @Named("jcr:content/jcr:lastModified")
    @Optional
    private String lastModified;

    @Inject
    @Named("jcr:content/metadata/dc:title")
    @Optional
    private String title;

    @Inject
    @Named("jcr:content/metadata/dc:description")
    @Optional
    private String description;

    @PostConstruct
    protected void init() {
         // You can code here any task needed to be executed after all the injections of the model are done
    }

  //getters and setters...

}

请注意,您可以使用注释 @Named 指定资源的任何后代节点的任何属性。

如果您需要资源的特定很少的属性,我会建议您使用这种方法。如果您需要所有属性,我认为您找到的方法更好,因为您不需要创建模型来维护所有属性。

使用该模型,最终代码将是:

for (Hit hit : result.getHits()) {
      Resource resource = hit.getResource();
        if(resource!=null){
         MyAsset myAsset = resource.adaptTo(MyAsset.class);
        Logger.info("The asset {} was modified on {}", myAsset.getTitle(), myAsset.getLastModified());
        }
    }

有关 Sling 模型的更多信息,您可以参考:

https://sling.apache.org/documentation/bundles/models.html


推荐阅读