richardwhitney
richardwhitney

Reputation: 532

How do I implement acronyms as synonyms in elasticsearch?

I have the following settings in my request:

    var synonyms = [
        "usa, united states of america",
        "oa, other acronym"
    ]
        
    "settings" : {
        "index" : {
            "analysis" : {
                "analyzer" : {
                    "synonym" : {
                        "type" : "custom",
                        "tokenizer" : "whitespace",
                        "filter" : ["lowercase", "synonym"]
                    }
                },
                "filter" : {
                    "synonym" : {
                        "type" : "synonym",
                        "lenient": true,
                        "synonyms" : synonyms
                    },
                }
            }
        }
    },
    "search": {
        "size": 50,
        "query": {
            "bool": {
                "should": [
                    {"match": {'ANNOTATIONS': {"query": "usa", boost: 2}}},
                ]
            }
         }
     }

when I search on usa, I need to rank results with United States of America equally with usa

so far, I am at a total loss. Can anyone assist?

Here's hoping so, Cheers!

Upvotes: 0

Views: 600

Answers (1)

Bhavya
Bhavya

Reputation: 16172

You need to define the analyzer, in the mappings part of the particular field also

Adding a working example with index data, mapping, search query and search result

Index Mapping:

{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "synonym": {
            "tokenizer": "whitespace",
            "filter": [
              "synonym"
            ]
          }
        },
        "filter": {
          "synonym": {
            "type": "synonym",
            "synonyms": [
              "usa, united states of america",
              "ny, new york"
            ]
          }
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "ANNOTATIONS": {
        "type": "text",
        "analyzer": "synonym"
      }
    }
  }
}

Index Data:

{
    "ANNOTATIONS":"united states of america"
}
{
    "ANNOTATIONS":"usa"
}

Search Query:

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "ANNOTATIONS": {
              "query": "usa"
            }
          }
        }
      ]
    }
  }
}

Search Result:

 "hits": [
      {
        "_index": "67274014",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.86133814,
        "_source": {
          "ANNOTATIONS": "usa"
        }
      },
      {
        "_index": "67274014",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.86133814,
        "_source": {
          "ANNOTATIONS": "united states of america"
        }
      }
    ]

Upvotes: 1

Related Questions