Search code examples
salesforceapex-code

How to search on the words of a phrase using SOSL in salesforce?


I am searching on ideas in my community. I am using SOSL for this, but I have an issue regarding not searching on the exact phrase. I want to search on the words of phrase.

SOSL

 string searchQuery = 'FIND {'+searchText+'} IN ALL FIELDS RETURNING Idea(Id, title, body, categories, createddate, lastmodifieddate)';

So can anybody please help me to search on the words of a phrase?


Solution

  • If you're using SOSL in APEX, you don't need the curly braces around the find text (they are for the API).

    Assuming that you're using APEX, let's say that the phrase that you were searching for was 'awesome'. This would be the APEX syntax:

    List<Sobject[]> awesomeResults = [FIND 'awesome' IN ALL FIELDS RETURNING Idea(Id, title, body, categories, createddate, lastmodifieddate)'];

    If you want to create SOSL dynamically, then use the Search.query(query_string) method. Make sure that you escape the 's in your query string if you do that.

    The documentation is pretty good for these features: