Developer Guide
Other documentationsDemoCommunityGitHub
  • Forest Admin
  • Getting Started
    • Quick start
    • Development workflow
  • Reference Guide
    • How it works
      • Environments
      • Developing on Forest Admin
        • Using branches
        • Deploying your changes
        • Forest CLI commands
          • init
          • login
          • branch
          • switch
          • set-origin
          • push
          • environments:reset
          • environments:create
          • deploy
          • schema:diff [beta]
        • Express packages
    • Models
      • Enrich your models
      • Relationships
        • Create a Smart relationship
          • GetIdsFromRequest
        • Smart Relationship Examples
          • Smart hasMany relationship in mongoDB
    • Actions
      • Create and manage Smart Actions
        • Use a Smart Action Form
        • Use a Smart Action Intent
      • Smart Action Examples
        • Calculate the distance between two string addresses
        • Impersonate a user
        • Create a record with a multiselect through a many-to-many relationship
        • Handle enums with alias labels in a smart action
        • Dropdown with list of values in smart action form
        • Custom dynamic dropdown in a form using smart collections
        • Refresh hasMany relationship in smart action
        • Smart segment to restrict access to an action on a record details view
        • BelongsToMany edition through smart collection
        • Upload files to amazon s3
        • Upload several files with the File Picker
        • Retrieve smart field info in a smart action
        • Smart action to create several records from the input of a single smart action form
        • Add many existing records at the same time (hasMany-belongsTo relationship)
        • Call a webhook with record ids
        • Bulk update records
    • Smart Fields
      • Smart Field Examples
        • Add an HTML credit card as a smart field in a summary view
        • Display field with complex info in html format (rich text editor)
        • Generate signed urls to display S3 files in a smart field
        • Print a status object in a single line field
        • Sort by smart field
        • Sort by smart field that includes value from a belongsTo relationship
        • Add fields destined to the create form
        • Add validation to a smart field edition
        • Display smart field as progress bar using rich text editor
        • Update point geometry field using a smart field and algolia api
    • Smart Collections
      • Examples
        • Create a Smart Collection with Amazon S3
        • Smart relationship between model and stripe cards
        • Create records from a Smart collection
        • Searchable smart collection with records fetched from hubspot API
      • Serializing your records
    • Routes
      • Default routes
      • Extend a route
      • Override a route
    • Integrations
      • Stripe
      • Mixpanel
      • Intercom
      • Elasticsearch
        • Interact with your Elasticsearch data
        • Elasticsearch service/utils
        • Another example
      • Zendesk
        • Authentication, Filtering & Sorting
        • Display Zendesk tickets
        • Display Zendesk users
        • View tickets related to a user
        • Bonus: Direct link to Zendesk + change priority of a ticket
      • Dwolla
        • Display Dwolla customers
        • Display Dwolla funding sources
        • Display Dwolla transfers
        • Link users and Dwolla customers
        • Dwolla Service
      • Razorpay
      • Hubspot
        • Create a Hubspot company
        • Display Hubspot companies
      • Twilio
        • Send an SMS with Twilio and Zapier
      • Azure Table Storage
      • Slack
        • Send Smart Action notifications to Slack
      • Algolia
        • Geocode an address with Algolia
    • 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 dynamic calendar view for an event-booking use case
      • Create a custom moderation view
    • Smart Segments
    • Scopes
      • Create a scope more than one level away based on a Smart field
      • Scope on a smart field extracting a json's column attribute
    • Performance
    • Charts
      • Create an API-based Chart
      • Create a Smart Chart
      • Create Charts with AWS Redshift
  • Extra help
    • Setup
      • Install
      • Connecting Forest Admin to Your Database (Forest Cloud)
      • Forest Admin IP white-listing (Forest Cloud)
      • Why HTTPS is necessary even locally
      • Troubleshooting
      • Prevent permission errors at installation
      • Deploy your admin backend to AWS
      • Deploy your admin backend on Heroku
      • Deploy your admin backend to Ubuntu server
      • Deploy your admin backend to Google Cloud Platform
      • Install Forest Admin on a remote machine
      • Use Forest Admin with a read-only database
      • Configuring CORS headers
      • Running Forest Admin on multiple servers
      • Flatten nested fields (MongoDB)
    • Upgrade
      • Upgrade notes (Rails)
        • Upgrade to v9
        • Upgrade to v8
        • Upgrade to v7
        • Upgrade to v6
        • Upgrade to v5
        • Upgrade to v4
        • Upgrade to v3
      • Upgrade notes (SQL, Mongodb)
        • Upgrade to v9
        • Upgrade to v8
        • Upgrade to v7
        • Upgrade to v6
        • Upgrade to v5
        • Upgrade to v4
        • Upgrade to v3
      • Update your models' definition
      • Monitor your Forest's status
      • Manage your Forest Admin environments programmatically
      • Changing your domain name
      • Migrate to the new role system
      • Push your new version to production
    • Databases
      • Use a demo SQL database
      • Use a demo MongoDB database
      • Populate a postgreSQL database on Heroku
      • Connect to a read replica database
      • Plug multiple schemas
      • Add new databases
      • Manage SQL views
    • Settings
      • Customize your /forest folder
      • Disable automatic Forest Admin schema update
      • Include/exclude models
      • Display extensive logs
      • Laravel specific settings
    • Releases Support
    • Other documentations
