随笔 20250413 Elasticsearch 的 term 查询
你这个问题非常经典,来自于 Elasticsearch 的 term 查询是 ✅精确匹配(case-sensitive,大小写敏感)!
🧨 为什么查不到 "World"?
你的查询语句是:
GET /movie/_search
{
"query": {
"term": {
"tagline": "World"
}
}
}
这条语句的含义是:
查找
tagline字段中精确值为 "World"(区分大小写) 的文档。
🔍 但是你的数据中可能是:
{
"tagline": "world"
}
或者:
{
"tagline": "the world is beautiful"
}
这种情况下,term 查询根本不会命中,因为:
term查询不会分析(不分词)、不做小写转换、只查精确 token。
✅ 正确写法:使用 match 查询(可自动分词 + 忽略大小写)
GET /movie/_search
{
"query": {
"match": {
"tagline": "World"
}
}
}
🔥
match会将 "World" 转为 "world",也会对tagline字段做分词处理,因此可以模糊匹配、大小写不敏感。
❓ 但是 term 一定没用吗?
不是,如果你明确知道 tagline 是 keyword 类型字段(未分词),你可以查它的 .keyword:
GET /movie/_search
{
"query": {
"term": {
"tagline.keyword": "World"
}
}
}
但前提是:你需要在字段映射(mapping)中配置了 .keyword(text + keyword)这种类型。
🧠 总结:
| 你的目的 | 推荐查询方式 |
|---|---|
| 查 "包含 world" | ✅ match 查询 |
| 精确查 "World"(大小写) | ✅ term + .keyword(非分词字段) |
| 查部分词、模糊匹配 | ✅ match / match_phrase |
需要我帮你分析你 index 的 mapping 吗?你可以贴一下 /movie/_mapping 的结构,我可以告诉你字段类型是否支持 .keyword,从根上解决 💡
