A
A
Andrey Mensky2019-06-25 19:53:49
MongoDB
Andrey Mensky, 2019-06-25 19:53:49

How to optimize composite indexes for complex sorting with different order?

Good day.
There is an unusual task in my subjective opinion. It is necessary to sort the products in order of preference, more is better.
In total there is 1 general sorting order (By price, By novelty) and 4 more which can be arranged in a different custom order, i.e. the user can change the order of these items:
- Size
- Color
- Clarity
- Quality
Usually the request looks like this:

db.getCollection("products")
  .find({
    status: 'available',
    shape: { '$in': [...] },

    price:             { '$gte': 0, '$lte': 100000 },
    size:              { '$gte': 0, '$lte': 5 },
    color:             { '$gte': 0, '$lte': 22 },
    clarity:           { '$gte': 0, '$lte': 11 },
    quality:           { '$gte': 0, '$lte': 5 },
  })
  .sort({ price: 1, size: -1, color: -1, clarity: -1, quality: -1 })

The problem is that there are a lot of products and they are often added, and sorting options for 24+ and starting an index for each of them does not seem like a sound idea to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aristarkh Zagorodnikov, 2019-06-25
@onyxmaster

How many products are in the database? Less than 100,000? Load into memory and sort not into DB?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question