区别

match

全文搜索, 通常用于对text类型字段的查询,会对进行查询的文本先进行分词操作,如下图

Elasticsearch match和term查询的区别_elasticsearch


term

精确查询,通常用于对keyword和有精确值的字段进行查询,不会对进行查询的文本进行分词操作,精确匹配,如下图

Elasticsearch match和term查询的区别_java编程思想_02

实例说明

  1. 新建索引
  2. 添加数据
  3. 测试分词效果
  4. 测试match查询
  5. 测试term查询

新建索引
添加一个text类型的字段,使用ik_max_word分析器

PUT /testquery
{
"mappings": {
"books":{
"properties": {
"bookName":{
"type":"text",
"analyzer": "ik_max_word"
}
}
}
}
}

添加数据

POST /testquery/books
{
"bookName":"Java编程思想"
}

测试分词效果

GET /_analyze
{
"analyzer": "ik_max_word",
"text": ["Java编程思想"]
}

结果

{
"tokens": [
{
"token": "java",
"start_offset": 0,
"end_offset": 4,
"type": "ENGLISH",
"position": 0
},
{
"token": "编程",
"start_offset": 4,
"end_offset": 6,
"type": "CN_WORD",
"position": 1
},
{
"token": "思想",
"start_offset": 6,
"end_offset": 8,
"type": "CN_WORD",
"position": 2
}
]
}

所以,Java编程思想 实际分词效果如下

Elasticsearch match和term查询的区别_term_03


测试match查询,进行分词操作

查询 Java

先看看 Java 的分词效果

GET /_analyze
{
"analyzer": "ik_max_word",
"text": ["Java"]
}
{
"tokens": [
{
"token": "java",
"start_offset": 0,
"end_offset": 4,
"type": "ENGLISH",
"position": 0
}
]
}

存在, 所以是可以查询到的

POST /testquery/books/_search
{
"query": {
"match": {
"bookName": "Java"
}
}
}
{
"took": 60,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.2876821,
"hits": [
{
"_index": "testquery",
"_type": "books",
"_id": "vYOz-msB_TzP5bFY5JlL",
"_score": 0.2876821,
"_source": {
"bookName": "Java编程思想"
}
}
]
}
}

查询 Java思想
查看分词效果

GET /_analyze
{
"analyzer": "ik_max_word",
"text": ["Java思想"]
}
{
"tokens": [
{
"token": "java",
"start_offset": 0,
"end_offset": 4,
"type": "ENGLISH",
"position": 0
},
{
"token": "思想",
"start_offset": 4,
"end_offset": 6,
"type": "CN_WORD",
"position": 1
}
]
}

存在, 所以也是可以查询到的

POST /testquery/books/_search
{
"query": {
"match": {
"bookName": "Java思想"
}
}
}
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.5753642,
"hits": [
{
"_index": "testquery",
"_type": "books",
"_id": "vYOz-msB_TzP5bFY5JlL",
"_score": 0.5753642,
"_source": {
"bookName": "Java编程思想"
}
}
]
}
}

测试term查询, 不进行分词操作
查询 java
查看上面的分词结果, java是在分词结果中的,所以可以查询到

POST /testquery/books/_search
{
"query": {
"term": {
"bookName": "java"
}
}
}
{
"took": 7,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 0.2876821,
"hits": [
{
"_index": "testquery",
"_type": "books",
"_id": "vYOz-msB_TzP5bFY5JlL",
"_score": 0.2876821,
"_source": {
"bookName": "Java编程思想"
}
}
]
}
}

查询 Java
Java不在上面的分词结果中, 结果当然就查询不到

POST /testquery/books/_search
{
"query": {
"term": {
"bookName": "Java"
}
}
}
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
}
}