做网站和商城有什么好处,网站建设 app开发网站,和平手机网站建设,开放平台是干什么的在使用Elasticsearch时#xff0c;有时我们需要在同一个索引中存放不同类型的文档#xff0c;并且这些文档的字段可能不一致。在早期版本中#xff0c;我们可以使用types来实现#xff0c;但在Elasticsearch 7.x及更高版本中#xff0c;types概念已被弃用。本文将介绍如何…在使用Elasticsearch时有时我们需要在同一个索引中存放不同类型的文档并且这些文档的字段可能不一致。在早期版本中我们可以使用types来实现但在Elasticsearch 7.x及更高版本中types概念已被弃用。本文将介绍如何在新的版本中使用标识字段和索引别名来实现这一需求。
一、创建索引和添加映射
首先我们需要创建一个索引并定义映射以包含不同类型文档的字段。
PUT /my_test_index
{mappings: {properties: {doc_type: { type: keyword },field1: { type: text },field2: { type: integer },fieldA: { type: text },fieldB: { type: date }}}
}参考官方文档Mapping - Elasticsearch
二、添加文档
接下来我们添加一些文档并在每个文档中使用doc_type字段来标识文档类型。以下是一些包含假数据的文档示例
POST /my_test_index/_doc/1
{doc_type: type1,field1: 值1,field2: 10
}POST /my_test_index/_doc/2
{doc_type: type2,fieldA: 值A,fieldB: 2023-06-16
}POST /my_test_index/_doc/3
{doc_type: type1,field1: 值2,field2: 20
}POST /my_test_index/_doc/4
{doc_type: type2,fieldA: 值B,fieldB: 2023-06-17
}参考官方文档Create Index - Elasticsearch
三、使用标识字段进行查询
在创建别名之前我们可以直接使用doc_type字段进行查询
查询类型为type1的文档
GET /my_test_index/_search
{query: {term: { doc_type: type1 }}
}查询类型为type2的文档
GET /my_test_index/_search
{query: {term: { doc_type: type2 }}
}参考官方文档Query DSL - Elasticsearch
四、创建索引别名并添加过滤器
为了方便查询我们可以为索引创建别名并为别名添加过滤器这样可以在逻辑上将一个索引分成多个“虚拟索引”。
POST /_aliases
{actions: [{add: {index: my_test_index,alias: type1_index,filter: { term: { doc_type: type1 } }}},{add: {index: my_test_index,alias: type2_index,filter: { term: { doc_type: type2 } }}}]
}参考官方文档Index Aliases - Elasticsearch
五、查询文档
我们可以使用别名来查询不同类型的文档这样可以有效地区分和管理不同类型的数据。
查询类型为type1的文档
GET /type1_index/_search
{query: {match_all: {}}
}查询类型为type2的文档
GET /type2_index/_search
{query: {match_all: {}}
}六、对比新的做法和老的做法
在Elasticsearch 6.x及之前版本中我们可以使用types来区分不同类型的文档
PUT /my_index
{mappings: {type1: {properties: {field1: { type: text },field2: { type: integer }}},type2: {properties: {fieldA: { type: text },fieldB: { type: date }}}}
}然而在Elasticsearch 7.x中types概念被移除了推荐使用标识字段和索引别名的方式来管理和区分不同类型的文档。
老的做法 使用多个types在同一个索引中区分文档。优点是直观且易于管理但已被弃用。
新的做法 使用标识字段和索引别名来管理不同类型的文档。优点是符合最新的Elasticsearch版本灵活性更高但需要在文档设计和查询时额外注意区分。
如果对你有帮助的话点个赞呗~