Powered by GitBook
On this page

Was this helpful?

  1. Reference Guide
  2. Integrations
  3. Elasticsearch

Interact with your Elasticsearch data

PreviousElasticsearchNextElasticsearch service/utils

Last updated 1 year ago

Was this helpful?

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 v1.

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

This is still the latest Ruby on Rails documentation of the forest_liana agent, you’re at the right place, please read on.

This is the documentation of the django-forestadmin Django agent that will soon reach end-of-support.

If you’re using a Django agent, notice that django-forestadmin v1 is replaced by v1.

If you’re using a Flask agent, go to the v1 documentation.

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

This is the documentation of the forestadmin/laravel-forestadmin Laravel agent that will soon reach end-of-support.

If you’re using a Laravel agent, notice that forestadmin/laravel-forestadmin v1 is replaced by v3.

If you’re using a Symfony agent, go to the v1 documentation.

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

Interact with your Elasticsearch data

Creating the Smart Collection

Let's take a simple example from Kibana, we will use You can easily import the data using Kibana Home page section Ingest your data.

When it's done we can start looking at how to play with those data in Forest Admin.

First, we declare the bank-accounts collection in the forest/ directory. In this Smart Collection, all fields are related to document mapping attributes except the field id that is computed using the document _id.

You can check out the list of if you need them.

You MUST declare an id field when creating a Smart Collection. The value of this field for each record MUST be unique. On the following example, we simply use the UUID provided on every Elasticsearch documents.

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

collection('bank-accounts', {
  isSearchable: false,
  fields: [
    {
      field: 'id',
      type: 'string',
    },
    {
      field: 'account_number',
      type: 'Number',
      isFilterable: true,
    },
    {
      field: 'address',
      type: 'String',
      isFilterable: true,
    },
    {
      field: 'firstname',
      type: 'String',
      isFilterable: true,
    },
    {
      field: 'lastname',
      type: 'String',
      isFilterable: true,
    },
    {
      field: 'age',
      type: 'Number',
      isFilterable: true,
    },
    {
      field: 'balance',
      type: 'Number',
      isFilterable: true,
    },
    {
      field: 'city',
      type: 'String',
      isFilterable: true,
    },
    {
      field: 'employer',
      type: 'String',
      isFilterable: true,
    },
    {
      field: 'email',
      type: 'String',
      isFilterable: true,
    },
    {
      field: 'gender',
      type: 'Enum',
      isFilterable: true,
      enums: ['M', 'F'],
    },
    {
      field: 'state',
      type: 'String',
      isFilterable: true,
    },
  ],
});

You can add the option isSearchable: true to your collection to display the search bar. Note that you will have to implement the search yourself by including it into your own GET logic.

Implementing the routes

Before getting further, in order to search your data using filters, we need to define the Elasticsearch configuration.

Name
Type
Description

index

string

The name of your Elasticsearch index.

filterDefinition

string

Type of your Elasticsearch fields. Can be number, date, text,keyword

sort

array of objects

mappingFunction

function

(optional) Required only to modify the data retrieved from Elasticsearch. Example: (id, source) => { id, ...source}

/routes/bank-accounts.js
const express = require('express');
const router = express.Router();

const {
  RecordSerializer,
  RecordCreator,
  RecordsGetter,
  RecordUpdater,
  PermissionMiddlewareCreator,
} = require('forest-express-sequelize');

const ElasticsearchHelper = require('../service/elasticsearch-helper');
const { FIELD_DEFINITIONS } = require('../utils/filter-translator');

const permissionMiddlewareCreator = new PermissionMiddlewareCreator(
  'bank-accounts'
);

const configuration = {
  index: 'bank-accounts',
  filterDefinition: {
    account_number: FIELD_DEFINITIONS.number,
    address: FIELD_DEFINITIONS.keyword,
    age: FIELD_DEFINITIONS.number,
    balance: FIELD_DEFINITIONS.number,
    city: FIELD_DEFINITIONS.keyword,
    email: FIELD_DEFINITIONS.keyword,
    employer: FIELD_DEFINITIONS.keyword,
    firstname: FIELD_DEFINITIONS.keyword,
    lastname: FIELD_DEFINITIONS.keyword,
    employer: FIELD_DEFINITIONS.keyword,
    state: FIELD_DEFINITIONS.keyword,
    gender: FIELD_DEFINITIONS.keyword,
  },
};

const elasticsearchHelper = new ElasticsearchHelper(configuration);

// Routes implementation

module.exports = router;

Our custom filter translator only support number, keyword, text, date data types. Nonetheless, you can implement more filter mapper type in theutils/filter-translator.js

Implementing the GET (all records)

