| Engineering | Development | Search | How to add Taggings and Synonyms to ElasticSearch Rails
How to add Taggings and Synonyms to ElasticSearch Rails

Overview

This guide is a continuation of How to deploy ElasticSearch on a Rails app using Digital Ocean and will walk through how to use synonym search in Elastic Search.

Add a filter and analyzer to your Chewy Index file

class JobIndex < Chewy::Index
  settings analysis: {
    "filter": {
      "synonym_filter": {
        "type": "synonym",
        "ignore_case": true,
        "synonyms": [File.read(Rails.root + 'db/fixtures/search_synonyms.json')]
      }
    },
    "analyzer": {
      "synonym_analyzer": {
        "tokenizer": "standard",
        "filter": ["lowercase", "synonym_filter"] 
      }
    }
  }
  ...

Add the synonym analyzer to the specified fields

class JobIndex < Chewy::Index
  ...
  define_type Job do 
    field "title", type: 'text'
    field "category_list", type: 'text', analyzer: 'synonym_analyzer', value: -> (job) {
      job.category_list
    }
  end
end

Create a list of synonyms

Create a new file db/fixtures/search_synonyms.json and store a comma separated list of synonyms.

"customer service, customer success, customer support, chat agent, chat support",
"developer, development, coding, coder, software developer, software engineer",

Test

Create a post with a category tag of coder and search for developer. The post should show up.