1. 基本文档操作
1.1 索引文档(新增/替换)
POST /my_index/_doc
{
"title": "Elasticsearch 入门",
"author": "张三",
"publish_date": "2026-01-20"
}
PUT /my_index/_doc/1
{
"title": "Elasticsearch 入门",
"author": "张三",
"publish_date": "2026-01-20"
}
1.2 获取文档
GET /my_index/_doc/1
1.3 查询文档(基础)
# 按字段匹配
GET /my_index/_search
{
"query": {
"match": {
"author": "张三"
}
}
}
1.4 更新文档
POST /my_index/_update/1
{
"doc": {
"title": "Elasticsearch 从入门到精通"
}
}
1.5 删除文档
DELETE /my_index/_doc/1
2. 组合搜索(复合/布尔查询)
组合搜索(Compound Query)允许你通过布尔逻辑(must、should、must_not、filter)组合多个条件,常用于复杂的检索需求。
2.1 Bool 查询(布尔查询)基本用法
GET /my_index/_search
{
"query": {
"bool": {
"must": [
{ "match": { "author": "张三" } },
{ "match": { "title": "Elasticsearch" } }
],
"filter": [
{ "range": { "publish_date": { "gte": "2025-01-01", "lte": "2026-12-31" } } }
],
"must_not": [
{ "match": { "title": "高级" } }
]
}
}
}
说明:
must:文档必须匹配的条件(相当于 AND)
should:应当匹配至少一项(相当于 OR,可设置 minimum_should_match)
filter:与 must 类似,但不影响相关性评分,常用于过滤
must_not:必须不匹配的条件(相当于 NOT)
2.2 只用 should(或操作)
GET /my_index/_search
{
"query": {
"bool": {
"should": [
{ "match": { "author": "张三" } },
{ "match": { "author": "李四" } }
],
"minimum_should_match": 1
}
}
}
说明: “作者”为“张三”或“李四”的文档都会被查出来。
2.3 must、should 结合使用
GET /my_index/_search
{
"query": {
"bool": {
"must": [
{ "match": { "title": "Elasticsearch" } }
],
"should": [
{ "match": { "author": "张三" } },
{ "match": { "author": "李四" } }
],
"minimum_should_match": 1
}
}
}
说明: “标题”包含“Elasticsearch”,且作者为“张三”或“李四”其一。
2.4 多条件范围查询(range)
GET /my_index/_search
{
"query": {
"bool": {
"filter": [
{ "range": { "publish_date": { "gte": "2025-01-01", "lt": "2026-01-01" } } },
{ "range": { "score": { "gte": 60 } } }
]
}
}
}
说明: 检索发表时间在 2025 年,且分数大于等于 60 的文档。
2.5 terms 查询(多个指定值)
GET /my_index/_search
{
"query": {
"terms": {
"author.keyword": ["张三", "李四", "王五"]
}
}
}
说明: “author”值为“张三”、“李四”或“王五”。
3. 更多操作
- 使用 nested 查询嵌套对象,使用 aggregations 聚合统计,更多复杂场景请查阅官方文档。
- 可通过 Kibana Dev Tools、Postman、curl 工具尝试上述命令。
参考资料