AEM Cloud Service - Extend Fulltext Predicate Evaluator to modify Search Term

Goal

AEM Cloud Service 2021.11.6058.20211123T163652Z-211000 (Nov 23, 2021)

Oftentimes you may have to modify the entered OmniSearch term (fulltext) to deal with special characters or files names with specific conventions. Code in this post extends FulltextPredicateEvaluator to replace "_"  (underscore) with " " (space) in search term...

Package Install | Github



Solution

1) Create class apps.experienceaem.assets.core.servlets.SpecialCharacterInFulltextPredicateEvaluator extending com.day.cq.search.eval.FulltextPredicateEvaluator, add the code below...

package apps.experienceaem.assets.core.servlets;

import com.day.cq.search.Predicate;
import com.day.cq.search.eval.EvaluationContext;
import com.day.cq.search.eval.FulltextPredicateEvaluator;
import org.apache.commons.lang3.StringUtils;
import org.osgi.service.component.annotations.Component;

@Component(
        factory = "com.day.cq.search.eval.PredicateEvaluator/fulltext"
)
public class SpecialCharacterInFulltextPredicateEvaluator extends FulltextPredicateEvaluator {

    public String getXPathExpression(Predicate predicate, EvaluationContext context) {
        String searchTerm = predicate.get(predicate.getName());

        if(StringUtils.isEmpty(searchTerm) || !searchTerm.contains("_")){
            return super.getXPathExpression(predicate, context);
        }

        searchTerm = searchTerm.replace("_", " ");

        predicate.set("fulltext", searchTerm);

        return super.getXPathExpression(predicate, context);
    }
}


No comments:

Post a Comment