Smart Segments

Please be sure of your agent type and version and pick the right documentation accordingly.

This is the documentation of the forest-express-sequelize and forest-express-mongoose Node.js agents that will soon reach end-of-support.

forest-express-sequelize v9 and forest-express-mongoose v9 are replaced by @forestadmin/agent v1.

Please check your agent type and version and read on or switch to the right documentation.

Smart Segments

What is a Smart Segment?

A Segment is a subset of a collection: it's basically a saved filter of your collection.

Segments are designed for those who want to systematically visualize data according to specific sets of filters. It allows you to save your filters configuration so you don’t have to compute the same actions every day.

A Smart Segments is useful when you want to use a complex filter, which you'll add as code in your backend.

Creating a Smart Segment

Sometimes, segment filters are complicated and closely tied to your business. Forest Admin allows you to code how the segment is computed.

On our Live Demo example, we’ve implemented a Smart Segment on the collection products to allow admin users to see the bestsellers at a glance.

You’re free to implement the business logic you need. The only requirement is to return a valid Sequelize condition. Most of the time, your Smart Segment should return something like { id: { in: [ 1,2,3,4,5 ] } }.

On our implementation, we use a raw SQL query to filter and sort the product that was sold the most.

/forest/products.js
const { collection } = require('forest-express-sequelize');
const models = require('../models');

const { Op, QueryTypes } = models.objectMapping;

collection('products', {
  segments: [
    {
      name: 'Bestsellers',
      where: (product) => {
        return models.connections.default
          .query(
            `
        SELECT products.id, COUNT(orders.*)
        FROM products
        JOIN orders ON orders.product_id = products.id
        GROUP BY products.id
        ORDER BY count DESC
        LIMIT 5;
      `,
            { type: QueryTypes.SELECT }
          )
          .then((products) => {
            let productIds = products.map((product) => product.id);
            return { id: { [Op.in]: productIds } };
          });
      },
    },
  ],
});

Setting up independent columns visibility

By default, Forest Admin applies the same configuration to all segments of the same collection.

However, the Independent columns configuration option allows you to display different columns on your different segments.

Last updated