您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用Spring数据与elasticsearch别名进行交互

如何使用Spring数据与elasticsearch别名进行交互

我通过在与对象相关联的存储库类中使用ElasticsearchTemplate来解决了这一限制(尽管如果有一种在实体本身上指定别名的方法会更好)。

它的工作方式是创建自定义存储库界面。在您的情况下,将为TestRepositoryCustom:

public interface TestRepositoryCustom
{
    Test> findByCustom(...);
}

然后实现此接口,在基本存储库名称的末尾附加“ Impl”:

public class TestRepositoryImpl implements TestRepositoryCustom
{
    Page<Test> findByCustom(Pageable pageable, ...)
    {
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();
        FilterBuilder filter = FilterBuilders.staticMethodsToBuildFilters;
        /*
         * Your code here to setup your query
        */

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder().withQuery(boolQuery).withFilter(filter).withPageable(pageable);

        //These two are the crucial elements that will allow the search to look up based on alias
        builder.withIndices("test-alias");
        builder.withTypes("test");

        //Execute the query
        SearchQuery searchQuery = builder.build();
        return elasticSearchTemplate.queryForPage(searchQuery, Test.class);
    }
}

最后,在基本的JPA代理接口TestRepository中,扩展TestRepositoryCustom接口,以从存储库bean访问自定义接口上的任何方法

public interface TestRepository extends ElasticsearchRepository<Consultant, String>, TestRepositoryCustom
{
}

我真正想看到的是对实体的注释,例如:

@Document(aliasName="test-alias")

这只会在后台工作,以提供对这个索引的搜索,因此无论索引名如何,所有jpa查询都将正常工作。

Java 2022/1/1 18:19:46 有393人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