如何按_id对elasticsearch数据进行排序

qlckcl4x  于 7个月前  发布在  ElasticSearch
关注(0)|答案(1)|浏览(103)

现在我有一个eleasticsearch已经存在的 IndexedDB ,_id值是“a:1”,“a:2”,“a:3”“a:100”,现在我想按_id desc对es索引数据进行排序。所以结果序列是这样的:a:100,a:3:a:2 a:1
我的elasticsearch版本是最新版本:8.10。在我执行查询语句后,有一个错误消息:

#! Loading the fielddata on the _id field is deprecated and will be removed in future versions. If you require sorting or aggregating on this field you should also include the id in the body of your documents, and map this field as a keyword field that has [doc_values] enabled

字符串
这是我的疑问句:

GET /my_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {"_doc": "desc"}
  ]
}


这是索引创建语句:

PUT /my_index
{
  "mappings": {
    "properties": {
      "name": {"type": "text"},
      "age": {"type": "integer"},
      "type": {"type": "keyword"}
    }
  }
}


看到错误消息后,我修改了索引创建语句:

PUT /my_index
{
  "mappings": {
    "properties": {
      "_id": {"type": "keyword", "copy_to":"id"},
      "id": {"type": "keyword", "store":true},
      "name": {"type": "text"},
      "age": {"type": "integer"},
      "type": {"type": "keyword"}
    }
  }
}


那么它也有错误。
因为elasticsearch中已有的数据库,“_id”字段的值以“string:integer”的方式增加。所以我想按“_id”字段对搜索结果进行排序,但新的elasticsearch版本不允许这样做,所以我不知道如何实现

7xzttuei

7xzttuei1#

您不能在Map中声明_id字段。您只能声明一个自定义的id字段,在索引文档时也将其用作ID。一旦您这样做,您就可以根据需要按ID排序:
首先使用id关键字字段创建Map:

PUT /my_index
{
  "mappings": {
    "properties": {
      "id": {"type": "keyword"},
      "name": {"type": "text"},
      "age": {"type": "integer"},
      "type": {"type": "keyword"}
    }
  }
}

字符串
然后,当索引您的数据时,也将您的ID包含在文档中:

PUT my-index/_doc/a:1
{
   "id": "a:1",
   ...
}
PUT my-index/_doc/a:2
{
   "id": "a:2",
   ...
}

...

PUT my-index/_doc/a:3
{
   "id": "a:3",
   ...
}


最后,您将能够在id字段上进行排序

GET /my_index/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {"id": "desc"}
  ]
}

**UPDATE:**如果您无法控制摄取过程,您仍然可以使用_update_by_query API更新索引:

POST my_index/_update_by_query?wait_for_completion=false
{
  "script": { 
    "source": "ctx._source.id = ctx._id"
  }
}


运行update by query之前,您需要确保将id字段作为关键字添加到您的Map中。当此过程完成时,您的所有文档都将具有一个id字段,您可以使用该字段对数据进行排序。
如果一直有新数据进来,你需要设置一个额外的摄取管道,以便在新文档被索引时动态创建这个新字段。如果你需要了解更多关于如何设置的信息,请告诉我。

相关问题