archura
archura

Reputation: 1283

Difference between keyword and text in ElasticSearch

Can someone explain the difference between keyword and text in ElasticSearch with an example?

Upvotes: 101

Views: 62778

Answers (3)

mrudult
mrudult

Reputation: 2570

Along with the other advantages of keyword type in elastic search, one more is that you can store any data type inside of it. Be it string, numeric, date, etc.

PUT /demo-index/
{
  "mappings": {
      "properties": {
        "name": { "type": "keyword" }
      }
    }
}

POST /demo-index/_doc
{
  "name": "2021-02-21"
}

POST /demo-index/_doc
{
  "name": 100
}

POST /demo-index/_doc
{
  "name": "Jhon"
}

Upvotes: 8

CodingBee
CodingBee

Reputation: 1199

The primary difference between the text datatype and the keyword datatype is that text fields are analyzed at the time of indexing, and keyword fields are not. What that means is, text fields are broken down into their individual terms at indexing to allow for partial matching, while keyword fields are indexed as is.

Keyword Mapping

"channel" : {
    "name" : "keyword"
},

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

Upvotes: 22

Tarek Essam
Tarek Essam

Reputation: 4010

keyword type: if you define a field to be of type keyword like this.

 PUT products
{
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "keyword"
        }
      }
    }
  }
}

Then when you make a search query on this field you have to insert the whole value (keyword search) so keyword field.

 POST products/_doc
{
  "name": "washing machine"
}

when you execute search like this:

 GET products/_search
{
  "query": {
    "match": {
      "name": "washing"
    }
  }
}

it will not match any docs. You have to search with the whole word "washing machine".

text type on the other hand is analyzed and you can search using tokens from the field value. a full text search in the whole value:

    PUT products
{
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "text"
        }
      }
    }
  }
}

and the search :

 GET products/_search
{
  "query": {
    "match": {
      "name": "washing"
    }
  }
}

will return a matching documents.

You can check this to more details keyword Vs. text

Upvotes: 139

Related Questions