_source 过滤是什么
_source 是 Elasticsearch 保存的文档原始 JSON,搜索响应里默认整段返回。字段过滤就是在返回阶段挑选需要哪些字段:可以整体关闭、用通配符列出字段名,或用 includes 与 excludes 组合。它只影响回显内容,不改变文档怎么被索引、检索与聚合。
基本信息
| 关闭返回 | "_source": false,响应里不带原始文档 |
|---|---|
| 数组写法 | "_source": ["obj.*", "user.name"],命中即包含 |
| 对象写法 | { "includes": [...], "excludes": [...] },先包含再排除 |
| 作用范围 | 只影响响应回显,不改变倒排索引与 doc_values |
| 替代手段 | stored_fields 与 docvalue_fields 可取出索引里的列值 |
典型使用场景
- 列表页只返回标题、时间等少量字段,降低网络与序列化开销
- 避免把密码、密钥等敏感字段回传给前端
- 宽表查询按需取字段,防止单次响应体积失控
- 调试阶段先看 _source 的完整结构,再决定过滤规则
- 导出数据时只保留需要的列,减小下游存储与处理压力
常用写法
常用写法
# 只取指定字段:先包含,再排除敏感字段
GET /my-index/_search
{ "_source": { "includes": ["title", "user.*"], "excludes": ["user.password"] },
"query": { "match_all": {} } }
# 数组写法,等价于包含列表
GET /my-index/_search
{ "_source": ["title", "user.name"], "query": { "match_all": {} } }
# 完全不要原始文档,只要聚合结果
GET /my-index/_search
{ "_source": false, "size": 0, "aggs": { "n": { "terms": { "field": "status" } } } }
# 不取 _source,只取索引中的列值
GET /my-index/_search
{ "_source": false, "docvalue_fields": ["ts", "status"], "size": 10 }写法与行为
| 写法 | 语义 | 注意 |
|---|---|---|
| _source: false | 响应不返回原始文档 | 需要字段值时必须另做指定 |
| _source: ["a", "b"] | 只返回列出的字段 | 通配符按路径逐层展开 |
| includes 与 excludes | 先按包含挑,再按排除去掉 | 排除优先于包含 |
| docvalue_fields | 取 doc_values 中的列值 | 只适用于支持列存的字段 |
_source 过滤只减少网络传输与反序列化开销,不会减少索引在磁盘上的占用;要省空间得从 mapping 的 index、doc_values 参数入手。
关闭 _source 后文档无法被重新索引、也无法用脚本更新,只有确认数据可以从上游重放时才可以这么做。