Many projects require a search page with a list of results, the total number of hits, and pagination.
Many projects require a search page with a list of results, the total number of hits, and pagination.
Let's walk through this: Suppose you have a SearchPage to render your results. The simplest controller to do this is:
The conditional assignment to @hits
is necessary for two reasons:
Obj.where
raises an exception if @query
is empty@hits
instance variable is needed in the viewThe corresponding view, app/views/search_page/index.html.erb
:
You now have a search that returns the first 10 results on a page. This is a great start but not very useful. Let's expand this and add a simple pagination.
Change your controller code to this:
The batch_size
is set explicitly here although it defaults to 10. Keeping the batch size in sync with the number of hits on a page ensures stable performance for more hits on a page. If you increase HITS_PER_PAGE
but leave the batch_size
at 10, the SDK needs more than one round trip to load those hits, which degrades performance.
And you can also add the number of hits to the view, right above where the hits are iterated over:
You now have a search page with a summary at the top and with links to navigate through the results at the bottom.
ObjSearchEnumerator
includes the Enumerable mixin and make use of methods like take
, map
or select
.
Note that using load_batch
directly may retrieve fewer items than expected in case your rate limit is exhausted. It can be used for special optimizations but is usually not needed on a day-to-day basis.
If you want to get all CMS objects at once using to_a
, make sure you call batch_size
with a sufficiently high value. Otherwise, the SDK is forced to do more round-trips than necessary.