使用Elasticsearch在同一索引中区分不同类型的文档

在使用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版本,灵活性更高,但需要在文档设计和查询时额外注意区分。

如果对你有帮助的话点个赞呗~

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦境游子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值