检索Copy_to / Stored字段

时间:2019-10-18 00:27:09

标签: elasticsearch

我通过更改下面的映射,从现有字段创建了一个copy_to字段:

{
  "properties": {
    "ExistingField": {
      "type": "date",
      "copy_to": "CopiedField"
    },
    "CopiedField": {
      "type": "date",
      "store": true
    }
  }
}

我使用了“ store”:“ true”,因为我希望在执行搜索时可以检索到新的字段值。带有“ CopiedField”的聚合工作正常,但是当我尝试在这个新的CopiedField中搜索值时,我看不到正在检索的任何内容:

{
  "stored_fields": [
      "CopiedField"
     ],
  "query": {
  "match_all": {}
  }
}

如何通过简单的搜索检索“ CopiedField”的值?

1 个答案:

答案 0 :(得分:0)

无法更改现有字段的映射。 您将需要创建一个新索引(具有正确的映射)并将文档从旧索引移到新索引。您可以删除旧索引并使用别名,以便不更改索引名称

  1. (映射)[https://www.elastic.co/blog/changing-mapping-with-zero-downtime]
  2. (重新索引)[https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html]
  3. (别名)[https://www.elastic.co/guide/en/elasticsearch/reference/6.2/indices-aliases.html] 例如

具有以下映射的旧索引index35

PUT index35
{
  "mappings": {
  "properties": {
    "ExistingField": {
      "type": "date"
    }
  }
 }
}

查询:以下查询不会返回任何内容

GET index35/_search
{
  "stored_fields": [
    "CopiedField"
  ],
  "query": {
    "match_all": {}
  }
}

创建新索引

PUT index36
{
  "mappings": {
    "properties": {
      "ExistingField": {
        "type": "date",
        "copy_to": "CopiedField"
      },
      "CopiedField": {
        "type": "date",
        "store": true
      }
    }
  }
}

将旧文档移动到新文档

POST _reindex
{
  "source": {
    "index": "index35"
  },
  "dest": {
    "index": "index36"  ----> must be created before reindex
  }
}

确保新旧索引中的文档计数相同(以防止数据丢失)

删除旧索引:-删除索引35

为新索引(赋予旧名称)创建别名,以使搜索查询不受影响

POST /_aliases
{
    "actions" : [
        { "add" : { "index" : "index36", "alias" : "index35" } }
    ]
}

旧查询现在将返回结果