Create and manage Smart Segments

Now that you know what a Segment is, you might want to take your filtering logic to the next level.

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 (Product in Rails) to allow admin users to see the bestsellers at a glance.

SQL
Mongodb

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 = models.Sequelize.Op;
collection('products', {
segments: [{
name: 'Bestsellers',
where: (product) => {
return models.sequelize.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: models.sequelize.QueryTypes.SELECT })
.then((products) => {
let productIds = products.map((product) => product.id);
return { id: { [Op.in]: productIds }};
});
}
}]
});

You’re free to implement the business logic you need. Your Smart Segment should return something like { _id: { $in: [ 1,2,3,4,5 ] } }.

/forest/products.js
const { collection } = require('forest-express-mongoose');
const Product = require('../models/products');
collection('Product', {
fields: [{
field: 'buyers',
type: ['String'],
reference: 'Customer'
}],
segments: [{
name: 'Bestsellers',
where: (product) => {
return Product
.aggregate([
{
$project: { orders_count: {$size: { "$ifNull": [ "$orders", [] ] } } }
},
{
$sort: {"orders_count":-1}
},
{
$limit: 5
}
])
.then((products) => {
let productIds = [];
products.filter((product) => {
if (product._id.length === 0) { return false; }
return true;
})
.forEach((product) => {
productIds.push(product._id);
});
return {"_id": { $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.