Optimize search query performance by using Lazy Query Approch . #18962
+10
−7
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Proposal to optimize the expensive search query issue #10777 .
Previously,
XpathEngineexecuted the search query immediately by calling.pluck(:id), which loaded all matching record IDs into memory as an Array. For broad searches (ex 300,000+ matches), this could cause memory spikes and blocked the worker, even if the user only requested the first 10 results.Changing
XpathEngineto return anActiveRecord::Relationinstead of an Array. This allows theSearchControllerto apply pagination (LIMIT and OFFSET) directly to the SQL query before execution .Also using
.countto avoid unnecessary loading of queries by.size.So at the end we are trading 1 massive, memory-intensive query for 2 small, efficient queries.
Before:
Query1 : Load everything from the db at once .
After:
Query1 : Count the total matching result and give only the number .
Query2 : Fetch only the results the end user can see at the moment .