java – 如何使用Spring数据与弹性搜索别名进行交互

前端之家收集整理的这篇文章主要介绍了java – 如何使用Spring数据与弹性搜索别名进行交互前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
嗨,我正在使用弹性搜索 Spring数据.我的项目的域结构不断变化.所以我必须删除索引才能每次更改映射.为了解决这个问题,我正在使用别名.
我用以下方法创建了一个Alias: @H_404_3@elasticsearchTemplate.createIndex(Test.class); elasticsearchTemplate.putMapping(Test.class); String aliasName = "test-alias"; AliasQuery aliasQuery = new AliasBuilder() .withIndexName("test") .withAliasName(aliasName).build(); elasticsearchTemplate.addAlias(aliasQuery);

我有一个测试类:

@H_404_3@import org.springframework.data.annotation.Id import org.springframework.data.elasticsearch.annotations.Document import org.springframework.data.elasticsearch.annotations.Field import org.springframework.data.elasticsearch.annotations.FieldIndex import org.springframework.data.elasticsearch.annotations.FieldType import org.springframework.data.elasticsearch.annotations.Setting @Document(indexName = "test",type = "test") @Setting(settingPath = 'elasticSearchSettings/analyzer.json') class Test extends BaseEntity{ @Id @Field(type = FieldType.String,index = FieldIndex.not_analyzed) String id @Field(type = FieldType.String,index = FieldIndex.analyzed,indexAnalyzer = "generic_analyzer",searchAnalyzer = "generic_analyzer") String firstName }

TestRepository类:

@H_404_3@package com.as.core.repositories import com.as.core.entities.Test import org.springframework.data.elasticsearch.repository.ElasticsearchRepository interface TestRepository extends ElasticsearchRepository<Test,String> { }

我的问题是如何从别名而不是索引本身读取?
写操作是否也发生在别名上.
我查看了以下链接
https://www.elastic.co/guide/en/elasticsearch/guide/current/index-aliases.html#index-aliases
它说我们将不得不交换别名而不是实际索引.如何使用Elasticsearch Spring数据Java API实现这一点.

解决方法

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

它的工作方式是创建自定义存储库接口.在你的情况下,它将是TestRepositoryCustom:

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

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

@H_404_3@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 repsitory接口TestRepository中,扩展TestRepositoryCustom接口,以便从您的存储库bean访问自定义接口上的任何方法.

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

我真的希望看到的是对实体的注释,如:

@H_404_3@@Document(aliasName="test-alias")

这将在后台工作,以提供从门上搜索此索引,以便所有jpa查询都可以正常工作,无论索引名称如何.

猜你在找的Java相关文章