简体   繁体   中英

Elasticsearch match vs. term in filter

I don't see any difference between term and match in filter:

POST /admin/_search
{
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "partnumber": "j1knd"
                    }
                }
            ]
        }
    }
}

And the result contains not exactly matched partnumbers too, eg: "52527.J1KND-H"

Why?

Term queries are not analyzed and mean whatever you send will be used as it is to match the tokens in the inverted index, while match queries are analyzed and the same analyzer applied on the fields, which is used at index time and accordingly matches the document.

Read more about term query and match query . As mentioned in the match query:

Returns documents that match a provided text, number, date or boolean value. The provided text is analyzed before matching.

You can also use the analyze API to see the tokens generated for a particular field.

Tokens generated by standard analyzer on 52527.J1KND-H text.

POST /_analyze
{
    "text": "52527.J1KND-H",
    "analyzer" : "standard"
}

{
    "tokens": [
        {
            "token": "52527",
            "start_offset": 0,
            "end_offset": 5,
            "type": "<NUM>",
            "position": 0
        },
        {
            "token": "j1knd",
            "start_offset": 6,
            "end_offset": 11,
            "type": "<ALPHANUM>",
            "position": 1
        },
        {
            "token": "h",
            "start_offset": 12,
            "end_offset": 13,
            "type": "<ALPHANUM>",
            "position": 2
        }
    ]
}

Above explain to you why you are getting the not exactly matched partnumbers too, eg: "52527.J1KND-H", I would take your example and how you can make it work.

Index mapping

{
  "mappings": {
    "properties": {
      "partnumber": {
        "type": "text",
        "fields": {
          "raw": { 
            "type":  "keyword" --> note this
          }
        }
      }
    }
  }
}

Index docs

{
  "partnumber" : "j1knd"
}

{
  "partnumber" : "52527.J1KND-H"
}

Search query to return only the exact match

{
    "query": {
        "bool": {
            "filter": [
                {
                    "term": {
                        "partnumber.raw": "j1knd" --> note `.raw` in field
                    }
                }
            ]
        }
    }

Result

 "hits": [
      {
        "_index": "so_match_term",
        "_type": "_doc",
        "_id": "2",
        "_score": 0.0,
        "_source": {
          "partnumber": "j1knd"
        }
      }
    ]

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM