0

I need to create a custom search on Lightning Component where I should be able to search the text from all the objects through SOSL. I followed the module on trailhead and was able to create a custom search through SOSL query. However, the example given in the module searches the text in specific/defined objects. I have read everywhere that if we dont mention the objects (and RETURNING) in the query, by default it searches from all objects, however Im not able to get the syntax of SOSL to search the text from all objects. I tried with many attempts but still no luck.

Please help me with a simple syntax to search the text from all objects and not just Accounts. Here's the query for the same-

List<List<SObject>> results = [FIND :searchText IN ALL FIELDS RETURNING Account(Id ORDER BY CreatedDate LIMIT 10)];

Thanks in advance.

2

You're not allowed to do this in Apex for some reason. You'll need to either make an API call, or list all the objects to search dynamically by creating a search string. The latter would probably look like:

String[] types = new String[0];
for(sObjectType sType: Schema.getGlobalDescribe().values()) {
    if(sType.getDescribe().isSearchable()) {
        types.add(''+sType);
    }
}
String searchTerm = 'demo';
List<List<sObject>> results = search.query('find :searchTerm in all fields returning '+String.join(types,','));

There appears to be at least one object that can't be searched despite saying it can (isSearchable() is true), so you may also need to make an exclusion list to avoid exceptions.

| improve this answer | |
  • Thanks @sfdcfox for your suggestion. But as per many of the articles, if the object is not mentioned in SOSL, it by default searches from all objects. If that's the case, is there any working solution for this without API calls? – Salesforce Learner Aug 7 at 7:24
  • @SalesforceLearner That's an Apex restriction. SOSL only supports search all by way of API, or you need to do something similar to this. Apex SOSL and SOQL has certain restrictions compared to the API versions, unfortunately. – sfdcfox Aug 7 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.