@websolutespa/payload-plugin-search
TypeScript icon, indicating that this package has built-in type declarations

0.1.1 • Public • Published

@websolutespa/payload-plugin-search

npm version

status alpha

Search plugin for PayloadCms.

Payload Search Plugin

A plugin for Payload CMS that adds collections, hooks, components and endpoints to manage search mechanism. It automatically creates a search index collection and exposes a search endpoint to retrieve search results based on the search index.

It is highly customizable and allows to define the fields to be included in the search index and their weights. It is also possible to define extra parameters to be included in the search and to customize the rating calculation among other things.

Requirements:

  • Payload version 2.28.0 or higher is required.

Installation

npm i @websolutespa/payload-plugin-search

Usage

import { buildConfig } from 'payload/config';
import search from '@websolutespa/payload-plugin-search';

export default buildConfig({
  plugins: [
    search({
      searchIndex: {
        admin: { group: 'SEARCH' },
        access: { read: () => false }
      },
      defaults: {
        fields: [
          { name: 'title', weight: 100 },
          { name: 'abstract', weight: 60 },
        ]
      },
      collections: [
        Contact.slug,
        Designer.slug,
        ShopDetail.slug,
        {
          slug: MagazineDetail.slug,
          fields: [
            { name: 'abstract', weight: 0 },
            { name: 'components', weight: 20 }
          ]
        },
        {
          slug: ProductDetail.slug,
          getTitle: (doc) => doc.title + " - " + doc.sku,
          fields: [
            { name: 'colors', weight: 60 },
            {
              name: 'size',
              weight: 10,
              beforeSync: ({ originalDoc, req }) => originalDoc?.size == 'XS_it' && req.locale == 'it' 
                ? 'La taglia più piccola del mondo!'
                : originalDoc?.size
            },
            { name: 'components', weight: 20 }
          ]
        }
      ],
      api: {
        locales: [ 'en', 'it' ],
        updateRequest: async (req) => {
          const { market, locale } = req.query;
          if (typeof market === 'string' && typeof locale === 'string') {
            await setMixerContext(req, market, locale);
          }
          return req;
        },
        extraParams: [{
          fieldName: 'market',
          serializer: (doc) => doc?.markets?.map((market: any) => market.id).join(' | ') ?? '',
          whereCondition: (req) => ({
            or: [
              { 'market': { equals: '' } },
              { 'market': { contains: req.query.market } }
            ]
          })
        }]
      }
    }),
    // The rest of your plugins config goes here
  ],
});

Plugin options

Option Type Description
searchIndex SearchIndexCollectionConfig The configuration for the automatically generated search index collection.
defaults SearchConfigDefaults The default search configuration, valid for all the specified collections if not overridden. getTitle allows to specify a function to set the title of the document. For each field you can specify the name and weight of the field to be included in the search index document. You can also provide a beforeSync function to customize the content of the field.
collections (SearchCollectionConfig | string)[] An array of collection slugs which indicates collection objects which should be included in the search index option. The slug property of the collection object must be specified if the collection is not a string. getTitle and fields properties can be specified to override the default title and fields configuration for the collection.
syncDrafts boolean A boolean to determine whether to sync drafts or not, default is false.
api apiConfig The configuration for the exposed search APIs. locales to be taken into account if not all. separators** is an array of separators to split the search query into words of minimum length equals to minLength. The wrapResults flag is used to determine whether to wrap the search doc results in objects { relationTo: string, value: IEntity, rating: number }, default is true. With extraParams it is possible to configure an array of extra parameters to be included in the search with their serializer and where condition. Defining calculateRating the default rating calculation is overridden. updateRequest allows to update the request object while retrieving the full document. It is also possible to define afterIndexRetrieval and afterDocsRetrieval hooks.
richTextSerializer (richText: any[]) => string A function to customize the serialization of rich text fields.

Notes

**The default separators are:

const defaultSeparators = [' ', ',', '.', ';', ':', '-', '_', '(', ')', '[', ']', '{', '}', '<', '>', '/', '\\', '|', '!', '?', '"', '\'', '@', '#', '$', '%', '^', '&', '*', '+', '=', '~', '`', '\t', '\n', '\r', '\n'];

Here's the search algorithm workflow:

  1. The search query is split into words of minimum length equals to minLength and the separators specified in the separators array;
  2. The configured extraParams where conditions are included if the parameter is found in the search query;
  3. The search index is queried for each word and the results are merged;
  4. The rating is calculated for each result based on the search query and the fields weights. The default rating calculation is based on the number of occurrences of the word in the field and the field weight;
  5. The results are paginated and sorted by rating in descending order.

Features

The plugin only affects collections and fields included in configuration with a weight greater than zero and automatically adds:

  • A Search Index collection to manage the search index with a refresh button to update the search index manually;
    • The plugin automatically updates search indexes when documents in the CMS are created, updated or deleted with afterChange and afterDelete hooks;
  • A search endpoint to retrieve search results based on the search index. To each result a rating is assigned based on the search query and the fields weights. The results can be paginated and are sorted by rating in descending order;
  • A search-sync endpoint to manually sync the search index with the documents in the CMS.

this library is for internal usage and not production ready

Readme

Keywords

Package Sidebar

Install

npm i @websolutespa/payload-plugin-search

Weekly Downloads

141

Version

0.1.1

License

MIT

Unpacked Size

45 kB

Total Files

5

Last publish

Collaborators

  • m.fort
  • giacomo_grassetti
  • federicodiluca
  • cbrualdi
  • actarian
  • websolute-admin