Synonyms with Search API

Submitted by christophe on Sun, 08/03/2020 - 17:34
Synonyms

 

Here is a really simple way to handle synonyms (or extra keywords) using Search API out of the box with a database server and no custom code involved.

Use case

We want to do a full text search based on synonyms that does not appear on the frontend.
These ones should be set from the Tags vocabulary.
The method should be flexible regarding translations, available for content editors and easily generalizable.

Content model

  • Article node type with Tags term reference
  • The Tags vocabulary have a Synonym plain text field with unlimited number of values

Add a synonym field to the Tags vocabulary

Tags synonym text field

So we end up with something like this for the Tags term

Term synonyms

and this for the Article node

Cherries article node

Setup

Install Search API with Database Search Defaults, it provides a fully working configuration with no other backend needed than the DB. The only requirement for this demo is to start with a vanilla Drupal setup or an existing one that still contains the Article, Tags and Comments configuration.

composer require drupal/search_api
drush en search_api_db_defaults -y

Site building

Add a new Taxonomy term view mode of Search index (/admin/structure/display-modes/view)

Add taxonomy term view mode

Enable it for the Tags vocabulary (/admin/structure/taxonomy/manage/tags/overview/display) and configure it

Enable search index vocabulary view mode

Search index term display

Render it on the Article Search index display that is already configured by Search API (/admin/structure/types/manage/article/display/search_index).

Search index node display

The Default search index from the Database Search Defaults module is already configured to make use of this display. This can be checked with /admin/config/search/search-api/index/default_index/fields (edit Rendered item).

Search index rendered item

Re-index the content (/admin/config/search/search-api/index/default_index)

Testing

Head to /search/content and type a keyword that is not displayed on the frontend.

Search synonym

Alternate setup

This setup is site building based, backend agnostic and can be used for simple use cases.

If you are looking after a module that supports the synonyms.txt format used by Solr, you may have a look at the Search API Synonym module. It also supports a plugin system that allows to export / import other formats.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.