In the file routes/bank-accounts.js, we’ve created a new route to implement the API behind the Smart Collection.

The logic here is to list all the BankAccount records. We use a custom service service/elasticsearch-helper.js for this example. The implementation code of this service is available here.

/routes/bank-accounts.js
// Imports and ElasticsearchHelper base definition ...

router.get('/bank-accounts', async (request, response, next) => {
  try {
    const pageSize = Number(request?.query?.page?.size) || 20;
    const page = Number(request?.query?.page?.number) || 1;
    // search is not handle in this example
    // const search = request.query?.search;
    const options = { timezone: request.query?.timezone };

    let filters;
    try {
      filters = request.query?.filters && JSON.parse(request.query.filters);
    } catch (e) {
      filters = undefined;
    }

    const result = await elasticsearchHelper.functionSearch({
      page,
      pageSize,
      filters: filters || undefined,
      options,
    });

    const serializer = new RecordSerializer({ name: 'bank-accounts' });

    response.send({
      ...(await serializer.serialize(result.results)),
      meta: {
        count: result.count,
      },
    });
  } catch (e) {
    next(e);
  }
});

module.exports = router;

Implementing the GET (a specific record)

To access the details view of a Smart Collection record, you have to catch the GET API call on a specific record. One more time, we use a custom service that encapsulates the Elasticsearch business logic for this example.

/routes/bank-accounts.js
// Imports and ElasticsearchHelper base definition ...

router.get('/bank-accounts/:id', async (request, response, next) => {
  try {
    const bankAccount = await elasticsearchHelper.getRecord(request.params.id);
    const serializer = new RecordSerializer({ name: 'bank-accounts' });

    response.send(await serializer.serialize(bankAccount));
  } catch (e) {
    next(e);
  }
});

module.exports = router;

Implementing the PUT

To handle the update of a record we have to catch the PUT API call.

/routes/bank-accounts.js
// Imports and ElasticsearchHelper base definition ...

router.put(
  '/bank-accounts/:id',
  permissionMiddlewareCreator.update(),
  (request, response, next) => {
    const updater = new RecordUpdater(
      { name: 'bank-accounts' },
      req.user,
      req.query
    );

    updater
      .deserialize(request.body)
      .then((recordToUpdate) =>
        elasticsearchHelper.updateRecord(recordToUpdate)
      )
      .then((record) => updater.serialize(record))
      .then((recordSerialized) => response.send(recordSerialized))
      .catch(next);
  }
);

module.exports = router;

Implementing the DELETE

Now we are able to see all the bank accounts on Forest Admin, it’s time to implement the DELETE HTTP method in order to remove the documents on Elasticsearch when the authorized user needs it.

Delete a list a single record

/routes/bank-accounts.js
// Imports and ElasticsearchHelper base definition ...

router.delete(
  '/bank-accounts/:id',
  permissionMiddlewareCreator.delete(),
  async (request, response, next) => {
    try {
      await elasticsearchHelper.removeRecord(request.params.id);
      response.status(204).send();
    } catch (e) {
      next(e);
    }
  }
);

module.exports = router;

Delete a list of records

/routes/bank-accounts.js
// Imports and ElasticsearchHelper base definition ...

router.delete(
  '/bank-accounts',
  permissionMiddlewareCreator.delete(),
  async (request, response, next) => {
    const getter = new RecordsGetter(
      { name: 'bank-accounts' },
      request.user,
      request.query
    );
    const ids = await getter.getIdsFromRequest(request);

    try {
      await elasticsearchHelper.removeRecords(ids);
      response.status(204).send();
    } catch (e) {
      next(e);
    }
  }
);

module.exports = router;

Implementing the POST

To create a record we have to catch the POST API call.

/routes/bank-accounts.js
// Imports and ElasticsearchHelper base definition ...

router.post(
  '/bank-accounts',
  permissionMiddlewareCreator.create(),
  (request, response, next) => {
    const recordCreator = new RecordCreator(
      { name: 'bank-accounts' },
      request.user,
      request.query
    );

    recordCreator
      .deserialize(request.body)
      .then((recordToCreate) =>
        elasticsearchHelper.createRecord(recordToCreate)
      )
      .then((record) => recordCreator.serialize(record))
      .then((recordSerialized) => response.send(recordSerialized))
      .catch(next);
  }
);

module.exports = router;

It's not an easy job to connect several data sources in the same structure. To accommodate you in this journey we already provide you a simple service that handles all the logic to connect with your Elasticsearch data.

(optional) Required only to sort your data. Example: [ { createdAt: { order: 'desc' } }]

Finally, the last step is to serialize the response data in the expected format which is simply a standard document. You are lucky forest-express-sequelize already does this for you using the RecordSerializer.

@forestadmin/agent
forestadmin-agent-django
forestadmin-agent-flask
forestadmin/laravel-forestadmin
forestadmin/symfony-forestadmin
a set of fictitious accounts with randomly generated data.
available field options
ElasticsearchHelper
JSON API
Elasticsearch documentation