SexyMF
SexyMF

Reputation: 11185

Elasticsearch exact match query (not fuzzy)

I have the following query over a string field:

const query = {
        "query": {
          "match_phrase": {
            name:  "ron"
          }
        },
        "from": 0,
        "size": 10
      };

these are the names I have in the database

1. "ron"
2. "ron martin"
3. "ron ron"
4. "ron howard"

the result of this query is very fuzzy, all the of the rows are returned instead of row number 1 only. It's like it is performing "contains" instead of "equals".

Thanks

Upvotes: 0

Views: 889

Answers (1)

Bhavya
Bhavya

Reputation: 16192

In your case, all the documents are returning, because all the documents have ron in them.

If you want that only the exact field should match, then you need to add keyword subfield to the name field. This uses the keyword analyzer instead of the standard analyzer (notice the ".keyword" after name field). Try out this below query -

Index Mapping:

{
  "mappings": {
    "properties": {
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
    }
  }
}

Index Data:

{
    "name":"ron"
}
{
    "name":"ron martin"
}
{
    "name":"ron ron"
}
{
    "name":"ron howard"
}
{
    "name": "john howard"
}

Search Query:

{
  "query": {
    "match_phrase": {
      "name.keyword": "ron"
    }
  },
  "from": 0,
  "size": 10
}

Search Result:

"hits": [
      {
        "_index": "64982377",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.2039728,
        "_source": {
          "name": "ron"
        }
      }
    ]

Update 1:

Based on the comments below, if you want to search for both exact match and fuzzy match (according to your requirement), then you can use multi_match query.

Search Query:

{
  "query": {
    "multi_match": {
      "query": "howard",
      "fields": [
        "name",
        "name.keyword"
      ],
      "type": "phrase"
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "64982377",
        "_type": "_doc",
        "_id": "4",
        "_score": 0.83740485,
        "_source": {
          "name": "ron howard"
        }
      },
      {
        "_index": "64982377",
        "_type": "_doc",
        "_id": "5",
        "_score": 0.83740485,
        "_source": {
          "name": "john howard"
        }
      }
    ]

Upvotes: 1

Related Questions