Different response of match and term query using synonyms

Hi all,
I have recently started working with elastic search. I read about synonyms and how expansion and replacement works in synonyms but when I perform a match query, resultant response seems like synonyms worked as expansions, and when I perform term query, resultant response matches the expectations of doing replacement.
Below is my setting

    {
    "settings": {
        "index" : {
            "analysis" : {
                "filter" : {
                    "synonym_filter" : {
                        "type" : "synonym_graph",
                        "synonyms" : [
                            "cat => pet",
                            "dog => pet"
                        ],
                        "tokenizer": "keyword"
                    }
                },
                "analyzer" : {
                    "synonym_analyzer" : {
                        "tokenizer" : "standard",
                        "filter" : ["lowercase", "synonym_filter"] 
                    }
                }
            }
        }
    },
    "mappings": {
            "properties": {
              "title": { 
                "type": "text",
                "analyzer": "synonym_analyzer"
              }
        }
    }
}

I have indexed three documents with titles cat, dog, and pet respectively.

  • When I search "cat" with match query, it returns cat along with dog and pet. And same response for all three documents when I search either of it.
  • When I search "cat" with term query, it returns cat as expected
  • When I search "pet" with term query, it returns all three i.e. cat, dog, and pet as expected.

Is there any way I can perform match query where synonyms don't expand but replace like happening in term query?

What is preferred way of using synonyms with match query?

Why there is difference in both queries for same synonyms?

Term Query

        {
            "explain": true,
            "query": {
                "bool": {
                    "filter": {
                        "term": {
                            "title": "cat"
                        }
                    }
                }
            }
        }

Match Query

        {
            "explain": true,
            "query": {
                "bool": {
                    "must": {
                        "match": {
                            "title": "cat"
                        }
                    }
                }
            }
        }

Thanks in advance.

match query runs the analyzer while term query does not. So searching with a matchquery for cat is turned into cat pet by the analyzer. Configuring separate analyzer for indexing and search, where only one contains the synonym_filter, should fix your problem.

Thanks for the reply Daneil! Can you please explain it more through mapping?

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.