Elasticsearch 入门:用 mapping 和 refresh 理解搜索流程
了解 Elasticsearch 的 mapping、分片与 refresh 如何配合,以及写入成功后为何不一定立即能搜到。
Elasticsearch 入门:用 mapping 和 refresh 理解搜索流程
向 Elasticsearch 写入成功,不代表文档马上会出现在搜索结果中。系统按 mapping 分析并索引文档,将其分配到分片,再通过 refresh 让最近的变更可供搜索。理解这个过程有助于选择字段类型、规划分片,并诊断写入后立即查询却找不到的情况。本文依据 2026 年 11 月 23 日查阅的 Elastic 官方文档;示例仅用于说明,未在集群上运行。
文档、mapping 与设置
索引是存储和搜索相关 JSON 文档的单位。mapping 定义字段类型和索引方式;设置则控制分片数、refresh 间隔等。text 会被分析器拆分成词项,适合全文搜索;keyword 保留整体值,适合精确过滤、排序和聚合。同一字段可以用 multi-field 提供两种表示。动态 mapping 会从输入推断类型,便于探索;但看起来像日期的字符串或数字标识符可能被误判。生产环境通常应明确指定 mapping。更改字段类型一般需要创建新索引并重新索引文档。
分片与搜索可见性
每份文档属于一个主分片。副本分片是主分片的复制,可提高冗余并分担读取搜索。主分片数量在创建索引时确定,副本数量之后可调整。应按数据量和负载规划主分片。Elasticsearch 是近实时系统:写入成功后,refresh 之前的变更可能还不能被搜索。Elastic 文档列出的默认间隔是 Elastic Stack 1 秒、Elastic Cloud Serverless 5 秒;配置和搜索空闲行为会影响刷新,因此它们不是每次请求的保证延迟。
通常省略refresh并使用默认行为。若某个流程必须在响应前搜到刚写入的文档,refresh=wait_for会等待下一次 refresh,而不是立即强制刷新。refresh=true强制立即可见,但频繁使用会产生较小 segment,增加索引、搜索和合并工作。关闭自动 refresh 时,wait_for可能一直等到其他操作触发刷新。
示例与排查
下面的示例将商品名设为全文字段,将类别和 SKU 设为精确值,将价格设为数值。它只是说明示例,没有实际执行:
Sources
[Elasticsearch index fundamentals](https://www.elastic.co/docs/manage-data/data-store/index-basics)
[The refresh parameter](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/refresh-parameter)
[Text field type](https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/text)
[Clusters, nodes, and shards](https://www.elastic.co/docs/deploy-manage/distributed-architecture/clusters-nodes-shards)
[Match query](https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-match-query)