1、查询基础dsl结构
{
"from": 0,
"size": 20,
"sort": [
{
"timestamp": {
"order": "desc"
}
}
],
"_source": {
"includes": ["title", "status", "created_at"],
"excludes": ["details"]
},
"query": {
"bool": {
"must": [
{
"match": {
"title": "Elasticsearch"
}
},
{
"term": {
"status": "published"
}
}
],
"should": [
{
"match_phrase": {
"content": "high performance search"
}
}
],
"must_not": [
{
"range": {
"created_at": {
"lt": "now-1y"
}
}
}
],
"filter": [
{
"range": {
"created_at": {
"gte": "2024-01-01",
"lte": "2024-12-31"
}
}
},
{
"term": {
"category.id": 101
}
}
]
}
},
"aggs": {
"group_by_status": {
"filter":{
"bool":{
}
},
"terms": {
"field": "status"
},
"aggs": {
"avg_age": {
"avg": {
"field": "age"
}
}
}
},
"stats_by_date": {
"date_histogram": {
"field": "created_at",
"calendar_interval": "month"
},
"aggs": {
"max_score": {
"max": {
"field": "score"
}
}
}
}
},
"highlight": {
"fields": {
"title": {},
"content": {
"fragment_size": 150
}
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"]
},
"track_total_hits": true,
"timeout": "10s"
}
结构 说明
from & size 分页参数:from 起始偏移,size 每页数量。用于实现分页(注意深度分页性能问题)
sort 排序规则,支持字段排序(如 timestamp)、_score、地理距离等
_source 控制返回字段:includes 指定返回字段,excludes 排除字段,节省带宽
query 查询主体,决定哪些文档匹配
→ bool 复合查询核心,支持 must, should, must_not, filter
• must 所有条件必须匹配,影响 _score
• should 满足其中一个或多个(可设 minimum_should_match)
• must_not 必须不匹配,不影响评分
• filter 过滤条件,不计算相关性评分,可被缓存,性能高
aggs 聚合分析,用于统计、分组、指标计算等
• terms 按字段值分组
• date_histogram 按时间间隔分组
• avg, sum, max, min, cardinality 指标聚合
highlight 高亮匹配关键词,常用于搜索结果展示
track_total_hits 是否精确统计总命中数(大数据集可设为 false 提升性能)
timeout 查询超时时间,防止长时间阻塞
常见查询子句类型(可在 must/filter/should 中使用)
查询类型 示例 用途
match 全文匹配,分词后查询 搜索标题、内容
term 精确值匹配(不分词) 状态、ID、枚举
terms 多个精确值匹配 status: ["active", "pending"]
range 范围查询 时间、数值范围
match_phrase 短语匹配(顺序+ proximity) “quick brown fox”
wildcard 通配符查询 log-2024-*
regexp 正则表达式 复杂模式匹配
exists 字段是否存在 {"exists": {"field": "email"}}
prefix 前缀匹配 user: "alice"