Elasticsearch索引的基本操作(5)-别名设置

Elasticsearch索引别名设置全解析
本文详细介绍了Elasticsearch中的别名,包括索引别名、过滤器别名和路由别名。阐述了索引别名在索引迁移、分组管理等场景的应用,还介绍了索引别名的增加、删除、重命名和查看操作。同时说明了过滤器别名和路由别名的特点及操作方式。

1、别名

Elasticsearch中的别名,可以分为索引别名、过滤器别名、路由别名等,不同的别名适用于不同的应用场景:

  • 索引别名就是给一个或几个索引重新定义一个名字,操作索引别名时会转化为对真实索引的操作,定义索引别名时不可以与真实的索引同名;
  • 过滤器别名提供了一种创建同一索引的不同“视图”的简便方法,可以使用Query DSL定义过滤器,并使用此别名将其应用于所有“搜索”,“计数”,“按查询删除”和“更多此类操作”;
  • 路由别名,将路由字段绑定到对应的别名,通过该别名操作时,会执行默认的路由规则,也可以理解为索引的另外一种“视图”;

1.1、索引别名

索引别名,可以应用于以下场景:

  • 将正常运行集群中的索引迁移到另外一个索引,无须停机操作;
  • 将多个索引进行分组,以便于更好的管理;
  • 给索引创建类似于视图的子集;

1.1.1、增加别名

给单个索引增加别名

为索引new_index定义别名new_index_alias,操作如下:

GET /new_index/_alias/new_index_alias

或执行如下操作:

POST /_aliases

{

    "actions" : [

        { "add" : { "index" : "new_index", "alias" : "new_index_alias" } }

    ]

}

 

给多个索引增加相同的别名

给索引new_index和new_index_2增加相同的别名new_index,操作如下:

POST /_aliases

{

    "actions" : [

        { "add" : { "index" : "new_index", "alias" : "new_index_alias" } },

        { "add" : { "index" : "new_index_2", "alias" : "new_index_alias" } }

    ]

}

也可以按以下的方式操作:

POST /_aliases

{

  "actions": [

    {

      "add": {

        "indices": [ "new_index","new_index_2" ],

        "alias": "new_index_alias"

      }

    }

  ]

}

 

 

​​​​​​​给多个索引增加不同的别名

给索引new_index和new_index_2分别增加相同的别名new_index_alias和new_index_alias_2,操作如下:

POST /_aliases

{

    "actions" : [

        { "add":{ "index" : "new_index", "alias" : "new_index_alias" } },

        { "add":{ "index" : "new_index_2", "alias" : "new_index_alias_2" } }

    ]

}

 

根据索引通配符创建别名

创建所有以new_index开头的别名new_index_alias,操作如下:

POST /_aliases

{

    "actions" : [

        { "add" : { "index" : "new_index*", "alias" : "new_index_alias" } }

    ]

}

 

​​​​​​​使用指向多个索引的别名执行索引操作

指向多个索引的别名,用于执行查询不需要做额外的设置,如果需要用于执行索引操作,则需要在被指向的多个索引中指定用于执行索引操作的索引,否则报错误。

如别名new_index_alias是索引new_index和new_index_2的别名,此时没有在new_index和new_index_2中指定哪个用于执行索引操作,则执行以下操作时:

POST /new_index_write/_doc

{

  "title": "Alias for multi index write test",

  "name": "Alias"

}

会报如下错误:

