Elasticsearch 创建索引
创建索引通常需要指定三部分内容:
- settings:索引配置,如索引分片数、副本数、索引刷新时长等
- mappings:索引字段的映射(mapping)
- aliases:索引的别名
1{
2 "settings": {},
3 "mappings": {},
4 "aliases": {}
5}
创建索引
创建一个简单的索引:这是一个 2 分片、1 副本的索引,别名是 product。索引包含一个 name 字段,该字段在索引时会被分词,可以支持全文搜索。
1PUT product_2024xxxx
2{
3 "settings": {
4 "number_of_shards": 2,
5 "number_of_replicas": 1,
6 "refresh_interval": "1s"
7 },
8 "mappings": {
9 "properties": {
10 "name": {
11 "type": "text",
12 "analyzer": "standard"
13 }
14 }
15 },
16 "aliases": {
17 "product":{}
18 }
19}
注意
- 索引在创建后分片数无法修改,副本数可以修改
- Mapping 字段在创建后不允许更改名称和类型,除非 Reindex
更新 settings
更新索引刷盘间隔。
1PUT product_2024xxxx/_settings
2{
3 "refresh_interval": "2s"
4}
更新 Mapping,添加字段
添加一个整数类型的 age:
1PUT product_2024xxxx/_mapping
2{
3 "properties":{
4 "age":{
5 "type": "integer"
6 }
7 }
8}
删除索引
1DELETE product_2024xxxx
索引别名
别名(alias)可以给一组索引命名,然后在查询中统一查询它们,适当使用别名可以提高系统的可维护性。
给索引添加一个别名:
1PUT product_2024xxxx/_alias/alias2
原子批量操作索引。添加 alias2 然后删除 alias1:
1POST _aliases
2{
3 "actions": [
4 {
5 "add": {
6 "index": "product_2024xxxx",
7 "alias": "alias2"
8 }
9 },
10 {
11 "remove": {
12 "index": "product_2024xxxx",
13 "alias": "alias1"
14 }
15 }
16 ]
17}
- [1] index API https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices.html
- [2] create index https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-create-index.html
- [3] update settings https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-update-settings.html
- [4] update mapping https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-put-mapping.html
- [5] delted index https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-delete-index.html
- [6] alias https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-get-alias.html
- [7] add alias https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-add-alias.html
- [8] delete alias https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-delete-alias.html
- [9] automatic update alias https://www.elastic.co/guide/en/elasticsearch/reference/8.15/indices-aliases.html