Search the Library
By the end of this lesson, you'll be able to:
- Search across Book__c by title or author using SOSL
- Explain why SOSL fits a "search box" scenario better than several separate SOQL queries
- Return search results in a usable form to the caller
Prerequisites: "Handle Checkouts and Returns"
A search method using SOSL
public List<Book__c> searchBooks(String searchTerm) {
List<List<sObject>> searchResults = [
FIND :searchTerm IN ALL FIELDS
RETURNING Book__c(Id, Title__c, Author__c, Is_Checked_Out__c)
];
return (List<Book__c>) searchResults[0];
}
This is Module 21's SOSL search pattern, applied directly: FIND :searchTerm IN ALL FIELDS matches the term against Title__c, Author__c, and any other searchable text field on Book__c at once — one search covering both title and author lookups a user might type.
Using the search method
LibraryService library = new LibraryService();
List<Book__c> results = library.searchBooks('Bachman');
for (Book__c book : results) {
System.debug(book.Title__c + ' by ' + book.Author__c);
}
A member typing "Bachman" into a search box finds every book by that author — even though the search term matched Author__c, not Title__c — without the search code needing to know in advance which field the match would come from.
Why SOSL fits this better than SOQL here
// The SOQL alternative would need two separate queries and merged results
List<Book__c> byTitle = [SELECT Id, Title__c FROM Book__c WHERE Title__c LIKE :('%' + searchTerm + '%')];
List<Book__c> byAuthor = [SELECT Id, Title__c FROM Book__c WHERE Author__c LIKE :('%' + searchTerm + '%')];
// ...then manually merge and deduplicate the two lists
Module 21's core lesson applies directly: SOSL naturally searches multiple fields (and, if needed later, multiple objects) in one statement, avoiding the manual merging and deduplication a SOQL-only approach would require here.
Exercise
Write a searchBooks call for the term "Long" and debug the title of the first result.
Show hint
library.searchBooks('Long')
Search the Library Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A library search box needs to match a term against both title and author — this lesson uses SOSL from Module 21 to search both fields in one statement.