Sorting by nested objects

Records in my index have the following structure (users indicate their programming skills and experience in years):

ex1

Search is performed on skills.name. I would like to be able to sort by corresponding skills.years. For example, if two users both know React, I would sort by descending years and find the more experienced of the two this way.

I’ve spent quite some time trying to find the solution in the documentation with no luck. Is this use case even possible and if so, could you please direct me in the right direction.

Thanks.

Hi @bakar.tavadze,

You are on the right direction. The key will be that you need to make multiple records for the same user. In this case:

{
skills: {name: "django", years: 4},
username: "docc"
}
{
skills: {name: "React", years: 3},
username: "docc"
}

Then you can:

  • use “skills.years” as the sort-by for your replica index (e.g., developers_years_desc [1]
  • and set “skills.name” as an attribute for faceting to filter on skills.name: "React" [2]

[1] https://www.algolia.com/doc/guides/managing-results/refine-results/sorting/how-to/sort-by-attribute/
[2] https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/

This is interesting but it creates a new problem for me:

If a search is performed with query “C” (looking for users who can code in C language), C++ and C# records will also be returned in results. So, if a particular user has C# and C in his skills, then the search returns this user two times.

I would like to have one user only once in results. Hope this makes sense.

Indeed,

You should use distinct in that case to group the records by unique key.

You can follow this guide to achieve what you want:

1 Like