摘要
本文介绍Elasticsearch的作用,基本结构,应用场景,常用注解,基本增删改查Restful写法。
认识ES
ES是一款开源的高扩展的分布式全文检索搜索型数据库。
特点
- 底层语言:Apache Lucene
- 组成部分:索引(类比db索引)、类型(类比db表)、文档(类比db数据)
- 存储形式:json格式,内容分词后建立反向索引进行存储
- 核心机制:倒排索引,通过拆分内容,对比关键字找完整内容
- 常见生态:ELK(logstash日志数据收集 + ES数据存储 + kibana可视化分析)
- 应用场景:全文搜索、日志管理、实时数据分析、复杂数据存储
常用注解
//=====用于类上
// indexName指定索引名 createIndex标记是否在存储库引导时创建索引。默认值为 true
@Document(indexName = "my_book", createIndex = true)
//指定索引级别的 settings(分片、分析器等)
@Setting(settingPath = "/settings/book.json")
//指定索引级别的 mapping(字段映射)
@Mapping(mappingPath = "/mappings/book.json")
//=====用于字段上
//标记主键字段 对应ES的_id
@Id
//type指定字段类型;analyzer指定自定义分析器和规范化器,使用IK分词器
@Field(type = FieldType.Text, analyzer = "ik_max_word")
@Field(type = FieldType.Keyword)
@Field(type = FieldType.Double)
//format指定内置日期格式
@Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second)
//标记创建日期字段
@CreatedDate
//标记地理坐标字段(经纬度)
@GeoPointField
//=====用于启动类上
//启用Repository自动扫描
@EnableElasticsearchRepositories(basePackages = "org.coffeebeans.entity")
Restful风格增删改查
1)创建索引
创建一个index_name索引,设置索引分片数为2,分片副本数为1,设置属性name类型为长文本,属性age类型为整型
PUT /<index_name>
{
"settings":{
"number_of_shards":2,
"number_of_replicas":1
},
"mappings":{
"properties":{
"name":{"type":"text"},
"age":{"type":"integer"}
}
}
}
使用IK分词器创建索引(预先安装IK插件)
PUT /book
{
"settings": {
"number_of_shards": 2,
"number_of_replicas": 1,
"analysis": {
"analyzer": {
"ik_max_word": {
"type": "custom",
"tokenizer": "ik_max_word"
}
}
}
},
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "ik_max_word"
},
"author": {
"type": "keyword"
},
"content": {
"type": "text",
"analyzer": "ik_max_word"
},
"price": {
"type": "double"
},
"location": {
"type": "geo_point"
},
"createTime": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd'T'HH:mm:ss||strict_date_optional_time"
}
}
}
}
2)添加文档
指定索引插入文档
PUT必须指定document_id,document_id存在就会修改这个数据
PUT /<index_name>/_doc/<document_id>
{
"name": "Alice",
"age": 25
}
POST不指定document_id时会自动生成document_id,指定document_id时如果document_id存在就会修改这个数据,并新增版本号_version
POST /<index_name>/_doc/<document_id>
{
"name": "Alice",
"age": 33
}
3)查询文档
通过文档id查
GET /<index_name>/_doc/<document_id>
4)更新文档
更改指定文档id的对应属性内容
POST /<index_name>/_update/<document_id>
{
"doc": {
"age": 26
}
}
5)删除文档
删除指定文档
DELETE /<index_name>/_doc/<document_id>
6)删除索引
删除指定索引,包括索引下的所有内容
DELETE /<index_name>
总结
以上我们了解了Elasticsearch是由Lucene演变而来的一种支持Restful风格增删改查的开源分布式全文检索数据库,数据结构由索引、类型、文档共同组成,支持分词检索,快速响应,倒排索引。
关注公众号:咖啡Beans
在这里,我们专注于软件技术的交流与成长,分享开发心得与笔记,涵盖编程、AI、资讯、面试等多个领域。无论是前沿科技的探索,还是实用技巧的总结,我们都致力于为大家呈现有价值的内容。期待与你共同进步,开启技术之旅。