Dotnetsqlcoder
Dotnetsqlcoder

Reputation: 890

Weird results from Elastic search when using a synonym analyzer

When i run this query

"multi_match": {
    "query": "paper copier ", 
    "fields": [ "allStringFields" ],
    "type": "cross_fields",
    "operator": "and",
    "analyzer": "synonym"   
}

i get 1342 results

But when i run this query (notice word order)

 "multi_match": {
    "query": " copier paper ", 
    "fields": [ "allStringFields" ],
    "type": "cross_fields",
    "operator": "and",
    "analyzer": "synonym"   
 }

I get zero results

I am using synonym analyzer and it is the cause for this behavior

Is there a solution to this ?

Upvotes: 1

Views: 245

Answers (1)

Bhavya
Bhavya

Reputation: 16172

Adding a working example with index data, mapping, search query, and search result. In the below example, I have taken two synonyms table and tables

I get zero results

Please go through your index mapping once again. According to the below example, the search keyword is table chair, this is to be searched in both the fields title and content. The below query will return the documents that contain both table AND chair. To get a detailed explanation, refer to ES documentation on the Multi match query and synonym token filter.

Index Mapping:

{
  "settings": {
    "index": {
      "analysis": {
        "filter": {
          "synonym_filter": {
            "type": "synonym",
            "synonyms": [
              "table, tables"
            ]
          }
        },
        "analyzer": {
          "synonym_analyzer": {
            "filter": [
              "lowercase",
              "synonym_filter"
            ],
            "tokenizer": "standard"
          }
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text"
      }
    }
  }
}

Index Data:

{ "title": "table chair" }
{ "title": "tables chair" }
{ "title": "table fan" }
{ "title": "light fan", "content": "chair" }

Search Query:

{
    "query": {
        "multi_match": {
            "query": "table chair",
            "operator": "and",
            "type":"cross_fields",
            "fields": [
                "title","content"
            ],
            "analyzer": "synonym_analyzer"
        }
    }
}

Search Result:

"hits": [
      {
        "_index": "synonym",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.7227666,
        "_source": {
          "title": "table chair"
        }
      },
      {
        "_index": "synonym",
        "_type": "_doc",
        "_id": "2",
        "_score": 1.3862942,
        "_source": {
          "title": "tables chair"
        }
      }
    ]

Searching table chair or chair table, gives the same search result as shown above.

Upvotes: 1

Related Questions