Skip to content

Add withTrackTotalHits method to Builder class to add track_total_hits #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

caufab
Copy link

@caufab caufab commented Jul 18, 2025

Add withTrackTotalHits method to Builder class to add track_total_hits in elasticsearch request body

@caufab caufab requested a review from pdphilip as a code owner July 18, 2025 14:48
@pdphilip
Copy link
Owner

Thanks for the PR @caufab - please provide more details (and use cases) around the utility of adding this as a feature

@caufab
Copy link
Author

caufab commented Jul 19, 2025

@pdphilip I was searching a way to add the flag track_total_hits in the body of the search request (outside the query field).
As explained in the official ES documentation, setting this param to true will allow to count the total number of elements found (see EDIT) in the whole index. Without this, if the index contains lots of hits (more than 10.000) hits field will contain always 10000.
This method can be called via the builder when creating the query very easily, like the example below:

$builder = Product::query();
$builder->trackTotalHits();

// build the query
$builder->search('test search');
$builder->whereTerm ....

// run the query
$results = $builder->get();

Of course the total hits will be in the same hits field as without the trackTotalHits, so we will need to take them in them meta data, but the count is precise, not limited to 10k.

EDIT: to be precise, not the total number of elements found, actually the total number of elements that have a hit with that query in the whole index

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants