Abel
Abel

Reputation: 1614

Exact match search on text field

I'm using ElasticSearch to search data. My data contains text field and when I tried to match query on input, it outputs the input with another string.

_mapping

"direction": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "keyword",
      "ignore_above": 256
    }
  }
}

Elastic Data

[
  {
   direction: "North"
  },
  {
   direction: "North East"
  }
]

Query

{
  match: {
    "direction" : {
      query: "North",
      operator : "and"
    }
  }
}

Result

[
  {
   direction: "North"
  },
  {
   direction: "North East"
  }
]

Expected Result

[
  {
   direction: "North"
  }
]

Noted: It should output exact match direction

Upvotes: 0

Views: 2805

Answers (3)

Rayies Banka
Rayies Banka

Reputation: 34

Try this { "query" : { "bool" : { "must": { "term": { "direction": "North" } } } } }

Upvotes: 0

Kamal Kunjapur
Kamal Kunjapur

Reputation: 8840

You may want to look at Term Queries which are used on keyword datatype to perform exact match searches.

POST <your_index_name>/_search
{
    "query": {
        "term": {
            "direction.keyword": {
                "value": "North"
            }
        }
    }
}

The reason you observe what you observe, is because you are querying on Text field using Match Query. The values of the text field are broken down into tokens which are then stored in inverted indexes. This process is called Analysis. Text fields are not meant to be used for exact match.

Also note that whatever words/tokens you'd mention in Match Query, they would also go through the analysis phase before getting executed.

Hope it helps!

Upvotes: 3

dtrv
dtrv

Reputation: 753

Based on you mapping, you should not search on field direction but on direction.keyword if you want exact match. The field direction is type text and gets analyzed - in your case to the words north and east.

Upvotes: 1

Related Questions