Home > Software engineering >  Diference between term and match in Elasticsearch in a bool query
Diference between term and match in Elasticsearch in a bool query

Time:04-28

I have a simple document where the _source looks like:

{
    "name" : "myProduct",
    "label" : "isApiisApi",
    "isApi" : 1,
    "sold" : 0
}

I've been trying to create a multiple condition query using bool. The only way that I get it working was by using a match query:

{
  "query": {
    "bool": {
      "must": [
        { "term": { "sold": 0 } },
        { "term": { "isApi": 1 } },
        { "match": { "name": "myProduct" } }
      ]
    }
  }
}

But why doesn't it work when I use the term query (as the final condition):

{
  "query": {
    "bool": {
      "must": [
        { "term": { "sold": 0 } },
        { "term": { "isApi": 1 } },
        { "term": { "name": "myProduct" } }
      ]
    }
  }
}

CodePudding user response:

Tldr;

Elastic text fields upon ingestion passes the data into a analyzer.

By default the standard analyzer is used. Which comes with a token filter named Lowercase.

Your text is indexed in lowercase.

But you are using a term which search for exact match on the indexed data.

In your case myproduct =/= myProduct.

To Reproduce

By default Elastic index, all string like data in two fields.

  • text
  • keyword

For exact match you want to use the keyword version.

See below:

POST /72020272/_doc
{
    "name" : "myProduct",
    "label" : "isApiisApi",
    "isApi" : 1,
    "sold" : 0
}

GET /72020272/_mapping

GET /72020272/_search
{
  "query": {
    "bool": {
      "must": [
        { "term": { "sold": 0 } },
        { "term": { "isApi": 1 } },
        { "term": { "name": "myProduct" } }
      ]
    }
  }
}

GET /72020272/_search
{
  "query": {
    "bool": {
      "must": [
        { "term": { "sold": 0 } },
        { "term": { "isApi": 1 } },
        { "term": { "name.keyword": "myProduct" } }
      ]
    }
  }
}
  • Related