美文网首页
Spring ES动态索引

Spring ES动态索引

作者: 冰火人生 | 来源:发表于2018-05-11 19:37 被阅读0次

Spring ES动态索引

本文主要探讨Spring中利用spring-data-elasticsearch(以下简称sde)操作es时如何使用动态索引。

何为动态索引?

动态索引一个典型的场景是ES中索引按照时间划分,比如按天生成索引,那么生成的索引的名称就形如index_2018_05_11

SDE中的索引

sde中通过Document注解来制定索引名,该注解应用于Document的对象类上,其定义如下

@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Document {

    String indexName();

    String type() default "";

    boolean useServerConfiguration() default false;

    short shards() default 5;

    short replicas() default 1;

    String refreshInterval() default "1s";

    String indexStoreType() default "fs";

    boolean createIndex() default true;
}

来看下SDE中生成索引是如何做的

@Override
    public <T> boolean createIndex(Class<T> clazz) {
        return createIndexIfNotCreated(clazz);
    }

private <T> boolean createIndexIfNotCreated(Class<T> clazz) {
        return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz);
    }

    private <T> boolean createIndexWithSettings(Class<T> clazz) {
        if (clazz.isAnnotationPresent(Setting.class)) {
            String settingPath = clazz.getAnnotation(Setting.class).settingPath();
            if (isNotBlank(settingPath)) {
                String settings = readFileFromClasspath(settingPath);
                if (isNotBlank(settings)) {
                    return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings);
                }
            } else {
                logger.info("settingPath in @Setting has to be defined. Using default instead.");
            }
        }
        return createIndex(getPersistentEntityFor(clazz).getIndexName(), getDefaultSettings(getPersistentEntityFor(clazz)));
    }

可以看到上述代码中有一段出现了两次

getPersistentEntityFor(clazz).getIndexName()

来看看这段代码做了什么

@Override
    public ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) {
        Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + clazz.getSimpleName()
                + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
        return elasticsearchConverter.getMappingContext().getRequiredPersistentEntity(clazz);
    }

MappingContext#getRequiredPersistentEntity是个接口default方法

@Nullable
    E getPersistentEntity(Class<?> type);

    /**
     * Returns a required {@link PersistentEntity} for the given {@link Class}. Will throw
     * {@link IllegalArgumentException} for types that are considered simple ones.
     *
     * @see org.springframework.data.mapping.model.SimpleTypeHolder#isSimpleType(Class)
     * @param type must not be {@literal null}.
     * @return never {@literal null}.
     * @throws MappingException when no {@link PersistentEntity} can be found for given {@literal type}.
     * @since 2.0
     */
    default E getRequiredPersistentEntity(Class<?> type) throws MappingException {

        E entity = getPersistentEntity(type);

        if (entity != null) {
            return entity;
        }

        throw new MappingException(String.format("Couldn't find PersistentEntity for type %s!", type));
    }

getPersistentEntity则是在抽象类AbstractMappingContext中实现的

@Nullable
    public E getPersistentEntity(Class<?> type) {
        return getPersistentEntity(ClassTypeInformation.from(type));
    }
    
    @Nullable
    @Override
    public E getPersistentEntity(TypeInformation<?> type) {

        Assert.notNull(type, "Type must not be null!");

        try {

            read.lock();

             // 这里是直接从一个map的缓存中获取
            Optional<E> entity = persistentEntities.get(type);

            if (entity != null) {
                return entity.orElse(null);
            }

        } finally {
            read.unlock();
        }
        
        // 如果是java简单类则直接返回null
        if (!shouldCreatePersistentEntityFor(type)) {

            try {
                write.lock();
                persistentEntities.put(type, NONE);
            } finally {
                write.unlock();
            }

            return null;
        }

        if (strict) {
            throw new MappingException("Unknown persistent entity " + type);
        }

        return addPersistentEntity(type).orElse(null);
    }

addPersistentEntity代码太长就不贴了,重点是它调用了本类的抽象类方法

protected abstract <T> E createPersistentEntity(TypeInformation<T> typeInformation);

简单来说,addPersistentEntity方法就是为指定的typeInformation生成一个MutablePersistentEntity对象放置在一个自己持有的map中作为缓存。

createPersistentEntity有一个实现类SimpleElasticsearchMappingContext,该类比较简单就不多说了。

综上可知:如果我们在Document中写死了indexName显然是没法做到动态索引的,那我们能不能动态改被Document注解修饰的类定义呢(比如字节码修改类定义)?太费劲了,因为SDE中用到了缓存,即便我们修改了类定义还得自己去刷缓存,况且修改字节码还得引入第三方框架。

思考

翻翻源码可以看到ElasticSearchTemplate类中索引名都是通过ElasticsearchPersistentEntity.getIndexName来获取的。尽管框架缓存了ElasticsearchPersistentEntity实例,但是getIndexName是每次都要执行的,我们看能不能从这个方法着手。这个接口只有一个实现类-SimpleElasticSearchPersistentEntity,来看看它的getIndexName方法

@Override
    public String getIndexName() {
        Expression expression = parser.parseExpression(indexName, ParserContext.TEMPLATE_EXPRESSION);
        return expression.getValue(context, String.class);
    }

我们发现这个方法并不是简单的返回了indexName,而是用一个解析器去解析处理,最后才返回。再去看看这个parser是个啥

private final SpelExpressionParser parser;

原来是Spel表达式解析器,不清楚Spel的请自行搜索。思路很清晰了,那就是利用Spel实现我们想要的动态索引。

解决方案

Spel中调用方法

Spel十分强大,可以在表达式中直接调用Java方法,那我们就写个方法生成我们想要的索引名,放在Spel中调用就行了。

indexName表达式设置为 "index_#{ T(com.example.springdemo.SpringDemoApplicationTests).getDateStr() }"

public static String getDateStr() {
        return new DateTime().toString("yyyy-MM-dd");
    }

需要注意的是getDateStr方法必须为public静态方法,当然也可以扔到一个bean里去作为一个普通方法,Spel也是支持调用bean方法的。

引用Bean属性

可以将indexName作为一个bean的属性,然后在Spel中引用即可

其他

本文只谈论如何在SDE中解决动态索引的问题,当然java原生es jar中可直接指定索引名,而不是作为注解的一部分。SDE和原生es jar孰好孰坏本文不讨论。

相关文章

网友评论

      本文标题:Spring ES动态索引

      本文链接:https://www.haomeiwen.com/subject/cmrqdftx.html