PUT my_index
{
"mappings": {
"properties": {
"name": {
"type": "keyword"
}
}
}
}
POST my_index/products
{
"name":"washing machin"
}
GET my_index/_search
{
"query": {
"term": {
"name": "washing"
}
}
}
出现查询不到添加的记录。
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 0,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
}
}
原因是,字段为keyword类型,是整个字段建立的索引,term查询的时候,查询条件也是作为整体进行搜索,所以没有和搜索条件name="washing"匹配的记录。
修改查询条件如下:
GET my_index/_search
{
"query": {
"term": {
"name": "washing machin"
}
}
}
这样就可以查询到记录了:
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.18232156,
"hits" : [
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.18232156,
"_source" : {
"name" : "washing machin"
}
}
]
}
}
PUT my_index/_mapping
{
"properties": {
"tag": {
"type": "text"
}
}
}
POST my_index/_doc/2
{
"name":"washing machine",
"tag":"electric household"
}
POST /my_index/_search
{
"query": {
"term": {
"tag": "household"
}
}
}
查询到添加的记录
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.2876821,
"hits" : [
{
"_index" : "my_index",
"_type" : "_doc",
"_id" : "2",
"_score" : 0.2876821,
"_source" : {
"name" : "washing machine",
"tag" : "electric household"
}
}
]
}
}
从以上查询结果可以验证,term查询在keyword字段和text字段的区别,keyword字段是将整个字段信息作为索引,term查询需要查询条件与keyword内容完全匹配才能查询到。text字段会进行分词建立索引,term查询时,只要term查询条件能够匹配分词后建立的索引即可查询到。