引言:ElasticSearch 的定位与应用
ElasticSearch 是一个分布式搜索和分析引擎。想象它是一个超大的图书馆:
- 可以快速找到任何书籍(搜索能力)
- 可以统计各类书籍的数量(分析能力)
- 可以随时添加新书架(可扩展性)
- 即使某个书架损坏,其他书架的书仍然可读(高可用性)
主要应用场景:
- 网站搜索
- 日志分析
- 指标监控
- 业务数据分析
一、基础概念
1.1 索引(Index)
什么是索引?
把索引理解为一个数据库:
- 传统数据库:Database → Table → Row → Column
- ElasticSearch:Index → Type* → Document → Field
(*注:Type 概念在新版本已弃用)
// 创建索引
PUT /books
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"title": {
"type": "text" },
"author": {
"type": "keyword" },
"publish_date": {
"type": "date" }
}
}
}
索引命名规范:
- 只能小写字母
- 不能包含 , /, *, ?, ", <, >, |,
- 不能以 -, _, + 开头
- 不能是 . 或 …
1.2 文档(Document)
文档是索引中的一条记录,类似数据库中的一行数据。
// 添加文档
PUT /books/_doc/1
{
"title": "ElasticSearch 入门指南",
"author": "张三",
"publish_date": "2024-01-01"
}
文档特点:
- 使用 JSON 格式
- 每个文档都有唯一的 _id
- 文档字段可以动态添加
1.3 字段类型(Field Types)
常见数据类型:
{
"mappings": {
"properties": {
"text_field": {
"type": "text" }, // 全文搜索
"keyword_field": {
"type": "keyword" }, // 精确值
"date_field": {
"type": "date" }, // 日期
"long_field": {
"type": "long" }, // 长整型
"double_field": {
"type": "double" }, // 浮点型
"boolean_field": {
"type": "boolean" }, // 布尔值
"object_field": {
"type": "object" } // 对象
}
}
}