Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

Elasticsearch term query issue

enter image description here

enter image description here

As the pictures show the record field of dispatchvoucher value is "True" But when I searched with the term it cannot found any record. when I changed the value to "true", the result match. What's the reason for this? enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned in the documentation :

Avoid using the term query for text fields.

By default, Elasticsearch changes the values of text fields as part of analysis. This can make finding exact matches for text field values difficult.

To search text field values, use the match query instead.

The standard analyzer is the default analyzer which is used if none is specified. It provides grammar-based tokenization.

GET /_analyze
    {
      "analyzer" : "standard",
      "text" : "True"
    }

The token generated is -

{
  "tokens": [
    {
      "token": "true", 
      "start_offset": 0,
      "end_offset": 4,
      "type": "<ALPHANUM>",
      "position": 0
    }
  ]
}

Term query returns documents that contain an exact term in a provided field. Since True gets tokenized to true, so when you are using the term query for "dispatchvoucher": "True", it will not show any results.

You can either change your index mapping to

{
  "mappings": {
    "properties": {
      "dispatchvoucher": {
        "type": "keyword"
      }
    }
  }
}

OR You need to add .keyword to the dispatchvoucher field. This uses the keyword analyzer instead of the standard analyzer (notice the ".keyword" after dispatchvoucher field).

Adding a working example with index data, search query, and search result

Index Data:

{
  "dispatchvoucher": "True"
}

Search Query:

{
  "query": {
    "bool": {
      "filter": {
        "term": {
          "dispatchvoucher.keyword": "True"
        }
      }
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "65605120",
        "_type": "_doc",
        "_id": "1",
        "_score": 0.0,
        "_source": {
          "dispatchvoucher": "True"
        }
      }
    ]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...