Node.js Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting started
    • How it works
    • Quick start
    • Install
      • Create your agent
      • Expose an HTTP endpoint
        • For standalone agents
        • On Express
        • On Koa
        • On Fastify
        • On NestJS
      • Autocompletion & Typings
      • Troubleshooting
    • Migrating legacy agents
      • What's new
      • Pre-requisites
      • Recommendations
      • Migration steps
        • Run new agent in parallel
        • Configure database connection
        • Code transformations
          • API Charts
          • Live Queries
          • Smart Charts
          • Route overrides
          • Smart Actions
          • Smart Fields
          • Smart Relationships
          • Smart Segments
        • Compare schemas
        • Swap agents
      • Post-migration
        • Dropping Sequelize
        • Optimize your agent
  • Data Sources
    • Getting Started
      • Collection selection
      • Naming conflicts
      • Cross-data source relationships
      • Query interface and Native Queries
        • Fields and projections
        • Filters
        • Aggregations
    • Provided data sources
      • SQL (without ORM)
      • Sequelize
      • Mongoose
      • MongoDB
    • Write your own
      • Replication strategy
        • Persistent cache
        • Updating the replica
          • Scheduled rebuilds
          • Change polling
          • Push & Webhooks
        • Schema & References
        • Write handlers
      • Translation strategy
        • Structure declaration
        • Capabilities declaration
        • Read implementation
        • Write implementation
        • Intra-data source Relationships
      • Contribute
  • Agent customization
    • Getting Started
    • Actions
      • Scope and context
      • Result builder
      • Static Forms
      • Widgets in Forms
      • Dynamic Forms
      • Form layout customization
      • Related data invalidation
    • Charts
      • Value
      • Objective
      • Percentage
      • Distribution
      • Leaderboard
      • Time-based
    • Fields
      • Add fields
      • Move, rename and remove fields
      • Override binary field mode
      • Override writing behavior
      • Override filtering behavior
      • Override sorting behavior
      • Validation
    • Hooks
      • Collection hook
      • Collection override
    • Pagination
    • Plugins
      • Provided plugins
        • AWS S3
        • Advanced Export
        • Flattener
      • Write your own
    • Relationships
      • To a single record
      • To multiple records
      • Computed foreign keys
      • Under the hood
    • Search
    • Segments
  • Frontend customization
    • Smart Charts
      • Create a table chart
      • Create a bar chart
      • Create a cohort chart
      • Create a density map
    • Smart Views
      • Create a Map view
      • Create a Calendar view
      • Create a Shipping view
      • Create a Gallery view
      • Create a custom tinder-like validation view
      • Create a custom moderation view
  • Deploying to production
    • Environments
      • Deploy on AWS
      • Deploy on Heroku
      • Deploy on GCP
      • Deploy on Ubuntu
      • Deploy on Azure
    • Development workflow
    • Using branches
    • Deploying your changes
    • Forest Admin CLI commands
      • init
      • login
      • branch
      • switch
      • set-origin
      • push
      • environments:create
      • environments:reset
      • deploy
  • Under the hood
    • .forestadmin-schema.json
    • Data Model
      • Typing
      • Relationships
    • Security & Privacy
Powered by GitBook
On this page
  • Search modes
  • Default behavior
  • Customization

Was this helpful?

  1. Agent customization

Search

PreviousUnder the hoodNextSegments

Last updated 3 months ago

Was this helpful?

This is the official documentation of the @forestadmin/agent Node.js agent.

In Forest Admin, pages that show lists of records have a free-text search bar on top of them.

Search modes

2 search modes are supported: "normal" and "extended".

  • All searches start by being a "normal" search.

  • If the records users are looking for are not found, it is possible to trigger an "extended" search from the footer.

Default behavior

Natively, the search behavior is to seek value occurrences within columns of the Collection (in normal mode), and columns of the Collections of direct relations (in extended mode).

By default, Forest Admin will search only in specific columns, depending on their type:

Column Type
Default search behavior

Enum

Column is equal to the search string (case-insensitive).

Number

Column is equal to the search string (if the search string is numeric).

String

Column contains the search string (case-insensitive).

Uuid

Column is equal to the search string.

Other types

Column is ignored by the default search handler.

Customization

Alternatively, you may want to change how the search behaves in your admin panel.

For instance:

  • search only on the columns that are relevant to your use case.

  • use full-text indexes (i.e. Postgres tsquery and tsvector, Algolia, Elastic search, ...)

Extending the default search

The context received by the function replaceSearch can have access to the default search behavior and extend it:

agent.customizeCollection('people', collection => {
  collection.replaceSearch((searchString, extendedMode, context) => {
    // This function in the context gives access to the default search behavior
    // including the advanced search
    return context.generateSearchFilter(searchString, {
      // Include fields from the first level of relations when true
      extended: extendedMode,
      // Remove these fields from the default search fields
      excludeFields: ['gender'],
      // Add these fields to the default search field
      includeFields: ['address:street'],
      // Replace the list of default searched field by these fields
      // onlyFields: [],
    });
  });
});

The condition tree returned by generateSearchFilter can be combined with other custom conditions:

agent.customizeCollection('people', collection => {
  collection.replaceSearch((searchString, extendedMode, context) => {
    const defaultCondition = context.generateSearchFilter(searchString, {
      extended: extendedMode,
    });

    return {
      aggregator: 'Or',
      conditions: [
        defaultCondition,
        { field: 'address:street', operator: 'IContains', value: searchString },
      ],
    };
  });
});

Making the search case-sensitive by default

In this example, we use the searchExtended condition to toggle between case-sensitive and insensitive searches.

agent.customizeCollection('people', collection => {
  collection.replaceSearch((searchString, extendedMode) => {
    const operator = extendedMode ? 'Contains' : 'IContains';

    return {
      aggregator: 'Or',
      conditions: [
        { field: 'firstName', operator, value: searchString },
        { field: 'lastName', operator, value: searchString },
      ],
    };
  });
});

Changing searched columns

const productReferenceRegexp = /^[a-f]{16}$/i;
const barCodeRegexp = /^[0-9]{10}$/i;

agent.customizeCollection('products', collection => {
  collection.replaceSearch(async (searchString, extendedMode, context) => {
    // User is searching using a product reference.
    if (productReferenceRegexp.test(searchString))
      return context.generateSearchFilter(searchString, {
        onlyFields: ['reference'],
      });

    // User is search a barcode
    if (barCode.test(searchString))
      return context.generateSearchFilter(searchString, {
        onlyFields: ['barCode'],
      });

    // User is searching something else, let's search in the product name only
    if (!extendedMode)
      return context.generateSearchFilter(searchString, { onlyFields: ['name'] });

    // In "extended" mode, we search on name, description and brand name
    return context.generateSearchFilter(searchString, {
      onlyFields: ['name', 'description', 'brand:name'],
    });
  });
});

Calling an external API

If your data is indexed using a SaaS, an external store, or a full-text index, you can call it in the search handler.

const algoliasearch = require('algoliasearch');
const client = algoliasearch('APPLICATION_ID', 'WRITE_API_KEY');
const index = client.initIndex('indexName');

agent.customizeCollection('products', collection =>
  collection.replaceSearch(async (searchString, extendedMode, context) => {
    const { hits } = index.search(searchString, {
      attributesToRetrieve: ['id'],
      hitsPerPage: 50,
    });

    return { field: 'id', operator: 'In', value: hits.map(h => h.id) };
  });
);

Disable the search

You can remove the search bar by disabling the search on a collection:

agent.customizeCollection('Products', collection => {
  collection.disableSearch();
});

If you want to make a column searchable, you must define the right operator to allow the search to be performed. Please refer to the table to know which operator to define.

To customize the search behavior, you must define a handler that returns a .

By default, the search bar is displayed when at least one field supports the operator used for search based on its type ().

see this table
Operators to support
ConditionTree
A search bar on the main Table View
Extended search call to action