在Elasticsearch中为现有索引添加新字段


Add new field to existing index in Elasticsearch

我创建了一个名为users的弹性搜索索引,如下所示:

$response = $client->index([
        'index' => 'users',
        'type' => 'user',
        'id' => Auth::user()->id,
        'body' => [
            'username' => Auth::user()->username,
            'name' => Auth::user()->name,
            'city' => Auth::user()->getCity(),
        ],
    ]);

我已经索引了一些数据。我想给这个索引添加一个名为"location"的新字段,这样它现在将是:

$response = $client->index([
        'index' => 'users',
        'type' => 'user',
        'id' => Auth::user()->id,
        'body' => [
            'username' => Auth::user()->username,
            'name' => Auth::user()->name,
            'city' => Auth::user()->getCity(),
            'location' => [$origin],
        ],
    ]);

我的问题是如何将该字段添加到已经存在的数据。我已经有了用户,但是没有位置字段。我需要将该字段添加到旧用户数据中,以便当用户更新他们的信息时,他们不会得到任何分片丢失错误

{"error":{"root_cause":[{"type":"document_missing_exception","reason":"[user][130]: document missing","shard":"0","index":"users"}],"type":"document_missing_exception","reason":"[user][130]: document missing","shard":"0","index":"users"},"status":404}

我不知道为什么你会看到碎片丢失错误这样的东西。使用Elasticsearch,默认情况下映射是动态的(参见动态映射)。这意味着您应该能够访问索引API,将新的位置信息添加到现有的和新的用户文档中,并能够搜索这些信息。

这样做的缺点是,您可能已经索引了一个文档,其中的位置信息在映射中被分配了某种类型,而后续文档的位置信息与该类型不匹配(请参阅字段数据类型)。也许,你可能想要对Elasticsearch映射有一个很好的控制,以避免遇到这样的问题,或者问题完全是别的什么。

编辑:根据最近关于document_missing_exception的问题中提供的更多细节,这不是那么相关。

您可以通过使用Update API

来实现这一点

如果这是一个新的索引-更新将失败。

为了避免这种情况-使用upsert

如果希望用已经索引的数据填充字段,则应该创建一个具有所需映射的新索引,并重新索引所有数据。一个很好的例子显示在https://www.youtube.com/watch?v=YSd1aV3iVhM&list=PL_mJOmq4zsHbcdoeAwNWuhEWwDARMMBta&index=23