Indexing: Products and Categories dependency


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());


public static int GetCountOfProducts(this Category category)
  return Find.Service.Search<Product>().Filter(x => x.Ancestors().Match(category.ContentLink.ToString())).Count();

Edited, Jul 01, 2020 14:29

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). 

Jul 06, 2020 6:05

Thank you for the answer, Mari.

The thing is I cannot use calculated count, as it is more time-expensive than indexed one.

Jul 06, 2020 8:49

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)

Jul 06, 2020 10:50

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?

Jul 30, 2020 7:17

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 to check with content links are products 

Jul 30, 2020 7:56
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.