# Segments

{% hint style="success" %}
This is the official documentation of the `agent_ruby` Ruby agent.
{% endhint %}

A Segment is a subset of a Collection: it's 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 filter configurations so user don’t have to do repetitive actions every day.

![](/files/LhFpuEDueTYpkhrQ9T3u)

## From your admin panel

Segments can be configured from the interface, without the need to write any code.

This is documented in the [User Guide](https://docs.forestadmin.com/user-guide/collections/segments).

## From your Agent

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

For instance, in our [Live Demo example](https://app.forestadmin.com/livedemo), we’ve implemented a Segment on the collection `products` to allow admin users to see the bestsellers at a glance.

### Example

The only requirement when implementing a Segment from your agent is to return a valid `ConditionTree`.

#### Traditional Syntax

Using full context methods with `customize_collection`:

```ruby
include ForestAdmin::Types

@create_agent.customize_collection('customer') do |collection|
  collection.add_segment('mostPurchased') do |context|
    rows = context.datasource.get_collection('order').aggregate(
      Filter.new,
      Aggregation.new(operation: 'Count', groups: [{ field: 'product_id' }]),
      10
    )

    {
      field: 'id',
      operator: Operators::IN,
      value: rows.map { |r| r['product_id'] }
    }
  end
end
```

#### DSL Syntax

Using simplified DSL with `collection`:

```ruby
@create_agent.collection :customer do |collection|
  collection.segment 'mostPurchased' do |context|
    rows = context.datasource.get_collection('order').aggregate(
      context.caller,
      Filter.new,
      Aggregation.new(operation: 'Count', groups: [{ field: 'product_id' }]),
      10
    )

    {
      field: 'id',
      operator: 'In',
      value: rows.map { |r| r['product_id'] }
    }
  end
end
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.forestadmin.com/developer-guide-agents-ruby/agent-customization/segments.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
