Skip to content

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

@pdphilip
Copy link
Owner

pdphilip commented Aug 4, 2025

Hey @caufab - I'm considering bringing this into the config/settings to apply it universally. The main consideration being the performance cost of doing so. In a Laravel context, it's very useful to have accurate hits. Great PR

@caufab
Copy link
Author

caufab commented Aug 4, 2025

Yeah I read something about the performance of tracking all hits especially when doing complex queries. There's not much documentation about this but it could be related to index size, so I think it might be a good idea to set it once in config a be applied to each search.
Looking forward to the next update! Thank you!

@pdphilip pdphilip merged commit e2124c8 into pdphilip:main Aug 20, 2025
1 check passed
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