Flows for calculating average ratings

Hello, I hope you’re having a great day.

I have a question.
I’d like to use Flows in Directus to build a system that calculates the average rating for each product based on user-submitted ratings. The idea is to gather all ratings submitted for a given product, calculate the average, and then display it under the product.

For example, for a product like “Red Power Bank”, I want the average rating to be displayed as 3.4.

How can I implement this? Has anyone done something similar before?
I’d really appreciate any guidance or advice you can offer.
Thank you for taking the time to read my message.

5 Answers

5

Without knowing the DB schema I think it can be easy done with average aggregate function.

Basically you would want to group on the product name and calculate the average on the ratings column.

I just would construct the query in postman or some other tool of choice for debugging reasons and then transcribe the query into the flow operation.

Yes exactly, that’s why i wrote that you have to “transcribe” the query. In flows you basically write your query params as JSON object. But the query remains basically the same. It’s just easier to test if a query works and yields the correct results through a REST client like Postman instead of jumping back and forth reading flow logs.

hi, thanks for answering, The problem that I have is that I want to use directus flows, I might be wrong since it’s not long that I started woking with directus, but the solution you gave me, seems to be handling it using the API, and in the run script operation in flow, it’s not possible to make API calls right? (I got an error every time I tried). If it is possible, can you please kindly guide me?

thank you so much! :folded_hands:
I will try this now.

Small correction to my initial answer, you have of course to group instead of filter on the product name to use aggregate functions. Just asked Copilot for quick example but didn’t test it:

REST
GET /items/your_collection_name?aggregate[avg]=rating&groupBy[]=product_name

JSON

{
  "aggregate": {
    "avg": ["rating"]
  },
  "groupBy": ["product_name"]
}

REST looks right to me, but let me know if the JSON syntax is correct