使用类名称进行动态索引命名

问题描述 投票:0回答:1

我正在为spring-data-elasticsearch创建一个框架作为练习项目。我的问题是关于@Document标记,它将根据注释的indexName参数中提供的名称创建索引。

但是,我在想它是否有可能让它变得动态!在我的大多数用例中,索引名称将与类名匹配。我的所有索引类都将扩展一个抽象类,该类具有通用实现,需要在实体类中完成所有特定实现。

这意味着,我必须为每个实体维护@Document注释。但由于所有实体都将扩展特定的抽象类,是否可以注释抽象类,并以某种方式告诉spring使用类名作为索引名。

import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "BaseClassName OR something like Animal.getName" /*And other index properties of-course*/)
abstract class Animal {
String name;

public String getName() {
    return name;
}

public abstract String makeSomeNoise();
}

扩展动物的所有具体类都将在Elasticsearch中编入索引。

abstract class TwoLeggedAnimals extends Animal {}

abstract class FourLeggedAnimals extends Animal {}

以上两个只是分组类。为了这个例子

class Duck extends TwoLeggedAnimals {
public Duck() {
    this.name = Duck.class.getSimpleName();
}
@Override
public String makeSomeNoise() {
    return "quack";
}
}

Class Duck扩展了TwoLeggedAnimals,后者又扩展了“Animals”类,因此Duck有资格创建索引。马类的解释相同

class Horse extends FourLeggedAnimals {
Horse() {
    this.name = Horse.class.getSimpleName();
}

@Override
public String makeSomeNoise() {
    return "neigh";
}
}
java elasticsearch spring-data-elasticsearch
1个回答
0
投票

您没有写出您的具体问题或错误以及您正在使用的ES版本。

您可以将带有索引名称的@Document注释放在抽象基类上,然后使用派生类将您的entites存储到索引中,而无需在派生类上添加一些注释;这没有问题。

但是自从Elasticsearch 6.0(参见TwoLeggedAnimals)以来,您无法在同一索引中存储不同类型(如FourLeggedAnimalsES 6.0 breaking changes)。只要您使用一种类型,您的程序就会正常工作,只要您尝试存储第二种类型,您就可以获得

Elasticsearch异常[type = illegal_argument_exception,reason =拒绝映射更新到[animals],因为最终映射将有多于1种类型:[twoleggedanimal,fourleggedanimal]]

最后的5.x版本5.6支持到2019-03-11(Elastic end of life dates),因此不再支持。

因此,由于无法在索引中存储多种类型,因此您必须重新考虑您的类以及如何存储它们 - 请检查ES removal of types,如果其中列出的替代方案可能对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.