Elasticsearch 创建索引
创建索引需要通常需要指定三部分内容:
- settings:索引配置,如索引分片数、副本数、索引刷新时长等
- mappings:索引字段的映射(mapping)
- aliases:索引的别名
{
"settings": {},
"mappings": {},
"aliases": {}
}
创建索引
创建一个简单的索引,这是一个 2 分片(node)1 副本(replica)的索引,别名是 product
,索引包含一个 name
字段,该字段在索引时被分词可以支持全文搜索。
PUT product_2024xxxx
{
"settings": {
"number_of_shards": 2,
"number_of_replicas": 1,
"refresh_interval": "1s"
},
"mappings": {
"properties": {
"name": {
"type": "text",
"analyzer": "standard"
}
}
},
"aliases": {
"product":{}
}
}
注意
- 索引在创建后分片数无法修改,副本数可以修改
- Mapping 字段在创建后不允许更改名称和类型,除非 Reindex
更新 settings
更新索引刷盘间隔。
PUT product_2024xxxx/_settings
{
"refresh_interval": "2s"
}
更新 Mapping,添加字段
添加一个整数类型的 age
:
PUT product_2024xxxx/_mapping
{
"properties":{
"age":{
"type": "integer"
}
}
}
删除索引
DELETE product_2024xxxx
索引别名
别名(alias)可以给一组索引命名,然后在查询中统一查询他们,适当使用别名可以提高系统的可维护性。
给索引添加一个别名:
PUT product_2024xxxx/_alias/alias2
原子批量操作索引。添加 alias2
然后删除 alias1
:
POST _aliases
{
"actions": [
{
"add": {
"index": "product_2024xxxx",
"alias": "alias2"
}
},
{
"remove": {
"index": "product_2024xxxx",
"alias": "alias1"
}
}
]
}
- [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