Skip to main content
Smart segments migrate quickly. The syntax is very similar to the legacy agent. The main difference is in the return value.

What changed

Because the new agent is designed to work with multiple databases, the return value of the segment handler is no longer a Sequelize/Mongoose condition. Instead, you build a condition tree that the agent translates to the appropriate database syntax.

API cheatsheet (Node.js)

Legacy agentNew agent
where:handler body (return value)
sequelize.where(...)condition tree { field, operator, value }

Performance tip

Many queries map directly to Forest condition trees, giving much better performance than performing the query yourself and then building a naive id IN (...) condition.

Example

collection('products', {
  segments: [{
    name: 'Bestsellers',
    where: async product => {
      const 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;
      `;
      const products = await models.connections.default.query(query, {
        type: QueryTypes.SELECT,
      });
      return { id: { [Op.in]: products.map(p => p.id) } };
    },
  }],
});