{

  "error": {

    "root_cause": [

      {

        "type": "illegal_argument_exception",

        "reason": "no write index is defined for alias [new_index_write]. The write index may be explicitly disabled using is_write_index=false or the alias points to multiple indices without one being designated as a write index"

      }

    ],

    ...

  "status": 400

}

 

这种情况需要通过设置is_write_index属性来指定哪个索引可用于执行索引操作,重新建立别名,操作如下:

POST /_aliases

{

  "actions": [

    {

      "add": {

        "index": "new_index",

        "alias": "new_index_write",

        "is_write_index": true

      }

    },

    {

      "add": {

        "index": "new_index_2",

        "alias": "new_index_write",

        "is_write_index": false

      }

    }

  ]

}

 

设置好后再执行索引上面的索引操作,就不会报错了。

​​​​​​​1.1.2、​​​​​​​删除别名

删除单个索引别名

删除索引new_index上的别名new_index_alias,操作如下:

DELETE /new_index/_alias/new_index_alias

POST /_aliases

{

    "actions" : [

        { "remove" : { "index" : "new_index", "alias" : "new_index_alias" } }

    ]

}

 

​​​​​​​删除多个索引别名

同时删除索引new_index和new_index_2上的别名new_index_alias,操作如下:

#多个索引以英文逗号“,”分隔

DELETE /new_index,new_index_2/_alias/new_index_alias

POST /_aliases

{

    "actions" : [

        { "remove" : { "index" : "new_index", "alias" : "new_index_alias" } },

        { "remove":{"index" : "new_index_2", "alias" : "new_index_alias" } }

    ]

}

 

同时删除索引new_index的多个别名,多个别名以英文逗号“,”分隔,操作如下:

#多个别名以英文逗号“,”分隔

DELETE /new_index/_alias/new_index_alias_1,new_index_alias_2

 

​​​​​​​1.1.3、重命名别名

别名的重命名,是通过同时执行remove和add操作来实现的,该操作中的两个动作是原子性的,不会存在别名被删除的瞬间产生没有指向任何索引的问题。

以下将指向new_index的别名new_index_alias重新指向new_index_2,操作如下:

POST /_aliases

{

    "actions" : [

        { "remove" : { "index" : "new_index", "alias" : "new_index_alias" } },

        { "add" : { "index" : "new_index_2", "alias" : "new_index_alias" } }

    ]

}

1.1.4、索引别名查看

查看单个索引的别名

查看指定索引有哪些别名,如查看索引new_index有哪些别名,操作如下:

GET /new_index/_alias/*

返回如下:

{

  "new_index" : {

    "aliases" : {

      "new_index_alias" : { },

      "new_index_alias_1" : { }

    }

  }

}

返回显示索引new_index有new_index_alias和new_index_alias_1两个别名。

​​​​​​​查看多个索引的别名

在索引参数中,通过英文逗号“,”分隔多个索引的名称,操作如下:

GET /new_index,new_index_2/_alias/*

或者使用通配置符指定:

GET /new_index*/_alias/*

​​​​​​​确认别名是否存在

使用HEAD方法,可以检查别名是否存在。

检查指定别名是否属于某个索引,操作如下:

HEAD /new_index/_alias/new_index_route_alias

存在则返回“200 - OK”,不存在则返回“404 - Not Found”。

​​​​​​​1.2、过滤器别名

过滤器别名也是属于索引别名的一种,只是其包含了过滤条件,属于类似视图的别名。

索引new_index中有如下示例数据:

此处创建一个过滤器别名,通过该别名只会查看到name为”Feng”的数据,操作如下:

POST /_aliases

{

  "actions": [

    {

      "add": {

        "index": "new_index",

        "alias": "new_index_feng_alias",

        "filter": { "term": { "name": "feng" } }

      }

    }

  ]

}

此处为索引new_index定义了一个名为new_index_feng_alias的过滤器别名,过滤条件为name的值为”feng”,后续直接使用该别名执行查询时,即使不带任何条件,也只会过滤出name的值为”feng”的数据,验证操作如下:

GET /new_index_feng_alias/_search

​​​​​​​1.3、路由别名

用于给查询和索引操作的路由字段指定别名,可统一指定也可以分别指定,操作方式和过滤器别名一样,也可以理解为索引的另外一种视图。

​​​​​​​​​​​​​​统一定义查询和索引操作的路由别名

以下定义了索引new_index的路由别名new_index_route_alias,使用字母“a”做为路由值,操作如下:

POST /_aliases

{

    "actions" : [

        {

            "add" : {

                 "index" : "new_index",

                 "alias" : "new_index_route_alias",

                 "routing" : "a"

            }

        }

    ]

}

 

​​​​​​​分别给查询和索引操作定义不同的路由值

以下定义了索引new_index的路由别名new_index_route_alias_2,使用字母“a”做为索引路由值,使用字母“a,b”做为查询路由,操作如下:

POST /_aliases

{

    "actions" : [

        {

            "add" : {

                 "index" : "new_index",

                 "alias" : "new_index_route_alias_2",

                 "index_routing":"a",

                 "search_routing" : "a,b"

            }

        }

    ]

}

注:查询路由可以包含多个值,以英文逗号“,”做为分隔,但是索引路由只能够是单一值。

 

​​​​​​​使用路由别名执行查询且指定了路由字段

有时在使用路由别名执行查询查询操作时,又同时通过参数的方式指定路由字段,如下查询示例:

GET /new_index_route_alias/_search?q=name:feng&routing=b,c

这种情况下,路由值就会取当前参数指定的值由与路由别名中定义的路由值的交集,当前示例就会取“b”做为查询路由值。

<think> 我们正在使用Elasticsearch的Java客户端,想要通过索引模板来实现自动创建索引。根据引用内容,我们可以了解到创建索引的基本方法,但关于索引模板的使用需要更具体的步骤。 索引模板(Index Template)允许我们定义在创建新索引时自动应用的设置、映射和别名。当新索引的名称与模板中定义的模式匹配时,Elasticsearch会自动应用该模板。 在Java客户端中,我们可以使用`RestHighLevelClient`(旧版)或新的Java客户端`ElasticsearchClient`(新版)来创建索引模板。由于引用中提到了`ElasticsearchTemplate`(属于Spring Data Elasticsearch),但我们的需求是直接使用elasticsearch-java(即官方Java客户端),因此我们将使用官方客户端的方式。 以下步骤基于Elasticsearch Java客户端(8.x版本)进行操作: 1. 创建索引模板请求(CreateIndexTemplateRequest)。 2. 设置模板的索引模式(例如"logs-*")。 3. 配置模板的设置(settings)和映射(mappings)。 4. 执行创建索引模板的请求。 注意:自动创建索引通常依赖于索引模板和索引名称的匹配。当我们向一个匹配模板模式的索引写入文档时,如果该索引不存在,Elasticsearch会自动创建该索引并应用模板。 以下是一个示例代码: ```java import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.indices.CreateIndexTemplateRequest; import co.elastic.clients.elasticsearch.indices.IndexTemplate; import co.elastic.clients.elasticsearch.indices.PutIndexTemplateRequest; import co.elastic.clients.elasticsearch.indices.put_index_template.IndexTemplateMapping; import co.elastic.clients.json.JsonData; import co.elastic.clients.json.JsonpMapper; import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.rest_client.RestClientTransport; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import java.io.IOException; import java.util.Collections; public class IndexTemplateExample { public static void main(String[] args) throws IOException { // 创建低级客户端 RestClient restClient = RestClient.builder( new HttpHost("localhost", 9200) ).build(); // 使用Jackson映射器创建传输层 JsonpMapper mapper = new JacksonJsonpMapper(); ElasticsearchTransport transport = new RestClientTransport(restClient, mapper); // 创建Java API客户端 ElasticsearchClient client = new ElasticsearchClient(transport); // 定义索引模板 PutIndexTemplateRequest request = PutIndexTemplateRequest.of(builder -> builder .name("my-template") // 模板名称 .indexPatterns(Collections.singletonList("logs-*")) // 匹配的索引模式 .template(IndexTemplate.of(it -> it .settings(settings -> settings .numberOfShards("3") .numberOfReplicas("1") ) .mappings(mappings -> mappings .properties("timestamp", property -> property .date(date -> date.format("epoch_millis")) ) .properties("message", property -> property .text(text -> text) ) ) )) ); // 执行创建索引模板 client.indices().putIndexTemplate(request); // 关闭客户端 transport.close(); restClient.close(); } } ``` 解释: - 我们创建了一个名为`my-template`的索引模板,它匹配所有以`logs-`开头的索引- 在模板中,我们定义了索引设置(3个主分片,1个副本)和映射(两个字段:`timestamp`和`message`)。 - 当向一个匹配`logs-*`模式的索引(例如`logs-2023`)写入文档时,如果该索引不存在,Elasticsearch会自动创建索引并应用模板中的设置和映射。 注意:以上代码使用了Elasticsearch Java客户端8.x的构建器模式。如果你使用的是旧版(7.x)的RestHighLevelClient,则写法会有所不同。 另外,引用[3]中提到了使用`ElasticsearchTemplate`(Spring Data Elasticsearch)来创建索引和映射。但我们的需求是使用索引模板,因此直接使用Java客户端API。 参考文献: [^1]: 提供了Java操作ES自动创建索引的一般步骤,但未涉及模板。 [^2]: 介绍了使用Java创建索引并写入数据,但同样没有具体讲模板。 [^3]: 展示了使用Spring Data Elasticsearch的`ElasticsearchTemplate`创建索引和映射,但未使用模板。 [^4]: 提到了Client对象的异步操作,但未涉及模板。 因此,我们根据官方文档和Java客户端的使用方法,编写了上述代码。 相关问题: 1. 如何验证索引模板是否创建成功? 2. 除了使用索引模板,还有其他方法实现自动创建索引吗? 3. 如何更新或删除一个已存在的索引模板? </think> 在 Java 中使用 Elasticsearch 索引模板实现自动创建索引,主要步骤如下: ### 1. 创建索引模板 使用 `PutIndexTemplateRequest` 定义索引模板,指定匹配规则和映射配置: ```java PutIndexTemplateRequest request = PutIndexTemplateRequest.of(b -> b .name("my-template") // 模板名称 .indexPatterns("logs-*") // 匹配以"logs-"开头的索引 .template(t -> t .settings(s -> s .numberOfShards("3") .numberOfReplicas("1") ) .mappings(m -> m .properties("timestamp", p -> p.date(d -> d.format("epoch_millis"))) .properties("message", p -> p.text(tf -> tf)) ) ) ); client.indices().putIndexTemplate(request); ``` ### 2. 启用自动创建索引(可选) 在 `elasticsearch.yml` 配置文件中添加: ```yaml action.auto_create_index: "logs-*,+myapp-*" ``` ### 3. 数据写入触发创建 当写入匹配模板的索引时(如 `logs-2023`),Elasticsearch 会自动创建索引: ```java IndexResponse response = client.index(i -> i .index("logs-2023") // 匹配模板的索引名 .document(new LogEntry(...)) ); ``` ### 关键配置说明 | 配置项 | 说明 | |----------------|---------------------------------------------------------------------| | `indexPatterns` | 使用通配符(如`logs-*`)匹配需要自动创建的索引名称 | | `settings` | 定义分片数、副本数等索引设置 | | `mappings` | 定义字段类型和属性(如`text`/`date`等) | | 自动创建开关 | 通过`action.auto_create_index`控制允许自动创建的索引模式(默认开启)[^1] | > **注意**:索引模板仅在**新索引创建时**生效,已有索引不受影响。Java 客户端需使用 **7.15+** 或 **8.x** 版本(新API)[^2][^3]。 ### 验证模板是否生效 ```java GetIndexTemplateResponse resp = client.indices().getIndexTemplate( g -> g.name("my-template") ); System.out.println(resp.templates()); // 查看模板详情 ``` ### 常见问题解决 1. **模板未应用** - 检查索引名称是否匹配 `indexPatterns` - 确认模板创建时间早于索引创建时间 2. **客户端兼容性** 旧版 High-Level REST Client 使用 `RestHighLevelClient.putTemplate()`[^4],新版推荐使用 `ElasticsearchClient` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值