You should avoid being dependent upon indexing order. You can solve it by changing code inside GetCountOfProducts to caclculate count using commerce api (not FIND).
Thank you for the answer, Mari.
The thing is I cannot use calculated count, as it is more time-expensive than indexed one.
If you use IRelationRepository.GetChildren, it would be fast enough for the purpose of indexing. Time-wise it should be as fast as the indexed one (if that works)
Thanks for the answers; using the Commerce API rather than Search one makes more sense here.
@Quan Mai: How can I list all products under specific category using IRelationRepository.GetChildren?
Out of my head, IRelationRepository.GetChildren<NodeEntryRelation>(parentLink) would give you content links to all entries under parentLink category. If your category has both products and variants it will be quite tricky. You can use https://github.com/vimvq1987/CatalogContentTypeResolver to check with content links are products
In this scenario, Category has an indexed property of count of Products that belongs to the category (or its ancestor). However, when Indexing is scheduled, it's indexing Categories first, so Products count is always 0.
How to resolve that, i.e. how to index Products and then Categories?
------
The code snippets are as following--
Indexing in ConfigurableModule:
client.Conventions.ForInstancesOf<Category>().IncludeField(x => x.GetCountOfProducts());
GetCountOfProducts:
public static int GetCountOfProducts(this Category category)
{
return Find.Service.Search<Product>().Filter(x => x.Ancestors().Match(category.ContentLink.ToString())).Count();
}