# Elastic – elasticsearch
## 项目介绍
elasticsearch 是一个开源的分布式搜索和分析引擎,由Elastic公司开发,该项目拥有 76385 颗星标。Elasticsearch基于Lucene构建,提供了实时的分布式搜索、分析和存储功能,是目前最流行的企业级搜索引擎之一。
## 主要特点
– **分布式架构**:支持水平扩展,处理海量数据
– **实时搜索**:近实时的搜索和分析能力
– **全文搜索**:强大的全文搜索功能,支持复杂查询
– **结构化搜索**:支持结构化数据的搜索和过滤
– **分析能力**:内置聚合和分析功能
– **RESTful API**:通过HTTP API进行操作
– **高可用性**:支持数据复制和故障转移
– **多语言支持**:支持多种编程语言的客户端
## 核心概念
– **索引(Index)**:类似于数据库中的数据库
– **类型(Type)**:类似于数据库中的表(在7.0+版本中已移除)
– **文档(Document)**:类似于数据库中的行
– **字段(Field)**:类似于数据库中的列
– **映射(Mapping)**:定义文档的结构和字段类型
– **分片(Shard)**:索引的水平分区
– **副本(Replica)**:分片的副本,提供高可用性
## 使用方式
### 安装
“`bash
# 下载并安装
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.14.0-linux-x86_64.tar.gz
tar -xzf elasticsearch-7.14.0-linux-x86_64.tar.gz
cd elasticsearch-7.14.0
# 启动服务
./bin/elasticsearch
# 或使用Docker
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.14.0
docker run -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node” docker.elastic.co/elasticsearch/elasticsearch:7.14.0
“`
### 基本操作
“`bash
# 创建索引
curl -X PUT “localhost:9200/my-index”
# 添加文档
curl -X POST “localhost:9200/my-index/_doc/1” -H “Content-Type: application/json” -d ‘{
“title”: “Elasticsearch Guide”,
“content”: “Elasticsearch is a distributed search engine”,
“tags”: [“search”, “elasticsearch”],
“date”: “2023-01-01”
}’
# 搜索文档
curl -X GET “localhost:9200/my-index/_search” -H “Content-Type: application/json” -d ‘{
“query”: {
“match”: {
“content”: “search engine”
}
}
}’
# 更新文档
curl -X PUT “localhost:9200/my-index/_doc/1” -H “Content-Type: application/json” -d ‘{
“title”: “Elasticsearch Complete Guide”,
“content”: “Elasticsearch is a distributed search and analytics engine”,
“tags”: [“search”, “elasticsearch”, “analytics”],
“date”: “2023-01-01”
}’
# 删除文档
curl -X DELETE “localhost:9200/my-index/_doc/1”
“`
### 高级功能
“`bash
# 聚合查询
curl -X GET “localhost:9200/my-index/_search” -H “Content-Type: application/json” -d ‘{
“size”: 0,
“aggs”: {
“tag_count”: {
“terms”: {
“field”: “tags.keyword”
}
}
}
}’
# 复合查询
curl -X GET “localhost:9200/my-index/_search” -H “Content-Type: application/json” -d ‘{
“query”: {
“bool”: {
“must”: [
{“match”: {“content”: “elasticsearch”}}
],
“filter”: [
{“range”: {“date”: {“gte”: “2022-01-01”}}}
]
}
}
}’
“`
## 应用场景
– **全文搜索**:网站搜索、文档搜索
– **日志分析**:日志收集、分析和可视化
– **安全分析**:安全事件监控和分析
– **业务分析**:业务数据的分析和洞察
– **实时监控**:系统和应用的实时监控
– **地理空间搜索**:基于地理位置的搜索和分析
– **内容推荐**:个性化内容推荐
## 优势
– **高性能**:快速的搜索和分析能力
– **可扩展性**:水平扩展,处理海量数据
– **可靠性**:高可用性设计,数据复制和故障转移
– **灵活性**:支持多种数据类型和查询方式
– **生态系统**:丰富的生态系统,包括Kibana、Logstash等
– **易于集成**:提供RESTful API和多种语言的客户端
Elasticsearch已经成为现代企业级搜索和分析的标准解决方案,被广泛应用于各种场景,特别是需要实时搜索和分析的应用中。